@snyxex/pipex 0.0.0-stage → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +21 -0
  3. package/README.md +319 -2
  4. package/dist/compression-2mm0MhWY.mjs +1 -0
  5. package/dist/compression-CtrHxa9G.d.mts +38 -0
  6. package/dist/compression-DnVFu8TM.d.cts +38 -0
  7. package/dist/compression-DrgzribA.cjs +1 -0
  8. package/dist/compression.cjs +1 -0
  9. package/dist/compression.d.cts +2 -0
  10. package/dist/compression.d.mts +2 -0
  11. package/dist/compression.mjs +1 -0
  12. package/dist/core-BOdvxKBq.mjs +2 -0
  13. package/dist/core-B_z1gN5W.cjs +2 -0
  14. package/dist/dataEngine-4m6GTOLe.mjs +1 -0
  15. package/dist/dataEngine-Bvl6amzP.cjs +1 -0
  16. package/dist/dataEngine-D-fIXgE7.d.cts +232 -0
  17. package/dist/dataEngine-DUEmWp7a.d.mts +232 -0
  18. package/dist/encryption-BmmNECIc.d.cts +44 -0
  19. package/dist/encryption-CnSL1BEY.d.mts +44 -0
  20. package/dist/encryption-CqxtoqAD.mjs +1 -0
  21. package/dist/encryption-DdP1zFYl.cjs +1 -0
  22. package/dist/encryption.cjs +1 -0
  23. package/dist/encryption.d.cts +2 -0
  24. package/dist/encryption.d.mts +2 -0
  25. package/dist/encryption.mjs +1 -0
  26. package/dist/hashing-B6xGcbQR.d.mts +33 -0
  27. package/dist/hashing-ChrADfcH.mjs +1 -0
  28. package/dist/hashing-JtOHPybU.cjs +1 -0
  29. package/dist/hashing-LY-8x66g.d.cts +33 -0
  30. package/dist/hashing.cjs +1 -0
  31. package/dist/hashing.d.cts +2 -0
  32. package/dist/hashing.d.mts +2 -0
  33. package/dist/hashing.mjs +1 -0
  34. package/dist/index.cjs +1 -0
  35. package/dist/index.d.cts +302 -0
  36. package/dist/index.d.mts +302 -0
  37. package/dist/index.mjs +1 -0
  38. package/dist/kms.cjs +1 -0
  39. package/dist/kms.d.cts +3 -0
  40. package/dist/kms.d.mts +3 -0
  41. package/dist/kms.mjs +1 -0
  42. package/dist/kms_encryption-Da-KqjKI.d.mts +33 -0
  43. package/dist/kms_encryption-Dh1LEHhk.d.cts +33 -0
  44. package/dist/kms_encryption-R9auKGW4.mjs +1 -0
  45. package/dist/kms_encryption-xyWi65rZ.cjs +1 -0
  46. package/dist/native.cjs +1 -0
  47. package/dist/native.d.cts +2 -0
  48. package/dist/native.d.mts +2 -0
  49. package/dist/native.mjs +1 -0
  50. package/dist/parallel.cjs +1 -0
  51. package/dist/parallel.d.cts +2 -0
  52. package/dist/parallel.d.mts +2 -0
  53. package/dist/parallel.mjs +1 -0
  54. package/dist/plugin-C9Kd9coY.d.cts +16 -0
  55. package/dist/plugin-CE94-p8P.d.mts +16 -0
  56. package/dist/resourceLimits-C1HHDwXQ.mjs +1 -0
  57. package/dist/resourceLimits-CI0Qrqdf.cjs +1 -0
  58. package/dist/types-Bytga6zd.d.mts +155 -0
  59. package/dist/types-ia4x-Dvp.d.cts +155 -0
  60. package/dist/validation-CqmhNHdW.d.cts +32 -0
  61. package/dist/validation-D17IkoHy.d.mts +32 -0
  62. package/dist/validation-P5WRSAUK.mjs +1 -0
  63. package/dist/validation-pEeJmCad.cjs +1 -0
  64. package/dist/validation.cjs +1 -0
  65. package/dist/validation.d.cts +2 -0
  66. package/dist/validation.d.mts +2 -0
  67. package/dist/validation.mjs +1 -0
  68. package/dist/worker-CbuCpSNc.d.cts +37 -0
  69. package/dist/worker-CgCC-BWG.d.mts +37 -0
  70. package/dist/worker-I_kqxWeK.cjs +1 -0
  71. package/dist/worker-c0_VZ9c7.mjs +1 -0
  72. package/package.json +188 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,30 @@
1
+ # Changelog
2
+
3
+ Changes are documented here for users and downstream maintainers. Versioned releases are also listed under [GitHub Releases](https://github.com/Snyxex/PipeX/releases). This file is not a claim that the package has been published on npm.
4
+
5
+ ## Unreleased
6
+
7
+ - Maintained Jenkins CI now validates current Node.js 22, 24, and 26 lines.
8
+ - Release checks cover package tarballs, clean consumers, a dependency audit, and repository AI-skill validation.
9
+ - Added open-source security, contribution, conduct, and release documentation.
10
+ - Retired unused Docker-based CI scripts that still referenced Node.js 20.
11
+ - Prepared a minimal consumer-facing npm tarball with release metadata and verified packaging tests.
12
+
13
+ ## 1.0.2 — release candidate (not published to npm)
14
+
15
+ - Prepared the first npm distribution under the scoped name `@snyxex/pipex`; the unrelated unscoped `pipex` package is not this project.
16
+ - Kept the Standard Core ESM entrypoint and `@snyxex/pipex/plugins/kms` subpath, and aligned downstream examples and consumer tests.
17
+ - Added a protected, read-only release-candidate verification pipeline that audits dependencies, checks Git history, verifies packed consumers and archives the tarball digest.
18
+ - Fixed the GitHub dependency consumer smoke test by running a syntax-checked ESM fixture instead of an embedded import expression.
19
+ - Publication is pending separate verification and maintainer authorization.
20
+
21
+ ## [1.0.1] - 2026-09-12
22
+
23
+ - Improved reliability of KMS provider timeout handling.
24
+
25
+ ## [1.0.0] - 2026-09-12
26
+
27
+ - First stable Standard Core release, including bounded binary, stream and file transformations and security-focused plugin infrastructure.
28
+
29
+ [1.0.1]: https://github.com/Snyxex/PipeX/releases/tag/v1.0.1
30
+ [1.0.0]: https://github.com/Snyxex/PipeX/releases/tag/v1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Snyxex
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,320 @@
1
- # Temporary Holding Version
1
+ # PipeX
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ PipeX composes compression, authenticated encryption, and HMAC integrity checks into reversible data-processing pipelines for Node.js buffers, files, and streams.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@snyxex/pipex)](https://www.npmjs.com/package/@snyxex/pipex)
6
+ [![license](https://img.shields.io/github/license/Snyxex/PipeX)](https://github.com/Snyxex/PipeX/blob/main/LICENSE)
7
+ [![CI](https://img.shields.io/badge/CI-Jenkins-informational)](https://github.com/Snyxex/PipeX/commits/main/)
8
+ [![TypeScript](https://img.shields.io/badge/TypeScript-types-included-blue)](https://github.com/Snyxex/PipeX/blob/main/package.json)
9
+ [![npm package size](https://img.shields.io/npm/unpacked-size/@snyxex/pipex)](https://www.npmjs.com/package/@snyxex/pipex)
10
+
11
+ ## Installation
12
+
13
+ ```sh
14
+ npm install @snyxex/pipex
15
+ ```
16
+
17
+ Requires **Node.js 22 or newer** and ESM. PipeX uses Node.js streams, cryptography, and filesystem facilities; it does not provide a browser build.
18
+
19
+ ## Quick Start
20
+
21
+ This in-memory example requires no native filesystem bindings.
22
+
23
+ ```ts
24
+ import { DataEngine, CompressionPlugin } from '@snyxex/pipex';
25
+
26
+ const engine = new DataEngine().use(
27
+ new CompressionPlugin({ type: 'gzip', level: 6 }),
28
+ );
29
+
30
+ const encoded = await engine.binary.run({ id: 42, status: 'ready' });
31
+ const original = await engine.binary.undo<{ id: number; status: string }>(encoded);
32
+
33
+ console.log(original); // { id: 42, status: 'ready' }
34
+ ```
35
+
36
+ ## Core Concepts
37
+
38
+ - **DataEngine:** Owns the configured plugin chain, resource limits, operation lifecycle, and binary/file/stream controllers.
39
+ - **Controllers:** `engine.binary` processes in-memory values, `engine.file` works with paths under an allowed root, and `engine.stream` connects Node.js streams.
40
+ - **Plugin:** Implements `process(Buffer, context)` and optionally `reverse` or `createStream`.
41
+ - **Transformation:** Plugins run in registration order. Reverse transformations execute reversible plugins in the opposite order.
42
+ - **Capabilities:** Query whether a plugin supports processing, reversal, or native/fallback streaming.
43
+ - **Execution context:** Request-scoped metadata, cancellation signal, limits, and optional logging/tracing.
44
+ - **Source and destination:** The input and output objects passed to the relevant controller; they are concepts, not exported PipeX classes.
45
+
46
+ `pack()` and `unpack()` are **serialization-only** operations; they do not apply the transformation pipeline.
47
+
48
+ ## Transformation Examples
49
+
50
+ ### Compression
51
+
52
+ ```ts
53
+ import { DataEngine, CompressionPlugin } from '@snyxex/pipex';
54
+
55
+ const engine = new DataEngine().use(new CompressionPlugin({ type: 'brotli', level: 5 }));
56
+ const result = await engine.binary.run('Repeated application data');
57
+ console.log(await engine.binary.undo<string>(result));
58
+ ```
59
+
60
+ Compression types: `gzip`, `brotli`, and `none`.
61
+
62
+ ### Encryption
63
+
64
+ ```ts
65
+ import { randomBytes } from 'node:crypto';
66
+ import { DataEngine, EncryptionPlugin } from '@snyxex/pipex';
67
+
68
+ // Demonstration only: retain this key securely to decrypt persisted data.
69
+ const key = randomBytes(32);
70
+ const engine = new DataEngine().use(new EncryptionPlugin({
71
+ algorithm: 'aes-256-gcm',
72
+ key,
73
+ allowLegacyDecrypt: false,
74
+ }));
75
+
76
+ const encrypted = await engine.binary.run('confidential');
77
+ const plaintext = await engine.binary.undo<string>(encrypted);
78
+ console.log(plaintext);
79
+ ```
80
+
81
+ Alternative algorithm: `chacha20-poly1305`. Both require a 32-byte key.
82
+
83
+ ### Hashing / HMAC integrity
84
+
85
+ ```ts
86
+ import { DataEngine, HashingPlugin } from '@snyxex/pipex';
87
+
88
+ const engine = new DataEngine().use(new HashingPlugin({
89
+ algorithm: 'sha256',
90
+ secret: process.env.PIPEX_HMAC_SECRET ?? (() => { throw new Error('Missing HMAC key'); })(),
91
+ }));
92
+
93
+ const signed = await engine.binary.run('message');
94
+ const verified = await engine.binary.undo<string>(signed);
95
+ console.log(verified);
96
+ ```
97
+
98
+ `HashingPlugin` **appends a keyed HMAC** and verifies it during reversal. It is not a standalone, one-way digest API. The secret must contain at least 16 characters; use a high-entropy secret in production.
99
+
100
+ ### Combined reversible pipeline
101
+
102
+ ```ts
103
+ import { randomBytes } from 'node:crypto';
104
+ import { DataEngine, CompressionPlugin, EncryptionPlugin, HashingPlugin } from '@snyxex/pipex';
105
+
106
+ const encryptionKey = randomBytes(32);
107
+ const hmacSecret = randomBytes(32).toString('hex');
108
+ const engine = new DataEngine()
109
+ .use(new CompressionPlugin({ type: 'gzip', level: 6 }))
110
+ .use(new EncryptionPlugin({ algorithm: 'aes-256-gcm', key: encryptionKey }))
111
+ .use(new HashingPlugin({ algorithm: 'sha512', secret: hmacSecret }));
112
+
113
+ const result = await engine.binary.run({ event: 'example' });
114
+ const restored = await engine.binary.undo<{ event: string }>(result);
115
+ console.log(restored);
116
+ ```
117
+
118
+ Keep keys outside code and configuration repositories. The HMAC in this example is an optional additional integrity layer; authenticated encryption already authenticates encrypted data.
119
+
120
+ ## Data Interfaces
121
+
122
+ | Controller | Use | Runtime considerations |
123
+ | --- | --- | --- |
124
+ | `engine.binary` | Values and buffers held in memory | Does not load native file bindings |
125
+ | `engine.file` | Files on disk | Uses Koffi-based native filesystem operations |
126
+ | `engine.stream` | Large streams, pipes, sockets | Uses Node.js backpressure and supports `AbortSignal` |
127
+
128
+ ### Binary
129
+
130
+ ```ts
131
+ const encoded = await engine.binary.run({ ok: true });
132
+ const decoded = await engine.binary.undo(encoded);
133
+ const serialized = engine.binary.pack({ ok: true });
134
+ const parsed = engine.binary.unpack<{ ok: boolean }>(serialized);
135
+ ```
136
+
137
+ For data reconstructed after transport or storage, supply a trusted `expectedType` to `undo`; never trust unverified type metadata.
138
+
139
+ ### Files
140
+
141
+ ```ts
142
+ await engine.file.process('./data/source.bin', './data/source.px', './data');
143
+ await engine.file.reverse('./data/source.px', './data/restored.bin', './data');
144
+ ```
145
+
146
+ Output is staged and atomically replaced. Paths are restricted to `allowedRoot`; create the parent directories first.
147
+
148
+ ### Streams
149
+
150
+ ```ts
151
+ import { createReadStream, createWriteStream } from 'node:fs';
152
+
153
+ const controller = new AbortController();
154
+ await engine.stream.pipe(
155
+ createReadStream('./source.bin'),
156
+ createWriteStream('./output.px'),
157
+ false,
158
+ { signal: controller.signal, timeoutMs: 30_000 },
159
+ );
160
+ ```
161
+
162
+ The `reverse` argument is `true` when decoding. Serialization-only stream adapters are `engine.stream.pack()` and `engine.stream.unpack()`.
163
+
164
+ ## Plugins
165
+
166
+ ### Built-in plugins
167
+
168
+ | Plugin | Purpose | Notes |
169
+ | --- | --- | --- |
170
+ | `CompressionPlugin` | Gzip/Brotli transformations | Reversible; native streaming |
171
+ | `EncryptionPlugin` | AES-256-GCM / ChaCha20-Poly1305 | Reversible authenticated frames |
172
+ | `HashingPlugin` | HMAC-SHA-256 / HMAC-SHA-512 | Appends and verifies a keyed digest |
173
+ | `BenchmarkPlugin` | Processing metrics | Observes transformation timings |
174
+ | `ValidationPlugin` | Application schema validation | Integrates Zod |
175
+ | `WorkerPoolPlugin` | Caller-supplied worker module transforms | Opt-in local Piscina pool |
176
+ | `KmsEncryptionPlugin` | Envelope encryption using caller-supplied KMS | Binary-only; needs KMS provider |
177
+
178
+ The `Plugins` object exposes these constructors under their shortened names, e.g. `Plugins.Compression`.
179
+
180
+ ### Plugin lifecycle
181
+
182
+ Register with `engine.use(plugin)` in the intended order, or use `DataEngine.fromConfig()` with registered plugin names. Third-party plugins may implement `ProcessorPlugin` or extend `BasePlugin`. Registration validates capability declarations; pipeline configuration cannot change during an active operation. Reverse operations reject pipelines containing non-reversible plugins rather than silently skipping a step.
183
+
184
+ Read [the full API reference](docs/api.md) for the plugin contract, constructor options, and error types.
185
+
186
+ ## Streaming & Backpressure
187
+
188
+ `stream.pipe(source, destination, reverse?, options?)` connects a source to the configured transform chain and destination, awaiting completion. Node.js backpressure propagates across native stream plugins. `stream.into(destination)` and `stream.reverseInto(destination)` expose writable adapters for use with Node.js pipelines.
189
+
190
+ Plugins lacking `createStream()` use a per-chunk fallback **only when chunk independence is valid**. Such a fallback is not suitable for algorithms requiring whole-message authentication or global framing.
191
+
192
+ Authenticated encryption emits bounded frames, each verified before its plaintext is released. Previously authenticated frames can already have been consumed if a later frame or final marker fails: **treat successful stream completion as the transaction commit point**. HMAC verification, unlike per-frame AEAD, withholds complete bounded plaintext until its final digest verifies.
193
+
194
+ Cancellation uses `AbortSignal`; operation limits and deadlines apply to stream processing.
195
+
196
+ ### Lifecycle, cancellation, and cleanup
197
+
198
+ PipeX runs byte-stream transformations through Node.js `stream/promises.pipeline()`. This awaits completion, propagates failures from the source, any plugin transform, or the destination, and destroys connected streams when a stage fails or the operation is aborted.
199
+
200
+ ```ts
201
+ import { createReadStream, createWriteStream } from 'node:fs';
202
+ import { DataEngine, CompressionPlugin } from '@snyxex/pipex';
203
+
204
+ const controller = new AbortController();
205
+ const engine = new DataEngine().use(new CompressionPlugin({ type: 'gzip' }));
206
+
207
+ await engine.stream.pipe(
208
+ createReadStream('./input.bin'),
209
+ createWriteStream('./output.px'),
210
+ false,
211
+ { signal: controller.signal, timeoutMs: 30_000 },
212
+ );
213
+
214
+ // controller.abort() cancels an operation in progress.
215
+ ```
216
+
217
+ For a destination you already own, `stream.into(destination, options)` and `stream.reverseInto(destination, options)` expose a writable endpoint. Connect external sources using `pipeline()`, **not** unguarded `.pipe()`:
218
+
219
+ ```ts
220
+ import { pipeline } from 'node:stream/promises';
221
+
222
+ await pipeline(
223
+ createReadStream('./input.bin'),
224
+ engine.stream.into(createWriteStream('./output.px'), { signal: controller.signal }),
225
+ { signal: controller.signal },
226
+ );
227
+ ```
228
+
229
+ Backpressure propagates through the transforms: a slow downstream writable pauses upstream reads instead of buffering the entire input. Memory still depends on configured frame limits and plugin implementations; `binary.run()` is deliberately in-memory, and HMAC verification may hold a bounded complete message until its digest is verified.
230
+
231
+ **Lifecycle rules:** Each invocation requires fresh source and destination stream instances; the same `DataEngine` may process multiple operations. On abort or failure, the source, plugin streams, and destination are destroyed. A failed destination can contain partial output: use the file controller's atomic-output operations when partial files must not become visible. Set `timeoutMs` and resource limits appropriate for large inputs. A caller-owned `AbortSignal` is supported by binary, stream, and file controllers; aborted operations reject rather than producing partial success.
232
+
233
+ ## API Reference
234
+
235
+ See **[docs/api.md](docs/api.md)** for public entry points, signatures, options, return values, error classes, and serialization semantics.
236
+
237
+ Primary operations:
238
+
239
+ ```ts
240
+ new DataEngine(limits?)
241
+ DataEngine.fromConfig(config)
242
+ engine.use(plugin)
243
+ engine.binary.run(input, options?)
244
+ engine.binary.undo(result, options?)
245
+ engine.binary.pack(data)
246
+ engine.binary.unpack(buffer)
247
+ engine.file.process(inputPath, outputPath, allowedRoot?, options?)
248
+ engine.file.reverse(inputPath, outputPath, allowedRoot?, options?)
249
+ engine.stream.pipe(source, destination, reverse?, options?)
250
+ ```
251
+
252
+ ## Security
253
+
254
+ **Hashing is not encryption.** HMAC detects unauthorized modification when its key remains secret; it does not conceal contents. Authenticated encryption provides confidentiality and integrity. Complete-message integrity for framed encrypted streams is confirmed only after the final authenticated frame and successful completion.
255
+
256
+ - **Encryption:** AES-256-GCM and ChaCha20-Poly1305 with 32-byte keys; authenticated framing uses the `PXAE` v4 format.
257
+ - **Authentication tags:** A frame is not emitted as plaintext until its AEAD tag verifies. Sequence numbers and a final authenticated frame detect reordering, duplication, and truncation.
258
+ - **Key handling:** Supply keys through a secret manager or application-managed KMS. PipeX is not a key vault. Do not reuse a randomly generated per-process key for data requiring later decryption.
259
+ - **HMAC:** SHA-256 or SHA-512 with a caller-owned secret. A mismatched or truncated digest rejects reversal.
260
+ - **Limits:** Input, output, frame, concurrency, and timeout limits protect the host; configure them for the deployment.
261
+ - **KMS:** External providers are supplied by the application; the KMS plugin is binary-only and requires a working `generateDataKey` capability.
262
+
263
+ **Compatibility:** Version 4 encryption writes framed `PXAE` only. Reading legacy unversioned v3 encrypted data is a temporary migration option (`allowLegacyDecrypt`, default `false`; explicitly enable it only during migration); disable it after migration. Format compatibility is not a promise that all future versions or arbitrary plugin combinations can read every older payload. Keep original plugin configuration and secrets where reversibility is required.
264
+
265
+ See [Encryption migration](docs/encryption-v4-migration.md) and [Production security](docs/enterprise.md).
266
+
267
+ ## Error Handling
268
+
269
+ Operations reject on invalid configuration, unsupported reverse/stream operations, resource-limit violations, authentication failures, aborted operations, timeouts, and underlying stream/filesystem errors. Typed errors include `PipeXError`, `UnsupportedReverseError`, `UnsupportedStreamingError`, `OperationAbortedError`, `OperationTimeoutError`, and worker/KMS errors. Check `error.code` on `PipeXError` when branching on supported classifications; other errors may be ordinary `Error` instances.
270
+
271
+ ```ts
272
+ import { OperationTimeoutError } from '@snyxex/pipex';
273
+
274
+ try {
275
+ await engine.binary.run('data', { timeoutMs: 1000 });
276
+ } catch (error) {
277
+ if (error instanceof OperationTimeoutError) {
278
+ console.error('Transformation timed out');
279
+ } else {
280
+ throw error;
281
+ }
282
+ }
283
+ ```
284
+
285
+ ## Optional Features
286
+
287
+ - **Worker Threads:** `WorkerPoolPlugin` is opt-in at runtime, but `piscina` is presently installed as a regular dependency. Workers execute caller-provided module exports, not a built-in job scheduler.
288
+ - **Native file operations:** `engine.file` uses `koffi`, currently a regular dependency. Binary and stream controllers do not load these native bindings. File operations fail if required native bindings are unavailable; there is no path-only fallback.
289
+ - **KMS:** `KmsEncryptionPlugin` requires a provider implementation supplied by your application.
290
+ - **Validation and observability:** Zod validation, logging, tracing, audit logging, and caller-owned failure sinks are integrated only when configured.
291
+
292
+ ## Performance & Resource Limits
293
+
294
+ Streaming reduces whole-payload buffering, but some operations (including HMAC verification and binary processing) necessarily retain bounded data in memory. The engine enforces finite defaults for input/output bytes, frames, concurrent operations, retry attempts, and deadlines.
295
+
296
+ ```ts
297
+ const limited = new DataEngine({
298
+ maxInputBytes: 64 * 1024 * 1024,
299
+ maxOutputBytes: 256 * 1024 * 1024,
300
+ maxFrameBytes: 8 * 1024 * 1024,
301
+ maxConcurrentOperations: 32,
302
+ operationTimeoutMs: 30_000,
303
+ });
304
+ ```
305
+
306
+ These are example limits, not all defaults. See [resource-limit details](docs/enterprise.md#resource-limits).
307
+
308
+ ## Documentation
309
+
310
+ - [Complete public API reference](docs/api.md)
311
+ - [Architecture](docs/architecture.md)
312
+ - [Production operations and security](docs/enterprise.md)
313
+ - [Encryption v4 migration](docs/encryption-v4-migration.md)
314
+ - [Changelog](CHANGELOG.md)
315
+
316
+ ## Contributing & License
317
+
318
+ See [CONTRIBUTING.md](CONTRIBUTING.md), [SUPPORT.md](SUPPORT.md), and [SECURITY.md](SECURITY.md). Report vulnerabilities privately according to the security policy, not in public issues.
319
+
320
+ MIT © Snyxex.
@@ -0,0 +1 @@
1
+ import{p as e}from"./core-BOdvxKBq.mjs";import{b as t,i as n,n as r,o as i,r as a}from"./resourceLimits-C1HHDwXQ.mjs";import{Duplex as o,PassThrough as s,Readable as c,Transform as l,compose as u}from"node:stream";import{brotliCompress as d,brotliDecompress as f,constants as p,createBrotliCompress as m,createBrotliDecompress as h,createGunzip as g,createGzip as _,gunzip as v,gzip as y}from"node:zlib";import{promisify as b}from"node:util";const x={none:0,gzip:1,brotli:2},S={0:`none`,1:`gzip`,2:`brotli`},C=b(y),w=b(v),T=b(d),E=b(f);var D=class extends n{name=`compression`;version=`3.0.0`;constructor(e){if(super(e),this.options=e,!(e.type in x))throw new t({transformName:`compression`,stage:`configuration`});if(e.level!==void 0&&!Number.isInteger(e.level)||e.type===`gzip`&&e.level!==void 0&&(e.level<0||e.level>9)||e.type===`brotli`&&e.level!==void 0&&(e.level<0||e.level>11)||e.type===`none`&&e.level!==void 0)throw new i({transformName:`compression`})}async process(e,t){let n=r(t),o=a(t);if(e.length>n)throw new i({transformName:`compression`,stage:`input`});let{type:s,level:c}=this.options,l=Buffer.from([x[s]]);if(e.length>o-l.length&&s===`none`||o<=l.length&&s!==`none`)throw new i({transformName:`compression`,stage:`output`});let u;return u=s===`gzip`?await C(e,{level:c??6,maxOutputLength:o-l.length}):s===`brotli`?await T(e,{params:{[p.BROTLI_PARAM_QUALITY]:c??11},maxOutputLength:o-l.length}):e,Buffer.concat([l,u])}async reverse(e,n){let o=r(n),s=a(n);if(e.length>o)throw new i({transformName:`compression`,stage:`input`});if(e.length<1)throw new i({transformName:`compression`});let c=S[e.readUInt8(0)],l=e.subarray(1);if(c===`gzip`)return await w(l,{maxOutputLength:s});if(c===`brotli`)return await E(l,{maxOutputLength:s});if(c!==`none`)throw new t({transformName:`compression`,stage:`configuration`});if(l.length>s)throw new i({transformName:`compression`,stage:`output`});return l}createStream(n,d){let{type:f,level:v}=this.options,y=r(d),b=a(d);if(n===`compress`){let t=f===`gzip`?_({level:v??6}):f===`brotli`?m({params:{[p.BROTLI_PARAM_QUALITY]:v??11}}):new s,n=!1,r=new l({transform(e,t,r){n||(n=!0,this.push(Buffer.from([x[f]]))),r(null,e)},flush(e){n||this.push(Buffer.from([x[f]])),e()}});return u(e(y,`compression input`),t,r,e(b,`compression output`))}return o.from(async function*(e){let n=e[Symbol.asyncIterator](),r,a=0,o=0;for(;!r;){let e=await n.next();if(e.done)throw new i({transformName:`compression`});let t=Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value);if(t.length>y-a)throw new i({transformName:`compression`,stage:`input`});a+=t.length,t.length>0&&(r=t)}let l=S[r.readUInt8(0)];if(!l)throw new t({transformName:`compression`,stage:`decompress`});let d=l===`gzip`?g():l===`brotli`?h():new s;async function*f(){let e=r.subarray(1);for(e.length>0&&(yield e);;){let e=await n.next();if(e.done)return;let t=Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value);if(t.length>y-a)throw new i({transformName:`compression`,stage:`input`});a+=t.length,t.length>0&&(yield t)}}try{for await(let e of u(c.from(f()),d)){let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(t.length>b-o)throw new i({transformName:`compression`,stage:`output`});o+=t.length,yield t}}finally{d.destroy();try{await n.return?.()}catch{}}})}};export{D as t};
@@ -0,0 +1,38 @@
1
+ import { C as StreamPluginContext, _ as ProcessorContext } from "./types-Bytga6zd.mjs";
2
+ import { t as BasePlugin } from "./plugin-CE94-p8P.mjs";
3
+ import { Duplex } from "node:stream";
4
+
5
+ //#region src/plugin/compression.d.ts
6
+ type CompressionType = 'gzip' | 'brotli' | 'none';
7
+ /** Gzip level is validated at runtime to be within 0–9. */
8
+ interface GzipCompressionOptions {
9
+ readonly type: 'gzip';
10
+ readonly level?: number;
11
+ }
12
+ /** Brotli quality is validated at runtime to be within 0–11. */
13
+ interface BrotliCompressionOptions {
14
+ readonly type: 'brotli';
15
+ readonly level?: number;
16
+ }
17
+ /** Pass-through compression never accepts a level option. */
18
+ interface NoCompressionOptions {
19
+ readonly type: 'none';
20
+ readonly level?: never;
21
+ }
22
+ /** Algorithm-discriminated compression configuration. */
23
+ type CompressionOptions = GzipCompressionOptions | BrotliCompressionOptions | NoCompressionOptions;
24
+ /**
25
+ * CompressionPlugin — Standard library plugin for Gzip and Brotli.
26
+ * Prepends a 1-byte header to identify the compression type.
27
+ */
28
+ declare class CompressionPlugin extends BasePlugin {
29
+ protected options: CompressionOptions;
30
+ readonly name = "compression";
31
+ readonly version = "3.0.0";
32
+ constructor(options: CompressionOptions);
33
+ process(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
34
+ reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
35
+ createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Duplex;
36
+ }
37
+ //#endregion
38
+ export { GzipCompressionOptions as a, CompressionType as i, CompressionOptions as n, NoCompressionOptions as o, CompressionPlugin as r, BrotliCompressionOptions as t };
@@ -0,0 +1,38 @@
1
+ import { C as StreamPluginContext, _ as ProcessorContext } from "./types-ia4x-Dvp.cjs";
2
+ import { t as BasePlugin } from "./plugin-C9Kd9coY.cjs";
3
+ import { Duplex } from "node:stream";
4
+
5
+ //#region src/plugin/compression.d.ts
6
+ type CompressionType = 'gzip' | 'brotli' | 'none';
7
+ /** Gzip level is validated at runtime to be within 0–9. */
8
+ interface GzipCompressionOptions {
9
+ readonly type: 'gzip';
10
+ readonly level?: number;
11
+ }
12
+ /** Brotli quality is validated at runtime to be within 0–11. */
13
+ interface BrotliCompressionOptions {
14
+ readonly type: 'brotli';
15
+ readonly level?: number;
16
+ }
17
+ /** Pass-through compression never accepts a level option. */
18
+ interface NoCompressionOptions {
19
+ readonly type: 'none';
20
+ readonly level?: never;
21
+ }
22
+ /** Algorithm-discriminated compression configuration. */
23
+ type CompressionOptions = GzipCompressionOptions | BrotliCompressionOptions | NoCompressionOptions;
24
+ /**
25
+ * CompressionPlugin — Standard library plugin for Gzip and Brotli.
26
+ * Prepends a 1-byte header to identify the compression type.
27
+ */
28
+ declare class CompressionPlugin extends BasePlugin {
29
+ protected options: CompressionOptions;
30
+ readonly name = "compression";
31
+ readonly version = "3.0.0";
32
+ constructor(options: CompressionOptions);
33
+ process(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
34
+ reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
35
+ createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Duplex;
36
+ }
37
+ //#endregion
38
+ export { GzipCompressionOptions as a, CompressionType as i, CompressionOptions as n, NoCompressionOptions as o, CompressionPlugin as r, BrotliCompressionOptions as t };
@@ -0,0 +1 @@
1
+ const e=require(`./core-B_z1gN5W.cjs`),t=require(`./resourceLimits-CI0Qrqdf.cjs`);let n=require(`node:stream`),r=require(`node:zlib`),i=require(`node:util`);const a={none:0,gzip:1,brotli:2},o={0:`none`,1:`gzip`,2:`brotli`},s=(0,i.promisify)(r.gzip),c=(0,i.promisify)(r.gunzip),l=(0,i.promisify)(r.brotliCompress),u=(0,i.promisify)(r.brotliDecompress);var d=class extends t.i{name=`compression`;version=`3.0.0`;constructor(e){if(super(e),this.options=e,!(e.type in a))throw new t.b({transformName:`compression`,stage:`configuration`});if(e.level!==void 0&&!Number.isInteger(e.level)||e.type===`gzip`&&e.level!==void 0&&(e.level<0||e.level>9)||e.type===`brotli`&&e.level!==void 0&&(e.level<0||e.level>11)||e.type===`none`&&e.level!==void 0)throw new t.o({transformName:`compression`})}async process(e,n){let i=t.n(n),o=t.r(n);if(e.length>i)throw new t.o({transformName:`compression`,stage:`input`});let{type:c,level:u}=this.options,d=Buffer.from([a[c]]);if(e.length>o-d.length&&c===`none`||o<=d.length&&c!==`none`)throw new t.o({transformName:`compression`,stage:`output`});let f;return f=c===`gzip`?await s(e,{level:u??6,maxOutputLength:o-d.length}):c===`brotli`?await l(e,{params:{[r.constants.BROTLI_PARAM_QUALITY]:u??11},maxOutputLength:o-d.length}):e,Buffer.concat([d,f])}async reverse(e,n){let r=t.n(n),i=t.r(n);if(e.length>r)throw new t.o({transformName:`compression`,stage:`input`});if(e.length<1)throw new t.o({transformName:`compression`});let a=o[e.readUInt8(0)],s=e.subarray(1);if(a===`gzip`)return await c(s,{maxOutputLength:i});if(a===`brotli`)return await u(s,{maxOutputLength:i});if(a!==`none`)throw new t.b({transformName:`compression`,stage:`configuration`});if(s.length>i)throw new t.o({transformName:`compression`,stage:`output`});return s}createStream(i,s){let{type:c,level:l}=this.options,u=t.n(s),d=t.r(s);if(i===`compress`){let t=c===`gzip`?(0,r.createGzip)({level:l??6}):c===`brotli`?(0,r.createBrotliCompress)({params:{[r.constants.BROTLI_PARAM_QUALITY]:l??11}}):new n.PassThrough,i=!1,o=new n.Transform({transform(e,t,n){i||(i=!0,this.push(Buffer.from([a[c]]))),n(null,e)},flush(e){i||this.push(Buffer.from([a[c]])),e()}});return(0,n.compose)(e.p(u,`compression input`),t,o,e.p(d,`compression output`))}return n.Duplex.from(async function*(e){let i=e[Symbol.asyncIterator](),a,s=0,c=0;for(;!a;){let e=await i.next();if(e.done)throw new t.o({transformName:`compression`});let n=Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value);if(n.length>u-s)throw new t.o({transformName:`compression`,stage:`input`});s+=n.length,n.length>0&&(a=n)}let l=o[a.readUInt8(0)];if(!l)throw new t.b({transformName:`compression`,stage:`decompress`});let f=l===`gzip`?(0,r.createGunzip)():l===`brotli`?(0,r.createBrotliDecompress)():new n.PassThrough;async function*p(){let e=a.subarray(1);for(e.length>0&&(yield e);;){let e=await i.next();if(e.done)return;let n=Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value);if(n.length>u-s)throw new t.o({transformName:`compression`,stage:`input`});s+=n.length,n.length>0&&(yield n)}}try{for await(let e of(0,n.compose)(n.Readable.from(p()),f)){let n=Buffer.isBuffer(e)?e:Buffer.from(e);if(n.length>d-c)throw new t.o({transformName:`compression`,stage:`output`});c+=n.length,yield n}}finally{f.destroy();try{await i.return?.()}catch{}}})}};Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return d}});
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./compression-DrgzribA.cjs`);exports.CompressionPlugin=e.t;
@@ -0,0 +1,2 @@
1
+ import { a as GzipCompressionOptions, i as CompressionType, n as CompressionOptions, o as NoCompressionOptions, r as CompressionPlugin, t as BrotliCompressionOptions } from "./compression-DnVFu8TM.cjs";
2
+ export { type BrotliCompressionOptions, type CompressionOptions, CompressionPlugin, type CompressionType, type GzipCompressionOptions, type NoCompressionOptions };
@@ -0,0 +1,2 @@
1
+ import { a as GzipCompressionOptions, i as CompressionType, n as CompressionOptions, o as NoCompressionOptions, r as CompressionPlugin, t as BrotliCompressionOptions } from "./compression-CtrHxa9G.mjs";
2
+ export { type BrotliCompressionOptions, type CompressionOptions, CompressionPlugin, type CompressionType, type GzipCompressionOptions, type NoCompressionOptions };
@@ -0,0 +1 @@
1
+ import{t as e}from"./compression-2mm0MhWY.mjs";export{e as CompressionPlugin};
@@ -0,0 +1,2 @@
1
+ import{C as e,S as t,_ as n,d as r,g as i,i as a,t as o}from"./resourceLimits-C1HHDwXQ.mjs";import{randomUUID as s}from"node:crypto";import{pipeline as c}from"node:stream/promises";import{Transform as l}from"node:stream";import{Packr as u,PackrStream as d,Unpackr as f,UnpackrStream as p}from"msgpackr";import"zod";import m from"node:path";import{existsSync as h,realpathSync as g}from"node:fs";function _(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.__pipex_v===1&&Array.isArray(t.plugins)&&t.plugins.length<=256&&t.plugins.every(e=>typeof e==`string`&&e.length<=256)&&typeof t.ts==`number`&&Number.isSafeInteger(t.ts)&&t.ts>=0}var v=class{#e;#t;#n=0;#r=1;#i=0;#a=!1;#o;#s=0;constructor(e,t){this.#e=e,this.#t=t}scan(e){let t=[],n=0;for(;n<e.length;){if(this.#i>0){if(this.#a){this.#c(1);let r=e[n];n++,this.#i--,this.#a=!1,r===101||r===115||r===120?(this.#u(1),this.#l(this.#i)):r!==0&&r!==66&&r!==116&&r!==255&&this.#v(),this.#i===0&&this.#g(n,t);continue}let r=Math.min(this.#i,e.length-n);this.#c(r),this.#i-=r,n+=r,this.#i>0&&this.#n===this.#e&&this.#_(),this.#i===0&&this.#g(n,t);continue}if(this.#o){let r=this.#o;if(this.#c(1),r.value=r.value*256+e[n],n++,r.read++,r.read===r.bytes){let{kind:e,value:i}=r;this.#o=void 0,this.#m(e,i),this.#g(n,t)}continue}this.#c(1);let r=e[n];n++,this.#r--,this.#r<0&&this.#v(),this.#h(r),this.#g(n,t)}return t}finish(){if(this.#n!==0||this.#o||this.#i!==0)throw Error(`[PipeX] Invalid MessagePack input: incomplete frame`)}#c(e){e>this.#e-this.#n&&this.#_(),this.#n+=e}#l(e=0){let t=this.#e-this.#n;(e>t||this.#r>t-e)&&this.#_()}#u(e){(!Number.isSafeInteger(e)||e<0||e>2**53-1-this.#r)&&this.#v(),this.#r+=e,this.#l()}#d(e){(!Number.isSafeInteger(e)||e<0)&&this.#v(),this.#l(e),this.#i=e}#f(e){this.#d(e+1),this.#a=!0}#p(e,t){this.#o={kind:e,bytes:t,read:0,value:0}}#m(e,t){e===`array`?this.#u(t):e===`map`?this.#u(t*2):(this.#d(t+ +(e===`extension`)),this.#a=e===`extension`)}#h(e){if(e<=127||e>=224||e>=192&&e<=195){e===193&&this.#v();return}if(e>=128&&e<=143)return this.#u((e&15)*2);if(e>=144&&e<=159)return this.#u(e&15);if(e>=160&&e<=191)return this.#d(e&31);switch(e){case 196:return this.#p(`payload`,1);case 197:return this.#p(`payload`,2);case 198:return this.#p(`payload`,4);case 199:return this.#p(`extension`,1);case 200:return this.#p(`extension`,2);case 201:return this.#p(`extension`,4);case 202:return this.#d(4);case 203:return this.#d(8);case 204:case 208:return this.#d(1);case 205:case 209:return this.#d(2);case 206:case 210:return this.#d(4);case 207:case 211:return this.#d(8);case 212:return this.#f(1);case 213:return this.#f(2);case 214:return this.#f(4);case 215:return this.#f(8);case 216:return this.#f(16);case 217:return this.#p(`payload`,1);case 218:return this.#p(`payload`,2);case 219:return this.#p(`payload`,4);case 220:return this.#p(`array`,2);case 221:return this.#p(`array`,4);case 222:return this.#p(`map`,2);case 223:return this.#p(`map`,4);default:return this.#v()}}#g(e,t){if(!(this.#o||this.#i>0||this.#r!==0)){if(this.#s++,this.#s>this.#t)throw Error(`[PipeX] Frame count exceeds ${this.#t}`);t.push(e),this.#n=0,this.#r=1,this.#a=!1}}#_(){throw Error(`[PipeX] MessagePack frame exceeds ${this.#e} bytes`)}#v(){throw Error(`[PipeX] Invalid MessagePack input`)}};function y(e,t,n=2**53-1){let r=new v(t,n),i=r.scan(Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength));return r.finish(),i.length}function ee(e,t){let n=new v(e,t),r=[],i=0;return new l({transform(e,t,a){try{let t=Buffer.isBuffer(e)?e:Buffer.from(e),o=n.scan(t),s=0;for(let e of o){let n=t.subarray(s,e);n.length>0&&(r.push(n),i+=n.length),this.push(r.length===1?r[0]:Buffer.concat(r,i)),r=[],i=0,s=e}if(s<t.length){let e=t.subarray(s);r.push(e),i+=e.length}a()}catch(e){a(e)}},flush(e){try{n.finish(),e()}catch(t){e(t)}}})}const b=new WeakMap;function x(e,t){t>0&&b.set(e,Date.now()+t)}function S(e){return e.reason instanceof n||e.reason instanceof i?e.reason:e.reason instanceof Error&&e.reason.name===`TimeoutError`?new n:new i}function C(e){if(!e)return;if(e.aborted)throw S(e);let t=b.get(e);if(t!==void 0&&Date.now()>=t)throw new n}async function w(e,t,r){let i=Promise.resolve(e);return r?.(i),t?new Promise((e,r)=>{let a=!1,o,s=()=>{t.removeEventListener(`abort`,l),o&&clearTimeout(o)},c=e=>{a||(a=!0,s(),r(e))},l=()=>c(S(t));t.addEventListener(`abort`,l,{once:!0});let u=b.get(t);u!==void 0&&(o=setTimeout(()=>c(new n),Math.max(0,u-Date.now()))),i.then(n=>{if(!a){try{C(t)}catch(e){c(e);return}a=!0,s(),e(n)}},c);try{C(t)}catch(e){c(e)}}):i}function T(e){try{Promise.resolve(e()).catch(()=>void 0)}catch{}}function E(e){if(e)return{info:(t,n)=>T(()=>e.info(t,n)),warn:(t,n)=>T(()=>e.warn(t,n)),error:(t,n)=>T(()=>e.error(t,n)),debug:(t,n)=>T(()=>e.debug(t,n))}}function D(e){if(e)return{startSpan(t,n){let r;try{let i=e.startSpan(t,n);i&&typeof i.then==`function`?T(()=>i):r=i}catch{}let i=!1,a={setAttribute(e,t){return T(()=>r?.setAttribute(e,t)),a},addEvent(e,t){return T(()=>r?.addEvent(e,t)),a},end(){i||(i=!0,T(()=>r?.end()))}};return a}}}async function O(e,t,n,r){n=E(n);let{attempts:i=1,backoff:a=`fixed`,delayMs:o=0}=t??{},s=r?.limits?.maxRetryAttempts??5,c=r?.limits?.maxRetryDelayMs??3e4;if(!Number.isSafeInteger(i)||i<1||i>s)throw Error(`[PipeX] Invalid retry attempts: ${i}`);if(!Number.isSafeInteger(o)||o<0||o>c)throw Error(`[PipeX] Invalid retry delay: ${o}`);let l;for(let t=0;t<i;t++){C(r?.signal);try{return await w(e(),r?.signal,r?.track)}catch(e){if(C(r?.signal),l=e instanceof Error?e:Error(String(e)),t<i-1){let e=a===`exponential`?o*2**t:o;n?.debug(`[PipeX] Retry ${t+1}/${i} after ${e}ms`,{error:l.message}),e>0&&await new Promise((t,n)=>{let i=()=>r?.signal?.removeEventListener(`abort`,o),a=setTimeout(()=>{i(),t()},Math.min(e,c)),o=()=>{clearTimeout(a),i(),n(r?.signal?.reason??Error(`[PipeX] Operation aborted`))};r?.signal?.addEventListener(`abort`,o,{once:!0}),r?.signal?.aborted&&o()})}}}throw l}const k=`__pipex_v`,A=new u({useRecords:!1,moreTypes:!0,structuredClone:!1,bundleStrings:!1}),j=new f({useRecords:!1,structuredClone:!1}),te=256*1024*1024,M=64*1024;function N(e){return typeof e.createStream==`function`}function P(e){let t=`${e.name}@${e.version}`,n=e.reversible,i=e.streaming,o=e.reverse,s=e.createStream,c=typeof o==`function`&&o!==a.prototype.reverse;if(n!==void 0&&typeof n!=`boolean`)throw new r(t,`reversible`,`MUST_BE_BOOLEAN`);if(i!==void 0&&typeof i!=`boolean`)throw new r(t,`streaming`,`MUST_BE_BOOLEAN`);if(n===!0&&!c)throw new r(t,`reversible`,`MISSING_IMPLEMENTATION`);if(i===!1&&typeof s==`function`)throw new r(t,`streaming`,`CONFLICTING_IMPLEMENTATION`);let l=n!==!1&&c,u=i!==!1;return Object.freeze({process:!0,reverse:l,streaming:u,streamMode:u?typeof s==`function`?`native`:`fallback`:`none`})}function F(e,t){let n=P(e);switch(t){case`process`:return n.process;case`reverse`:return n.reverse;case`stream`:return n.streaming;default:throw TypeError(`[PipeX] Unknown plugin operation`)}}function I(e){return F(e,`reverse`)}function L(e){let n=e.find(e=>!I(e));if(n)throw new t(`${n.name}@${n.version}`)}function R(t){let n=t.find(e=>!F(e,`stream`));if(n)throw new e(`${n.name}@${n.version}`)}function z(e){return e===null?`null`:Buffer.isBuffer(e)?`buffer`:Array.isArray(e)?`array`:typeof e==`object`?`object`:typeof e}function ne(e){return Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):typeof e==`object`&&e?A.pack(e):typeof e==`number`||typeof e==`boolean`?Buffer.from(String(e)):Buffer.from(String(e??``),`utf-8`)}const B=Object.freeze([`buffer`,`object`,`array`,`string`,`number`,`boolean`,`null`,`undefined`,`bigint`,`json`]);function V(e){if(typeof e!=`string`||!B.includes(e))throw Error(`[PipeX] Unsupported original type`)}function H(e,t,n=o.maxFrameBytes){if(V(t),!Buffer.isBuffer(e))throw Error(`[PipeX] Invalid binary payload`);switch(t){case`array`:case`object`:{y(e,n,1);let r;try{r=j.unpack(e)}catch{throw Error(`[PipeX] fromBuffer: invalid MessagePack input`)}if(t===`array`?!Array.isArray(r):typeof r!=`object`||!r||Array.isArray(r))throw Error(`[PipeX] Decoded value does not match the expected type`);return r}case`json`:try{return JSON.parse(e.toString(`utf-8`))}catch{throw Error(`[PipeX] fromBuffer: invalid JSON input`)}case`number`:{let t=Number(e.toString(`utf-8`));if(Number.isNaN(t))throw Error(`[PipeX] fromBuffer: invalid number`);return t}case`bigint`:try{return BigInt(e.toString(`utf-8`))}catch{throw Error(`[PipeX] fromBuffer: invalid bigint`)}case`boolean`:{let t=e.toString(`utf-8`);if(t!==`true`&&t!==`false`)throw Error(`[PipeX] fromBuffer: invalid boolean`);return t===`true`}case`string`:return e.toString(`utf-8`);case`null`:case`undefined`:if(e.length!==0)throw Error(`[PipeX] Payload does not match the expected empty type`);return t===`null`?null:void 0;default:return e}}function U(e,t={},n,r,i,a){return{requestId:e,timestamp:Date.now(),metadata:t,logger:n,span:r,signal:i,limits:a}}function W(e){return{__pipex_v:1,plugins:e.map(e=>`${e.name}@${e.version}`),ts:Date.now()}}function G(e){let t=!1,n=Buffer.from(A.pack(e));return new l({transform(e,r,i){t||(t=!0,this.push(n)),i(null,e)},flush(e){t||this.push(n),e()}})}function K(e){let t=!1;return new l({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){if(!t&&(t=!0,_(n))){try{e(n),i()}catch(e){i(e)}return}i(null,n)}})}var q=class extends p{#e=0;#t;constructor(e={},t=o.maxInputBytes){super(e),this.#t=t}_transform(e,t,n){if(e.length>this.#t-this.#e){n(Error(`[PipeX] Serialized input exceeds ${this.#t} bytes`));return}this.#e+=e.length,super._transform(e,t,e=>{n(e?Error(`[PipeX] Invalid MessagePack input`):void 0)})}};function J(){return new d({useRecords:!1,moreTypes:!0,structuredClone:!1,bundleStrings:!1})}function Y(e=o.maxInputBytes){return new q({useRecords:!1,structuredClone:!1},e)}function X(e,t){let n=0;return new l({transform(r,i,a){if(r.length>e-n){a(Error(`[PipeX] ${t} exceeds ${e} bytes`));return}n+=r.length,a(null,r)}})}function re(e){let t=0;return new l({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){if(t>=e){i(Error(`[PipeX] Application frame count exceeds ${e}`));return}t++,i(null,n)}})}function Z(e,t,n){let r=typeof e==`string`?Buffer.byteLength(e):Buffer.isBuffer(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer?e.byteLength:void 0;if(r!==void 0&&r>t)throw Error(`[PipeX] ${n} exceeds ${t} bytes`)}function ie(e,t){return new l({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){try{Z(n,e,t),i(null,n)}catch(e){i(e)}}})}function Q(e,n,r,i,a,c,u){i=E(i),a=D(a);let d=u?.requestId??`stream-${s()}`;return new l({async transform(s,l,f){let p=a?.startSpan(`plugin:${e.name}`,{requestId:d});p?.setAttribute(`plugin.version`,e.version),p?.setAttribute(`mode`,n?`reverse`:`process`);try{u?.signal.throwIfAborted();let a=U(d,{},i,p,u?.signal,u?.limits);if(n&&!I(e))throw new t(`${e.name}@${e.version}`);let c=n?e.reverse.bind(e):e.process.bind(e),l=await O(()=>c(s,a),e.retryOptions,i,{signal:u?.signal,limits:u?.limits,track:u?.track}),m=u?.limits.maxOutputBytes??o.maxOutputBytes;if(!Buffer.isBuffer(l)||l.length>m)throw Error(`[PipeX] Plugin output exceeds ${m} bytes`);r?.(l.length),p?.addEvent(`processed`,{bytes:l.length}),f(null,l)}catch(t){let n=t instanceof Error?t:Error(String(t));if(i?.error(`[PipeX] Plugin ${e.name} failed after retries`,{requestId:d,error:n.message}),p?.setAttribute(`error`,!0),p?.addEvent(`error`,{message:n.message}),c&&c.writable){i?.warn(`[PipeX] Diverting failed chunk to DLQ`,{requestId:d,plugin:e.name});try{c.write(s)||await new Promise((e,t)=>{let n=()=>{o(),e()},r=e=>{o(),t(e)},i=()=>{o(),t(u?.signal.reason instanceof Error?u.signal.reason:Error(`[PipeX] Operation aborted`))},a=()=>{o(),t(Error(`[PipeX] Stream closed while writing to DLQ`))},o=()=>{c.off(`drain`,n),c.off(`error`,r),u?.signal.removeEventListener(`abort`,i),this.off(`close`,a)};c.once(`drain`,n),c.once(`error`,r),this.once(`close`,a),u?.signal.aborted?i():u?.signal.addEventListener(`abort`,i,{once:!0})}),f(n)}catch(e){f(e)}}else f(n)}finally{p?.end()}}})}function ae(){return new l({writableObjectMode:!0,readableObjectMode:!1,transform(e,t,n){try{n(null,JSON.stringify(e)+`
2
+ `)}catch(e){n(Error(`[PipeX] NDJSON: ${e.message}`))}}})}function oe(e,t,n=!1,r,i,a,s,c){return i=E(i),a=D(a),R(e),n&&L(e),(n?[...e].reverse():e).flatMap((e,u)=>{let d=N(e)?e.createStream(t,c):Q(e,n,r,i,a,s,c),f=X(c?.limits.maxOutputBytes??o.maxOutputBytes,`output after plugin ${e.name}#${u}`);if(!N(e))return[d,f];let p=a?.startSpan(`plugin:${e.name}`,{requestId:c?.requestId??`stream`}),m=!1,h=e=>{m||(m=!0,e&&p?.setAttribute(`error`,!0),p?.end())};return[d,new l({transform(e,t,n){r?.(e.length),p?.addEvent(`processed`,{bytes:e.length}),n(null,e)},final(e){h(),e()},destroy(e,t){h(e),t(e)}}),f]})}async function se(e,t,n,r){await c(e,...t,n,r??{})}function $(e,t){let n=m.relative(t,e);if(n===`..`||n.startsWith(`..${m.sep}`)||m.isAbsolute(n))throw Error(`[PipeX] Path is outside the allowed root`)}function ce(e,t){let n=m.resolve(e);if(!h(n))throw Error(`[PipeX] File not found: ${n}`);let r=g.native(m.resolve(t??process.cwd())),i=g.native(n);return $(i,r),i}function le(e,t){let n=g.native(m.resolve(t??process.cwd())),r=m.resolve(e),i=g.native(m.dirname(r));$(i,n);let a=m.join(i,m.basename(r));return h(a)&&$(g.native(a),n),a}export{se as A,C as B,Y as C,N as D,P as E,T as F,ee as H,E as I,D as L,I as M,ne as N,U as O,O as P,w as R,J as S,H as T,_ as U,y as V,K as _,A as a,re as b,ce as c,L as d,R as f,W as g,ie as h,B as i,F as j,le as k,Z as l,Q as m,q as n,k as o,X as p,te as r,j as s,M as t,V as u,G as v,z as w,oe as x,ae as y,x as z};
@@ -0,0 +1,2 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require(`./resourceLimits-CI0Qrqdf.cjs`);let l=require(`node:crypto`),u=require(`node:stream/promises`),d=require(`node:stream`),f=require(`msgpackr`);require(`zod`);let p=require(`node:path`);p=s(p,1);let m=require(`node:fs`);function h(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.__pipex_v===1&&Array.isArray(t.plugins)&&t.plugins.length<=256&&t.plugins.every(e=>typeof e==`string`&&e.length<=256)&&typeof t.ts==`number`&&Number.isSafeInteger(t.ts)&&t.ts>=0}var g=class{#e;#t;#n=0;#r=1;#i=0;#a=!1;#o;#s=0;constructor(e,t){this.#e=e,this.#t=t}scan(e){let t=[],n=0;for(;n<e.length;){if(this.#i>0){if(this.#a){this.#c(1);let r=e[n];n++,this.#i--,this.#a=!1,r===101||r===115||r===120?(this.#u(1),this.#l(this.#i)):r!==0&&r!==66&&r!==116&&r!==255&&this.#v(),this.#i===0&&this.#g(n,t);continue}let r=Math.min(this.#i,e.length-n);this.#c(r),this.#i-=r,n+=r,this.#i>0&&this.#n===this.#e&&this.#_(),this.#i===0&&this.#g(n,t);continue}if(this.#o){let r=this.#o;if(this.#c(1),r.value=r.value*256+e[n],n++,r.read++,r.read===r.bytes){let{kind:e,value:i}=r;this.#o=void 0,this.#m(e,i),this.#g(n,t)}continue}this.#c(1);let r=e[n];n++,this.#r--,this.#r<0&&this.#v(),this.#h(r),this.#g(n,t)}return t}finish(){if(this.#n!==0||this.#o||this.#i!==0)throw Error(`[PipeX] Invalid MessagePack input: incomplete frame`)}#c(e){e>this.#e-this.#n&&this.#_(),this.#n+=e}#l(e=0){let t=this.#e-this.#n;(e>t||this.#r>t-e)&&this.#_()}#u(e){(!Number.isSafeInteger(e)||e<0||e>2**53-1-this.#r)&&this.#v(),this.#r+=e,this.#l()}#d(e){(!Number.isSafeInteger(e)||e<0)&&this.#v(),this.#l(e),this.#i=e}#f(e){this.#d(e+1),this.#a=!0}#p(e,t){this.#o={kind:e,bytes:t,read:0,value:0}}#m(e,t){e===`array`?this.#u(t):e===`map`?this.#u(t*2):(this.#d(t+ +(e===`extension`)),this.#a=e===`extension`)}#h(e){if(e<=127||e>=224||e>=192&&e<=195){e===193&&this.#v();return}if(e>=128&&e<=143)return this.#u((e&15)*2);if(e>=144&&e<=159)return this.#u(e&15);if(e>=160&&e<=191)return this.#d(e&31);switch(e){case 196:return this.#p(`payload`,1);case 197:return this.#p(`payload`,2);case 198:return this.#p(`payload`,4);case 199:return this.#p(`extension`,1);case 200:return this.#p(`extension`,2);case 201:return this.#p(`extension`,4);case 202:return this.#d(4);case 203:return this.#d(8);case 204:case 208:return this.#d(1);case 205:case 209:return this.#d(2);case 206:case 210:return this.#d(4);case 207:case 211:return this.#d(8);case 212:return this.#f(1);case 213:return this.#f(2);case 214:return this.#f(4);case 215:return this.#f(8);case 216:return this.#f(16);case 217:return this.#p(`payload`,1);case 218:return this.#p(`payload`,2);case 219:return this.#p(`payload`,4);case 220:return this.#p(`array`,2);case 221:return this.#p(`array`,4);case 222:return this.#p(`map`,2);case 223:return this.#p(`map`,4);default:return this.#v()}}#g(e,t){if(!(this.#o||this.#i>0||this.#r!==0)){if(this.#s++,this.#s>this.#t)throw Error(`[PipeX] Frame count exceeds ${this.#t}`);t.push(e),this.#n=0,this.#r=1,this.#a=!1}}#_(){throw Error(`[PipeX] MessagePack frame exceeds ${this.#e} bytes`)}#v(){throw Error(`[PipeX] Invalid MessagePack input`)}};function _(e,t,n=2**53-1){let r=new g(t,n),i=r.scan(Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength));return r.finish(),i.length}function v(e,t){let n=new g(e,t),r=[],i=0;return new d.Transform({transform(e,t,a){try{let t=Buffer.isBuffer(e)?e:Buffer.from(e),o=n.scan(t),s=0;for(let e of o){let n=t.subarray(s,e);n.length>0&&(r.push(n),i+=n.length),this.push(r.length===1?r[0]:Buffer.concat(r,i)),r=[],i=0,s=e}if(s<t.length){let e=t.subarray(s);r.push(e),i+=e.length}a()}catch(e){a(e)}},flush(e){try{n.finish(),e()}catch(t){e(t)}}})}const y=new WeakMap;function b(e,t){t>0&&y.set(e,Date.now()+t)}function x(e){return e.reason instanceof c._||e.reason instanceof c.g?e.reason:e.reason instanceof Error&&e.reason.name===`TimeoutError`?new c._:new c.g}function S(e){if(!e)return;if(e.aborted)throw x(e);let t=y.get(e);if(t!==void 0&&Date.now()>=t)throw new c._}async function C(e,t,n){let r=Promise.resolve(e);return n?.(r),t?new Promise((e,n)=>{let i=!1,a,o=()=>{t.removeEventListener(`abort`,l),a&&clearTimeout(a)},s=e=>{i||(i=!0,o(),n(e))},l=()=>s(x(t));t.addEventListener(`abort`,l,{once:!0});let u=y.get(t);u!==void 0&&(a=setTimeout(()=>s(new c._),Math.max(0,u-Date.now()))),r.then(n=>{if(!i){try{S(t)}catch(e){s(e);return}i=!0,o(),e(n)}},s);try{S(t)}catch(e){s(e)}}):r}function w(e){try{Promise.resolve(e()).catch(()=>void 0)}catch{}}function T(e){if(e)return{info:(t,n)=>w(()=>e.info(t,n)),warn:(t,n)=>w(()=>e.warn(t,n)),error:(t,n)=>w(()=>e.error(t,n)),debug:(t,n)=>w(()=>e.debug(t,n))}}function E(e){if(e)return{startSpan(t,n){let r;try{let i=e.startSpan(t,n);i&&typeof i.then==`function`?w(()=>i):r=i}catch{}let i=!1,a={setAttribute(e,t){return w(()=>r?.setAttribute(e,t)),a},addEvent(e,t){return w(()=>r?.addEvent(e,t)),a},end(){i||(i=!0,w(()=>r?.end()))}};return a}}}async function D(e,t,n,r){n=T(n);let{attempts:i=1,backoff:a=`fixed`,delayMs:o=0}=t??{},s=r?.limits?.maxRetryAttempts??5,c=r?.limits?.maxRetryDelayMs??3e4;if(!Number.isSafeInteger(i)||i<1||i>s)throw Error(`[PipeX] Invalid retry attempts: ${i}`);if(!Number.isSafeInteger(o)||o<0||o>c)throw Error(`[PipeX] Invalid retry delay: ${o}`);let l;for(let t=0;t<i;t++){S(r?.signal);try{return await C(e(),r?.signal,r?.track)}catch(e){if(S(r?.signal),l=e instanceof Error?e:Error(String(e)),t<i-1){let e=a===`exponential`?o*2**t:o;n?.debug(`[PipeX] Retry ${t+1}/${i} after ${e}ms`,{error:l.message}),e>0&&await new Promise((t,n)=>{let i=()=>r?.signal?.removeEventListener(`abort`,o),a=setTimeout(()=>{i(),t()},Math.min(e,c)),o=()=>{clearTimeout(a),i(),n(r?.signal?.reason??Error(`[PipeX] Operation aborted`))};r?.signal?.addEventListener(`abort`,o,{once:!0}),r?.signal?.aborted&&o()})}}}throw l}const O=new f.Packr({useRecords:!1,moreTypes:!0,structuredClone:!1,bundleStrings:!1}),k=new f.Unpackr({useRecords:!1,structuredClone:!1});function A(e){return typeof e.createStream==`function`}function j(e){let t=`${e.name}@${e.version}`,n=e.reversible,r=e.streaming,i=e.reverse,a=e.createStream,o=typeof i==`function`&&i!==c.i.prototype.reverse;if(n!==void 0&&typeof n!=`boolean`)throw new c.d(t,`reversible`,`MUST_BE_BOOLEAN`);if(r!==void 0&&typeof r!=`boolean`)throw new c.d(t,`streaming`,`MUST_BE_BOOLEAN`);if(n===!0&&!o)throw new c.d(t,`reversible`,`MISSING_IMPLEMENTATION`);if(r===!1&&typeof a==`function`)throw new c.d(t,`streaming`,`CONFLICTING_IMPLEMENTATION`);let s=n!==!1&&o,l=r!==!1;return Object.freeze({process:!0,reverse:s,streaming:l,streamMode:l?typeof a==`function`?`native`:`fallback`:`none`})}function M(e,t){let n=j(e);switch(t){case`process`:return n.process;case`reverse`:return n.reverse;case`stream`:return n.streaming;default:throw TypeError(`[PipeX] Unknown plugin operation`)}}function N(e){return M(e,`reverse`)}function P(e){let t=e.find(e=>!N(e));if(t)throw new c.S(`${t.name}@${t.version}`)}function F(e){let t=e.find(e=>!M(e,`stream`));if(t)throw new c.C(`${t.name}@${t.version}`)}function I(e){return e===null?`null`:Buffer.isBuffer(e)?`buffer`:Array.isArray(e)?`array`:typeof e==`object`?`object`:typeof e}function L(e){return Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):typeof e==`object`&&e?O.pack(e):typeof e==`number`||typeof e==`boolean`?Buffer.from(String(e)):Buffer.from(String(e??``),`utf-8`)}const R=Object.freeze([`buffer`,`object`,`array`,`string`,`number`,`boolean`,`null`,`undefined`,`bigint`,`json`]);function z(e){if(typeof e!=`string`||!R.includes(e))throw Error(`[PipeX] Unsupported original type`)}function B(e,t,n=c.t.maxFrameBytes){if(z(t),!Buffer.isBuffer(e))throw Error(`[PipeX] Invalid binary payload`);switch(t){case`array`:case`object`:{_(e,n,1);let r;try{r=k.unpack(e)}catch{throw Error(`[PipeX] fromBuffer: invalid MessagePack input`)}if(t===`array`?!Array.isArray(r):typeof r!=`object`||!r||Array.isArray(r))throw Error(`[PipeX] Decoded value does not match the expected type`);return r}case`json`:try{return JSON.parse(e.toString(`utf-8`))}catch{throw Error(`[PipeX] fromBuffer: invalid JSON input`)}case`number`:{let t=Number(e.toString(`utf-8`));if(Number.isNaN(t))throw Error(`[PipeX] fromBuffer: invalid number`);return t}case`bigint`:try{return BigInt(e.toString(`utf-8`))}catch{throw Error(`[PipeX] fromBuffer: invalid bigint`)}case`boolean`:{let t=e.toString(`utf-8`);if(t!==`true`&&t!==`false`)throw Error(`[PipeX] fromBuffer: invalid boolean`);return t===`true`}case`string`:return e.toString(`utf-8`);case`null`:case`undefined`:if(e.length!==0)throw Error(`[PipeX] Payload does not match the expected empty type`);return t===`null`?null:void 0;default:return e}}function V(e,t={},n,r,i,a){return{requestId:e,timestamp:Date.now(),metadata:t,logger:n,span:r,signal:i,limits:a}}function ee(e){return{__pipex_v:1,plugins:e.map(e=>`${e.name}@${e.version}`),ts:Date.now()}}function H(e){let t=!1,n=Buffer.from(O.pack(e));return new d.Transform({transform(e,r,i){t||(t=!0,this.push(n)),i(null,e)},flush(e){t||this.push(n),e()}})}function U(e){let t=!1;return new d.Transform({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){if(!t&&(t=!0,h(n))){try{e(n),i()}catch(e){i(e)}return}i(null,n)}})}var W=class extends f.UnpackrStream{#e=0;#t;constructor(e={},t=c.t.maxInputBytes){super(e),this.#t=t}_transform(e,t,n){if(e.length>this.#t-this.#e){n(Error(`[PipeX] Serialized input exceeds ${this.#t} bytes`));return}this.#e+=e.length,super._transform(e,t,e=>{n(e?Error(`[PipeX] Invalid MessagePack input`):void 0)})}};function G(){return new f.PackrStream({useRecords:!1,moreTypes:!0,structuredClone:!1,bundleStrings:!1})}function K(e=c.t.maxInputBytes){return new W({useRecords:!1,structuredClone:!1},e)}function q(e,t){let n=0;return new d.Transform({transform(r,i,a){if(r.length>e-n){a(Error(`[PipeX] ${t} exceeds ${e} bytes`));return}n+=r.length,a(null,r)}})}function J(e){let t=0;return new d.Transform({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){if(t>=e){i(Error(`[PipeX] Application frame count exceeds ${e}`));return}t++,i(null,n)}})}function Y(e,t,n){let r=typeof e==`string`?Buffer.byteLength(e):Buffer.isBuffer(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer?e.byteLength:void 0;if(r!==void 0&&r>t)throw Error(`[PipeX] ${n} exceeds ${t} bytes`)}function X(e,t){return new d.Transform({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){try{Y(n,e,t),i(null,n)}catch(e){i(e)}}})}function Z(e,t,n,r,i,a,o){r=T(r),i=E(i);let s=o?.requestId??`stream-${(0,l.randomUUID)()}`;return new d.Transform({async transform(l,u,d){let f=i?.startSpan(`plugin:${e.name}`,{requestId:s});f?.setAttribute(`plugin.version`,e.version),f?.setAttribute(`mode`,t?`reverse`:`process`);try{o?.signal.throwIfAborted();let i=V(s,{},r,f,o?.signal,o?.limits);if(t&&!N(e))throw new c.S(`${e.name}@${e.version}`);let a=t?e.reverse.bind(e):e.process.bind(e),u=await D(()=>a(l,i),e.retryOptions,r,{signal:o?.signal,limits:o?.limits,track:o?.track}),p=o?.limits.maxOutputBytes??c.t.maxOutputBytes;if(!Buffer.isBuffer(u)||u.length>p)throw Error(`[PipeX] Plugin output exceeds ${p} bytes`);n?.(u.length),f?.addEvent(`processed`,{bytes:u.length}),d(null,u)}catch(t){let n=t instanceof Error?t:Error(String(t));if(r?.error(`[PipeX] Plugin ${e.name} failed after retries`,{requestId:s,error:n.message}),f?.setAttribute(`error`,!0),f?.addEvent(`error`,{message:n.message}),a&&a.writable){r?.warn(`[PipeX] Diverting failed chunk to DLQ`,{requestId:s,plugin:e.name});try{a.write(l)||await new Promise((e,t)=>{let n=()=>{c(),e()},r=e=>{c(),t(e)},i=()=>{c(),t(o?.signal.reason instanceof Error?o.signal.reason:Error(`[PipeX] Operation aborted`))},s=()=>{c(),t(Error(`[PipeX] Stream closed while writing to DLQ`))},c=()=>{a.off(`drain`,n),a.off(`error`,r),o?.signal.removeEventListener(`abort`,i),this.off(`close`,s)};a.once(`drain`,n),a.once(`error`,r),this.once(`close`,s),o?.signal.aborted?i():o?.signal.addEventListener(`abort`,i,{once:!0})}),d(n)}catch(e){d(e)}}else d(n)}finally{f?.end()}}})}function Q(){return new d.Transform({writableObjectMode:!0,readableObjectMode:!1,transform(e,t,n){try{n(null,JSON.stringify(e)+`
2
+ `)}catch(e){n(Error(`[PipeX] NDJSON: ${e.message}`))}}})}function te(e,t,n=!1,r,i,a,o,s){return i=T(i),a=E(a),F(e),n&&P(e),(n?[...e].reverse():e).flatMap((e,l)=>{let u=A(e)?e.createStream(t,s):Z(e,n,r,i,a,o,s),f=q(s?.limits.maxOutputBytes??c.t.maxOutputBytes,`output after plugin ${e.name}#${l}`);if(!A(e))return[u,f];let p=a?.startSpan(`plugin:${e.name}`,{requestId:s?.requestId??`stream`}),m=!1,h=e=>{m||(m=!0,e&&p?.setAttribute(`error`,!0),p?.end())};return[u,new d.Transform({transform(e,t,n){r?.(e.length),p?.addEvent(`processed`,{bytes:e.length}),n(null,e)},final(e){h(),e()},destroy(e,t){h(e),t(e)}}),f]})}async function ne(e,t,n,r){await(0,u.pipeline)(e,...t,n,r??{})}function $(e,t){let n=p.default.relative(t,e);if(n===`..`||n.startsWith(`..${p.default.sep}`)||p.default.isAbsolute(n))throw Error(`[PipeX] Path is outside the allowed root`)}function re(e,t){let n=p.default.resolve(e);if(!(0,m.existsSync)(n))throw Error(`[PipeX] File not found: ${n}`);let r=m.realpathSync.native(p.default.resolve(t??process.cwd())),i=m.realpathSync.native(n);return $(i,r),i}function ie(e,t){let n=m.realpathSync.native(p.default.resolve(t??process.cwd())),r=p.default.resolve(e),i=m.realpathSync.native(p.default.dirname(r));$(i,n);let a=p.default.join(i,p.default.basename(r));return(0,m.existsSync)(a)&&$(m.realpathSync.native(a),n),a}Object.defineProperty(exports,`A`,{enumerable:!0,get:function(){return ne}}),Object.defineProperty(exports,`B`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`F`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`H`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`I`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,`L`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,`N`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`P`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,`R`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`U`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`V`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`W`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return`__pipex_v`}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return 268435456}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return 65536}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,`z`,{enumerable:!0,get:function(){return b}});
@@ -0,0 +1 @@
1
+ import{A as e,B as t,C as n,E as r,F as i,H as a,I as o,L as s,N as c,O as l,P as u,R as d,S as f,T as p,U as m,V as h,_ as g,a as _,b as v,c as y,d as b,g as x,h as S,k as C,l as w,p as T,s as E,t as D,u as O,v as k,w as A,x as j,y as ee,z as M}from"./core-BOdvxKBq.mjs";import{t as N,w as P}from"./resourceLimits-C1HHDwXQ.mjs";import{createRequire as te}from"node:module";import{randomUUID as F}from"node:crypto";import{Duplex as I,PassThrough as L,Readable as R,Transform as z,Writable as B}from"node:stream";import"zod";import V from"node:path";import{closeSync as H,constants as U,fstatSync as W,openSync as G,realpathSync as K}from"node:fs";import{EventEmitter as q}from"node:events";let J;const Y=()=>J??=te(import.meta.url)(`koffi`),X=e=>{throw Error(`[PipeX] Secure file `+e+` failed`)},Z=e=>{let t=V.parse(e).root;return e.slice(t.length).split(V.sep).filter(Boolean)};function ne(e,t,n){let r=K.native(V.resolve(n??process.cwd())),i=y(e,r),a=C(t,r);if(i===a)throw Error(`[PipeX] Input and output must be different files`);return process.platform===`win32`?ae(i,a,r):Q(i,a)}let re;function ie(){let e=Y(),t=e.load(`kernel32.dll`),n=e.load(`ntdll.dll`),r=e.struct({Length:`uint16_t`,MaximumLength:`uint16_t`,Buffer:`str16`}),i=e.struct({Length:`uint32_t`,RootDirectory:`intptr_t`,ObjectName:e.pointer(r),Attributes:`uint32_t`,SecurityDescriptor:`void *`,SecurityQualityOfService:`void *`}),a=e.struct({Status:`intptr_t`,Information:`uintptr_t`});return{setRelativeInfo:n.func(`__stdcall`,`NtSetInformationFile`,`int32_t`,[`intptr_t`,e.out(e.pointer(a)),`void *`,`uint32_t`,`int`]),relativeOpen:n.func(`__stdcall`,`NtCreateFile`,`int32_t`,[`_Out_ intptr_t *`,`uint32_t`,e.pointer(i),e.out(e.pointer(a)),`void *`,`uint32_t`,`uint32_t`,`uint32_t`,`uint32_t`,`void *`,`uint32_t`]),attributesSize:e.sizeof(i),pointerBytes:e.sizeof(`void *`),finalPath:t.func(`__stdcall`,`GetFinalPathNameByHandleW`,`uint32_t`,[`intptr_t`,`_Out_ void *`,`uint32_t`,`uint32_t`]),open:t.func(`__stdcall`,`CreateFileW`,`intptr_t`,[`str16`,`uint32_t`,`uint32_t`,`void *`,`uint32_t`,`uint32_t`,`void *`]),info:t.func(`__stdcall`,`GetFileInformationByHandle`,`int`,[`intptr_t`,`_Out_ void *`]),type:t.func(`__stdcall`,`GetFileType`,`uint32_t`,[`intptr_t`]),read:t.func(`__stdcall`,`ReadFile`,`int`,[`intptr_t`,`_Out_ void *`,`uint32_t`,`_Out_ uint32_t *`,`void *`]),write:t.func(`__stdcall`,`WriteFile`,`int`,[`intptr_t`,`void *`,`uint32_t`,`_Out_ uint32_t *`,`void *`]),setInfo:t.func(`__stdcall`,`SetFileInformationByHandle`,`int`,[`intptr_t`,`int`,`void *`,`uint32_t`]),close:t.func(`__stdcall`,`CloseHandle`,`int`,[`intptr_t`])}}function ae(e,t,n){let r=re??=ie(),i=[],a=new Map,o=new Set,s=!1,c=!1,l,u,d=e=>{let t=Buffer.alloc(52);return r.info(e,t)||X(`handle inspection`),t},f=(e,t,n,a,o)=>{let s=r.open(e,t,n,null,a,2097152|(o?33554432:128),null);BigInt(s)===-1n&&X(`open`),i.push(s);let c=d(s).readUInt32LE(0);return(c&1024||!!(c&16)!==o||r.type(s)!==1)&&X(`file type validation`),s},p=(e,t,n,a,o,s=!1)=>{(!t||t===`.`||t===`..`||/[\\/:]/.test(t))&&X(`relative name validation`);let c=[0],l=r.relativeOpen(c,(n|1048576)>>>0,{Length:r.attributesSize,RootDirectory:e,ObjectName:{Length:Buffer.byteLength(t,`utf16le`),MaximumLength:Buffer.byteLength(t,`utf16le`)+2,Buffer:t},Attributes:64,SecurityDescriptor:null,SecurityQualityOfService:null},{},null,128,o?3:1,a?2:1,2097184|(o?1:64),null,0);if(l<0){if(s&&l>>>0==3221225524)return;X(`relative open`)}let f=c[0];i.push(f),a&&(u=f);let p=d(f).readUInt32LE(0);return(p&1024||!!(p&16)!==o||r.type(f)!==1)&&X(`relative type validation`),f},m=(e,t)=>{let r=``,i=t;for(let t of Z(V.relative(n,V.dirname(e)))){r=V.join(r,t);let e=a.get(r.toLowerCase());e===void 0?(i=p(i,t,2147483648,!1,!0),a.set(r.toLowerCase(),i)):i=e}return i},h,g=()=>{for(let e of i.reverse())r.close(e);i.length=0};try{let a=f(n,2147483648,3,3,!0),o=Buffer.alloc(65536),s=r.finalPath(a,o,o.length/2,0);(!s||s>=o.length/2)&&X(`root identity validation`),V.normalize((e=>e.startsWith(`\\\\?\\UNC\\`)?`\\\\`+e.slice(8):e.startsWith(`\\\\?\\`)?e.slice(4):e)(o.subarray(0,s*2).toString(`utf16le`))).toLowerCase()!==V.normalize(n).toLowerCase()&&X(`root identity validation`);let c=m(e,a);h=m(t,a),l=p(c,V.basename(e),2147483648,!1,!1);let g=p(h,V.basename(t),2147483648,!1,!1,!0);if(g!==void 0)try{let e=d(l),t=d(g);if(e.readUInt32LE(28)===t.readUInt32LE(28)&&e.subarray(44,52).equals(t.subarray(44,52)))throw Error(`[PipeX] Input and output must be different files`);t.readUInt32LE(0)&1024&&X(`output reparse validation`)}finally{r.close(g),i.pop()}let _=`.pipex-`+F()+`.tmp`;u=p(h,_,1073807488,!0,!1)}catch(e){throw u!==void 0&&r.setInfo(u,4,Buffer.from([1]),1),g(),e}let _=(e,t)=>{let n=[0],i=new Promise((i,a)=>{(e?r.write:r.read).async(e?u:l,t,t.length,n,null,(t,r)=>{t||!r?a(Error(`[PipeX] Secure file `+(e?`write`:`read`)+` failed`)):i(n[0])})});return o.add(i),i.then(()=>o.delete(i),()=>o.delete(i)),i},v=!1,y=new R({highWaterMark:D,read(){if(v)return;v=!0;let e=Buffer.allocUnsafe(D);_(!1,e).then(t=>{v=!1,this.destroyed||this.push(t?e.subarray(0,t):null)},e=>{v=!1,this.destroy(e)})}}),b=new B({highWaterMark:D,write(e,t,n){let r=(async()=>{let t=0;for(;t<e.length;){c&&X(`write after disposal`);let n=await _(!0,e.subarray(t));n||X(`write progress`),t+=n}})();o.add(r),r.then(()=>{o.delete(r),n()},e=>{o.delete(r),n(e)})}});return{source:y,destination:b,commit(){(c||s)&&X(`commit state`);let e=r.pointerBytes,n=e===8?8:4,i=n+e,a=i+4,o=Buffer.from(V.basename(t)+`\0`,`utf16le`),l=Buffer.alloc(a+o.length);l[0]=1,e===8?l.writeBigUInt64LE(BigInt(h),n):l.writeUInt32LE(Number(h),n),l.writeUInt32LE(o.length-2,i),o.copy(l,a);let d=r.setRelativeInfo(u,{},l,l.length,10);d<0&&X(`atomic rename status `+(d>>>0).toString(16)),s=!0},async dispose(){c||(c=!0,y.destroy(),b.destroy(),await Promise.allSettled([...o]),s||r.setInfo(u,4,Buffer.from([1]),1),g())}}}let oe;function se(){let e=Y().load(null);return{read:e.func(`intptr_t read(int fd, _Out_ void *buffer, size_t count)`),write:e.func(`intptr_t write(int fd, const void *buffer, size_t count)`),fcntl:e.func(`int fcntl(int fd, int command, int argument)`),openat:e.func(`int openat(int dirfd, const char *path, int flags, unsigned int mode)`),mkdirat:e.func(`int mkdirat(int dirfd, const char *path, unsigned int mode)`),renameat:e.func(`int renameat(int oldfd, const char *oldname, int newfd, const char *newname)`),unlinkat:e.func(`int unlinkat(int dirfd, const char *path, int flags)`)}}function Q(e,t){let n=oe??=se(),r=[],i=U.O_NOFOLLOW,a=U.O_DIRECTORY;(!i||!a)&&X(`platform support`);let o=()=>{for(let e of r.reverse())try{H(e)}catch{}r.length=0},s=(e,t,a,o=0)=>{let s=n.openat(e,t,a|i,o);return s<0&&X(`relative open`),r.push(s),n.fcntl(s,2,1)<0&&X(`descriptor inheritance protection`),s},c=e=>{let t=G(V.parse(e).root,U.O_RDONLY|a);r.push(t);for(let n of Z(V.dirname(e)))t=s(t,n,U.O_RDONLY|a);return t},l=`.pipex-`+F(),u,d,f,p,m=!1,h=!1,g=!1,_=new Set,v=process.platform===`linux`?512:process.platform===`darwin`?128:process.platform===`openbsd`?8:2048,y=()=>{d!==void 0&&!m&&n.unlinkat(d,`data`,0),u!==void 0&&g&&n.unlinkat(u,l,v),o()};try{let r=c(e);u=c(t),f=s(r,V.basename(e),U.O_RDONLY|U.O_NONBLOCK);let o=W(f,{bigint:!0});o.isFile()||X(`input type validation`);let m=n.openat(u,V.basename(t),U.O_RDONLY|i|U.O_NONBLOCK,0);if(m>=0)try{let e=W(m,{bigint:!0});if(o.dev===e.dev&&o.ino===e.ino)throw Error(`[PipeX] Input and output must be different files`)}finally{H(m)}n.mkdirat(u,l,448)!==0&&X(`temporary directory creation`),g=!0,d=s(u,l,U.O_RDONLY|a);let h=W(d);(h.mode&63||h.uid!==process.geteuid?.())&&X(`temporary directory permissions`),p=s(d,`data`,U.O_WRONLY|U.O_CREAT|U.O_EXCL,384)}catch(e){throw y(),e}let b=(e,t)=>{let r=new Promise((r,i)=>{(e?n.write:n.read).async(e?p:f,t,t.length,(e,t)=>{e||t<0?i(Error(`[PipeX] Secure relative file I/O failed`)):r(Number(t))})});return _.add(r),r.then(()=>_.delete(r),()=>_.delete(r)),r},x=!1,S=new R({highWaterMark:D,read(){if(x)return;x=!0;let e=Buffer.allocUnsafe(D);b(!1,e).then(t=>{x=!1,this.destroyed||this.push(t?e.subarray(0,t):null)},e=>{x=!1,this.destroy(e)})}}),C=new B({highWaterMark:D,write(e,t,n){let r=(async()=>{let t=0;for(;t<e.length;){h&&X(`write after disposal`);let n=await b(!0,e.subarray(t));n||X(`relative write progress`),t+=n}})();_.add(r),r.then(()=>{_.delete(r),n()},e=>{_.delete(r),n(e)})}});return{source:S,destination:C,commit(){(h||m)&&X(`commit state`),n.renameat(d,`data`,u,V.basename(t))!==0&&X(`atomic relative rename`),m=!0},async dispose(){h||(h=!0,S.destroy(),C.destroy(),await Promise.allSettled([..._]),y())}}}var ce=class{#e;constructor(e){this.#e=e}async#t(e,n,r,i,a){let o=ne(e,n,r);try{await a(o.source,o.destination),t(i),o.commit()}finally{await o.dispose()}}#n(e,t){return{requestId:e,signal:t,track:t=>this.#e.trackWork(e,t),limits:this.#e.limits,logger:this.#e.logger,tracer:this.#e.tracer}}async process(n,r,i,a={}){let o=this.#e.createOperationSignal(a);t(o);let s=this.#e.startRequest();try{if(this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw file streams`);await this.#t(n,r,i,o,async(t,n)=>{let r=this.#n(s,o);await e(t,[T(this.#e.limits.maxInputBytes,`input`),...j(this.#e.plugins,`compress`,!1,e=>this.#e.emitProgress(e,s),this.#e.logger,this.#e.tracer,this.#e.dlq,r),T(this.#e.limits.maxOutputBytes,`output`)],n,{signal:o})}),await d(this.#e.emitAudit({requestId:s,operation:`process`,metadata:{controller:`file`}}),o,e=>this.#e.trackWork(s,e)),t(o),this.#e.endRequest(s)}catch(e){throw this.#e.emitError(e,s),e}}async reverse(n,r,i,a={}){let o=this.#e.createOperationSignal(a);t(o);let s=this.#e.startRequest();try{if(this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw file streams`);await this.#t(n,r,i,o,async(t,n)=>{let r=this.#n(s,o);await e(t,[T(this.#e.limits.maxInputBytes,`input`),...j(this.#e.plugins,`decompress`,!0,e=>this.#e.emitProgress(e,s),this.#e.logger,this.#e.tracer,this.#e.dlq,r),T(this.#e.limits.maxOutputBytes,`output`)],n,{signal:o})}),await d(this.#e.emitAudit({requestId:s,operation:`reverse`,metadata:{controller:`file`}}),o,e=>this.#e.trackWork(s,e)),t(o),this.#e.endRequest(s)}catch(e){throw this.#e.emitError(e,s),e}}async pack(n,r,i,o={}){let s=this.#e.createOperationSignal(o);t(s);let c=this.#e.startRequest();try{await this.#t(n,r,i,s,async(t,n)=>{await e(t,[T(this.#e.limits.maxInputBytes,`input`),v(this.#e.limits.maxFrames),S(this.#e.limits.maxFrameBytes,`MessagePack frame`),f(),k(x([])),a(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),T(this.#e.limits.maxOutputBytes,`output`)],n,{signal:s})}),await d(this.#e.emitAudit({requestId:c,operation:`pack`,metadata:{controller:`file`}}),s,e=>this.#e.trackWork(c,e)),t(s),this.#e.endRequest(c)}catch(e){throw this.#e.emitError(e,c),e}}async unpack(r,i,o,s={}){let c=this.#e.createOperationSignal(s);t(c);let l=this.#e.startRequest();try{await this.#t(r,i,o,c,async(t,r)=>{let i=n(this.#e.limits.maxInputBytes),o=g(e=>{let t=[];if(e.plugins.length!==t.length||e.plugins.some((e,n)=>e!==t[n]))throw Error(`[PipeX] Manifest plugin chain does not match the configured engine`);this.#e.emit(`manifest`,e,l)}),s=ee(),u=new z({writableObjectMode:!0,readableObjectMode:!0,transform:(e,t,n)=>{try{this.#e.validate(e),n(null,e)}catch(e){n(e)}}});await e(t,[T(this.#e.limits.maxInputBytes,`input`),a(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),i,o,v(this.#e.limits.maxFrames),u,s,T(this.#e.limits.maxOutputBytes,`output`)],r,{signal:c})}),await d(this.#e.emitAudit({requestId:l,operation:`unpack`,metadata:{controller:`file`}}),c,e=>this.#e.trackWork(l,e)),t(c),this.#e.endRequest(l)}catch(e){throw this.#e.emitError(e,l),e}}},le=class{#e;constructor(e){this.#e=e}pack(e){try{w(e,Math.min(this.#e.limits.maxInputBytes,this.#e.limits.maxFrameBytes),`Serialization input`);let t=_.pack(e);if(t.length>this.#e.limits.maxInputBytes)throw Error(`[PipeX] Packed input exceeds configured limit`);if(h(t,this.#e.limits.maxFrameBytes,1),t.length>this.#e.limits.maxOutputBytes)throw Error(`[PipeX] Packed output exceeds configured limit`);return t}catch(e){throw e instanceof Error&&e.message.startsWith(`[PipeX]`)?e:new P({stage:`pack`})}}unpack(e){try{if(e.byteLength>this.#e.limits.maxInputBytes)throw Error(`[PipeX] Serialized input exceeds configured limit`);return h(e,this.#e.limits.maxFrameBytes,1),E.unpack(e)}catch(e){throw e instanceof Error&&e.message.startsWith(`[PipeX]`)?e:new P({stage:`unpack`})}}#t=new WeakMap;async run(e,n={}){let r=this.#e.createOperationSignal(n);t(r);let i=A(e);O(i);let a=this.#e.plugins,o=[...this.#e.pipeline],s=this.#e.limits,f=this.#e.startRequest({operation:`run`}),p=Date.now(),m=this.#e.tracer?.startSpan(`binary:run`,{requestId:f});try{m?.setAttribute(`input.type`,i),this.#e.validate(e),w(e,s.maxInputBytes,`Input`);let n=c(e);if(n.length>s.maxInputBytes)throw Error(`[PipeX] Input exceeds configured limit`);(i===`object`||i===`array`)&&h(n,s.maxFrameBytes,1);let g=Object.create(null);for(let e of a){let t=Date.now(),a=this.#e.tracer?.startSpan(`plugin:${e.name}`,{requestId:f});try{a?.setAttribute(`mode`,`process`);let t=l(f,{originalType:i},this.#e.logger,a,r,s);if(n=await u(()=>e.process(n,t),e.retryOptions,this.#e.logger,{signal:r,limits:s,track:e=>this.#e.trackWork(f,e)}),!Buffer.isBuffer(n)||n.length>s.maxOutputBytes)throw Error(`[PipeX] Plugin output exceeds configured limit`)}catch(e){throw a?.setAttribute(`error`,!0),e}finally{a?.end()}g[e.name]=Date.now()-t,this.#e.emit(`plugin:after`,e.name,g[e.name])}if(n.length>s.maxOutputBytes)throw Error(`[PipeX] Output exceeds configured limit`);t(r);let _=Date.now()-p;await d(this.#e.emitAudit({requestId:f,operation:`process`,metadata:{inputType:i,durationMs:_}}),r,e=>this.#e.trackWork(f,e)),t(r),this.#t.set(n,i);let v={data:n,originalType:i,pipeline:o,metrics:{durationMs:_,steps:g}};return m?.setAttribute(`duration_ms`,_),this.#e.endRequest(f,_),v}catch(e){throw m?.setAttribute(`error`,!0),this.#e.emitError(e,f),e}finally{m?.end(),this.#e.releaseRequest(f)}}async undo(e,n,r={}){let i=Buffer.isBuffer(e),a,o,s;if(i)O(n),a=e,o=n,s=r;else{let t=e;if(!t||typeof t!=`object`||!Buffer.isBuffer(t.data)||!Array.isArray(t.pipeline)||t.pipeline.length>256||!t.pipeline.every(e=>typeof e==`string`&&e.length<=512)||!t.metrics||!Number.isFinite(t.metrics.durationMs)||t.metrics.durationMs<0||!t.metrics.steps||typeof t.metrics.steps!=`object`||Array.isArray(t.metrics.steps)||!Object.values(t.metrics.steps).every(e=>typeof e==`number`&&Number.isFinite(e)&&e>=0))throw Error(`[PipeX] Invalid EngineResult`);if(O(t.originalType),n!==void 0&&(typeof n!=`object`||!n))throw Error(`[PipeX] Invalid undo options`);let r=n,i=r?.expectedType??this.#t.get(t.data);if(i===void 0)throw Error(`[PipeX] Transported EngineResult requires a trusted expectedType`);if(O(i),i!==t.originalType)throw Error(`[PipeX] Result type does not match the expected type`);a=t.data,o=i,s=r??{}}let f=this.#e.createOperationSignal(s);t(f);let m=this.#e.plugins;b(m);let h=this.#e.limits;if(a.length>h.maxInputBytes)throw Error(`[PipeX] Undo input exceeds configured limit`);let g=this.#e.startRequest({operation:`undo`,originalType:o}),_=this.#e.tracer?.startSpan(`binary:undo`,{requestId:g});try{if(i&&m.length===0&&a.length>0){let e;try{e=this.unpackWithManifest(a)}catch{}if(e){if(e.manifest.plugins.length!==0)throw Error(`[PipeX] Manifest plugin chain does not match the configured engine`);if(A(e.data)!==o)throw Error(`[PipeX] Manifest data does not match the expected type`);a=c(e.data)}}for(let e of[...m].reverse()){let t=this.#e.tracer?.startSpan(`plugin:${e.name}`,{requestId:g});try{t?.setAttribute(`mode`,`reverse`);let n=l(g,{originalType:o},this.#e.logger,t,f,h);if(a=await u(()=>e.reverse(a,n),e.retryOptions,this.#e.logger,{signal:f,limits:h,track:e=>this.#e.trackWork(g,e)}),!Buffer.isBuffer(a)||a.length>h.maxOutputBytes)throw Error(`[PipeX] Plugin output exceeds configured limit`)}catch(e){throw t?.setAttribute(`error`,!0),e}finally{t?.end()}this.#e.emit(`plugin:after`,e.name,0)}if(a.length>h.maxOutputBytes)throw Error(`[PipeX] Output exceeds configured limit`);t(f);let e=p(a,o,h.maxFrameBytes);return this.#e.validate(e),t(f),await d(this.#e.emitAudit({requestId:g,operation:`reverse`,metadata:{originalType:o}}),f,e=>this.#e.trackWork(g,e)),t(f),this.#e.endRequest(g),e}catch(e){throw _?.setAttribute(`error`,!0),this.#e.emitError(e,g),e}finally{_?.end(),this.#e.releaseRequest(g)}}packWithManifest(e){if(this.#e.plugins.length>0)throw Error(`[PipeX] packWithManifest is serialization-only; use binary.run for plugin transforms`);let t=x([]);w(e,Math.min(this.#e.limits.maxInputBytes,this.#e.limits.maxFrameBytes),`Serialization input`);let n=_.pack(t),r=_.pack(e);if(h(n,this.#e.limits.maxFrameBytes,1),h(r,this.#e.limits.maxFrameBytes,1),n.length+r.length>Math.min(this.#e.limits.maxInputBytes,this.#e.limits.maxOutputBytes))throw Error(`[PipeX] Serialized input exceeds configured limit`);return Buffer.concat([n,r])}unpackWithManifest(e){if(e.length>this.#e.limits.maxInputBytes)throw Error(`[PipeX] Serialized input exceeds configured limit`);h(e,this.#e.limits.maxFrameBytes,2);let t=[];try{E.unpackMultiple(e,e=>{if(t.length>=2)throw Error(`[PipeX] Frame count exceeds configured limit`);t.push(e)})}catch(e){throw e instanceof Error&&e.message.startsWith(`[PipeX]`)?e:Error(`[PipeX] binary.unpackWithManifest: invalid MessagePack input`)}if(t.length<2)throw Error(`[PipeX] binary.unpackWithManifest: buffer contains fewer than 2 frames`);if(!m(t[0]))throw Error(`[PipeX] binary.unpackWithManifest: first frame is not a PipeXManifest`);return{manifest:t[0],data:t[1]}}},ue=class{#e;constructor(e){this.#e=e}#t(e,t){return{requestId:e,signal:t,track:t=>this.#e.trackWork(e,t),limits:this.#e.limits,logger:this.#e.logger,tracer:this.#e.tracer}}#n(e,t){return I.from({writable:e,readable:t})}#r(n,r,i){let a=this.#e.createOperationSignal(i);if(t(a),this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw byte streams`);let o=this.#e.startRequest(),s=this.#t(o,a),c=r?`decompress`:`compress`,l;try{l=j(this.#e.plugins,c,r,e=>this.#e.emitProgress(e,o),this.#e.logger,this.#e.tracer,this.#e.dlq,s)}catch(e){throw this.#e.emitError(e,o),e}let u=new L,f,p=new B({write(e,t,r){if(u.destroyed){let e=n.errored??u.errored;r(e instanceof Error?e:Error(`[PipeX] Stream pipeline is closed`));return}u.write(e,t,r)},final(e){f=e,u.end()},destroy(e,t){f=void 0,u.destroyed||u.destroy(e??void 0),t(e)}}),m=e=>{let t=f;f=void 0,t?t(e):e&&!p.destroyed&&p.destroy(e)};return e(u,[T(this.#e.limits.maxInputBytes,`input`),...l,T(this.#e.limits.maxOutputBytes,`output`)],n,{signal:a}).then(async()=>{await d(this.#e.emitAudit({requestId:o,operation:r?`reverse`:`process`,metadata:{controller:`stream`}}),a,e=>this.#e.trackWork(o,e)),t(a),this.#e.endRequest(o),m()}).catch(e=>{let t=e instanceof Error?e:Error(String(e));this.#e.emitError(t,o),m(t)}),p}into(e,t={}){return this.#r(e,!1,t)}reverseInto(e,t={}){return this.#r(e,!0,t)}pack(n={}){let r=this.#e.createOperationSignal(n);t(r);let i=this.#e.startRequest({operation:`pack`}),o=new L({objectMode:!0}),s=new L,c=[v(this.#e.limits.maxFrames),S(this.#e.limits.maxFrameBytes,`MessagePack frame`),f(),k(x([])),a(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),T(this.#e.limits.maxOutputBytes,`output`)],l=this.#n(o,s);return e(o,c,s,{signal:r}).then(async()=>{await d(this.#e.emitAudit({requestId:i,operation:`pack`,metadata:{controller:`stream`}}),r,e=>this.#e.trackWork(i,e)),t(r),this.#e.endRequest(i)}).catch(e=>{this.#e.emitError(e,i),l.destroy(e instanceof Error?e:Error(String(e)))}),l}unpack(r={}){let i=this.#e.createOperationSignal(r);t(i);let o=this.#e.startRequest({operation:`unpack`}),s=new L,c=new L({objectMode:!0}),l=n(this.#e.limits.maxInputBytes),u=g(e=>{let t=[];if(e.plugins.length!==t.length||e.plugins.some((e,n)=>e!==t[n]))throw Error(`[PipeX] Manifest plugin chain does not match the configured engine`);this.#e.emit(`manifest`,e,o)}),f=new z({writableObjectMode:!0,readableObjectMode:!0,transform:(e,t,n)=>{try{this.#e.validate(e),n(null,e)}catch(e){n(e)}}}),p=[T(this.#e.limits.maxInputBytes,`input`),a(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),l,u,v(this.#e.limits.maxFrames),f],m=this.#n(s,c);return e(s,p,c,{signal:i}).then(async()=>{await d(this.#e.emitAudit({requestId:o,operation:`unpack`,metadata:{controller:`stream`}}),i,e=>this.#e.trackWork(o,e)),t(i),this.#e.endRequest(o)}).catch(e=>{this.#e.emitError(e,o),m.destroy(e instanceof Error?e:Error(String(e)))}),m}async pipe(n,r,i=!1,a={}){let o=this.#e.createOperationSignal(a);if(t(o),this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw byte streams`);let s=this.#e.startRequest(),c=i?`decompress`:`compress`,l=this.#t(s,o);try{let a=j(this.#e.plugins,c,i,e=>this.#e.emitProgress(e,s),this.#e.logger,this.#e.tracer,this.#e.dlq,l);await e(n,[T(this.#e.limits.maxInputBytes,`input`),...a,T(this.#e.limits.maxOutputBytes,`output`)],r,{signal:o}),await d(this.#e.emitAudit({requestId:s,operation:i?`reverse`:`process`,metadata:{controller:`stream`}}),o,e=>this.#e.trackWork(s,e)),t(o),this.#e.endRequest(s)}catch(e){throw this.#e.emitError(e,s),e}}};const $=2147483647;var de=class e extends q{static pluginRegistry=new Map;static registerPlugin(e,t){if(!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(e)||typeof t!=`function`)throw Error(`[PipeX] Invalid plugin registration`);this.pluginRegistry.set(e,e=>new t(e))}static async fromConfig(t){if(!t||typeof t!=`object`)throw Error(`[PipeX] Configuration must be an object`);let n=new e(t.limits);if(t.logger&&n.setLogger(t.logger),t.tracer&&n.setTracer(t.tracer),t.auditLogger&&n.setAuditLogger(t.auditLogger),t.dlq&&n.setDlq(t.dlq),t.schemaRegistry&&n.setSchemaRegistry(t.schemaRegistry),t.schema&&n.setSchema(t.schema),t.plugins){if(!Array.isArray(t.plugins))throw Error(`[PipeX] Configuration plugins must be an array`);for(let e of t.plugins){let t=this.pluginRegistry.get(e.name);if(!t)throw Error(`[PipeX] Unknown plugin in config: ${e.name}`);try{n.use(t(e.options))}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`[PipeX] Failed to initialize plugin "${e.name}": ${n}`,{cause:t})}}}return n}#e=[];#t=Object.freeze([]);#n;#r;#i;#a;#o;#s;#c;#l=new Set;#u=new Map;#d=new Set;#f=new Map;file;binary;stream;constructor(e={}){super(),this.#c=Object.freeze({...N,...e}),this.#p(this.#c),this.file=new ce(this),this.binary=new le(this),this.stream=new ue(this)}#p(e){for(let[t,n]of Object.entries(e))if(!Number.isSafeInteger(n)||n<0)throw Error(`[PipeX] Invalid engine limit ${t}`);if(e.maxInputBytes<1||e.maxOutputBytes<1||e.maxFrameBytes<1||e.maxFrames<1||e.maxConcurrentOperations<1||e.maxRetryAttempts<1||e.maxKmsEncryptedKeyBytes<1||e.maxKmsKeyIdBytes<1)throw Error(`[PipeX] Engine limits must be positive`);if(e.operationTimeoutMs>$||e.maxKmsEncryptedKeyBytes>4294967295)throw Error(`[PipeX] Engine limit exceeds its supported protocol or timer range`)}get limits(){return this.#c}setLimits(e){if(this.#l.size>0)throw Error(`[PipeX] Cannot modify engine limits while operations are active`);let t={...this.#c,...e};return this.#p(t),this.#c=Object.freeze(t),this}createOperationSignal(e={}){let t=e.timeoutMs??this.#c.operationTimeoutMs;if(!Number.isSafeInteger(t)||t<0||t>$)throw Error(`[PipeX] Invalid operation timeout`);let n=e.signal?[e.signal]:[];t>0&&n.push(AbortSignal.timeout(t));let r=n.length===0?new AbortController().signal:AbortSignal.any(n);return M(r,t),r}setDlq(e){if(!e||typeof e.write!=`function`)throw Error(`[PipeX] DLQ must be a writable stream`);return this.#o=e,this}get dlq(){return this.#o}setLogger(e){if(!e||![`info`,`warn`,`error`,`debug`].every(t=>typeof e[t]==`function`))throw Error(`[PipeX] Logger must implement info, warn, error, and debug`);return this.#i=o(e),this}get logger(){return this.#i}setTracer(e){if(!e||typeof e.startSpan!=`function`)throw Error(`[PipeX] Tracer must implement startSpan`);return this.#a=s(e),this}get tracer(){return this.#a}setAuditLogger(e){if(!e||typeof e.log!=`function`)throw Error(`[PipeX] Audit logger must implement log`);return this.#s=e,this}async emitAudit(e){this.#s&&await this.#s.log({...e,pluginChain:e.operation===`pack`||e.operation===`unpack`?[]:[...this.#f.get(e.requestId)??this.pipeline],timestamp:Date.now()})}setSchemaRegistry(e){if(!e||typeof e.getSchema!=`function`)throw Error(`[PipeX] Schema registry must implement getSchema`);return this.#r=e,this}async loadSchema(e,t){if(!this.#r)throw Error(`[PipeX] No Schema Registry configured`);let n=await this.#r.getSchema(e,t);this.setSchema(n)}setSchema(e){if(!e||typeof e.safeParse!=`function`)throw Error(`[PipeX] Schema must implement safeParse`);return this.#n=e,this}get schema(){return this.#n}validate(e){if(this.#n&&!this.#n.safeParse(e).success)throw Error(`[PipeX] Core Validation failed`)}use(e){if(!e||typeof e.name!=`string`||e.name.length===0||e.name.length>128||typeof e.version!=`string`||e.version.length===0||typeof e.process!=`function`)throw Error(`[PipeX] Invalid processor plugin`);if(r(e),this.#l.size>0)throw Error(`[PipeX] Cannot modify the plugin pipeline while operations are active`);if(this.#e.length>=256)throw Error(`[PipeX] Maximum plugin count exceeded`);return this.#e.push(e),this.#t=Object.freeze([...this.#e]),this}get plugins(){return this.#t}get pipeline(){return Object.freeze(this.#t.map(e=>`${e.name}@${e.version}`))}get pluginCapabilities(){return Object.freeze(this.#t.map(e=>Object.freeze({plugin:`${e.name}@${e.version}`,...r(e)})))}startRequest(e={}){if(this.#l.size>=this.#c.maxConcurrentOperations)throw Error(`[PipeX] Maximum concurrent operations exceeded`);let t=F();this.#l.add(t),this.#f.set(t,this.pipeline);try{this.#i?.info(`[PipeX] Request started`,{requestId:t,...e})}catch{}return this.emit(`start`,t),t}trackWork(e,t){let n=this.#u.get(e);n||this.#u.set(e,n=new Set),n.add(t);let r=()=>{n.delete(t),n.size===0&&(this.#u.delete(e),this.#d.has(e)&&this.releaseRequest(e))};t.then(r,r)}releaseRequest(e){if(this.#u.get(e)?.size){this.#d.add(e);return}this.#l.delete(e),this.#d.delete(e),this.#f.delete(e)}endRequest(e,t){this.releaseRequest(e);try{this.#i?.info(`[PipeX] Request ended`,{requestId:e,durationMs:t})}catch{}this.emit(`end`,e,t)}emitProgress(e,t){this.emit(`progress`,e,t)}emitError(e,t){let n=e instanceof Error?e:Error(String(e));this.releaseRequest(t);try{this.#i?.error(`[PipeX] Request failed`,{requestId:t,error:n.message})}catch{}this.listenerCount(`error`)>0&&this.emit(`error`,n,t)}emit(e,...t){let n=this.rawListeners(e);for(let e of n)i(()=>Reflect.apply(e,this,t));return n.length>0}on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}};export{de as t};