@snyxex/pipex 1.0.2 → 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 (77) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +238 -139
  3. package/dist/compression-2mm0MhWY.mjs +1 -0
  4. package/dist/compression-CtrHxa9G.d.mts +38 -0
  5. package/dist/compression-DnVFu8TM.d.cts +38 -0
  6. package/dist/compression-DrgzribA.cjs +1 -0
  7. package/dist/compression.cjs +1 -0
  8. package/dist/compression.d.cts +2 -0
  9. package/dist/compression.d.mts +2 -0
  10. package/dist/compression.mjs +1 -0
  11. package/dist/core-BOdvxKBq.mjs +2 -0
  12. package/dist/core-B_z1gN5W.cjs +2 -0
  13. package/dist/dataEngine-4m6GTOLe.mjs +1 -0
  14. package/dist/dataEngine-Bvl6amzP.cjs +1 -0
  15. package/dist/dataEngine-D-fIXgE7.d.cts +232 -0
  16. package/dist/dataEngine-DUEmWp7a.d.mts +232 -0
  17. package/dist/encryption-BmmNECIc.d.cts +44 -0
  18. package/dist/encryption-CnSL1BEY.d.mts +44 -0
  19. package/dist/encryption-CqxtoqAD.mjs +1 -0
  20. package/dist/encryption-DdP1zFYl.cjs +1 -0
  21. package/dist/encryption.cjs +1 -0
  22. package/dist/encryption.d.cts +2 -0
  23. package/dist/encryption.d.mts +2 -0
  24. package/dist/encryption.mjs +1 -0
  25. package/dist/hashing-B6xGcbQR.d.mts +33 -0
  26. package/dist/hashing-ChrADfcH.mjs +1 -0
  27. package/dist/hashing-JtOHPybU.cjs +1 -0
  28. package/dist/hashing-LY-8x66g.d.cts +33 -0
  29. package/dist/hashing.cjs +1 -0
  30. package/dist/hashing.d.cts +2 -0
  31. package/dist/hashing.d.mts +2 -0
  32. package/dist/hashing.mjs +1 -0
  33. package/dist/index.cjs +1 -0
  34. package/dist/index.d.cts +302 -0
  35. package/dist/index.d.mts +87 -550
  36. package/dist/index.mjs +1 -3
  37. package/dist/kms.cjs +1 -0
  38. package/dist/kms.d.cts +3 -0
  39. package/dist/kms.d.mts +3 -0
  40. package/dist/kms.mjs +1 -0
  41. package/dist/kms_encryption-Da-KqjKI.d.mts +33 -0
  42. package/dist/kms_encryption-Dh1LEHhk.d.cts +33 -0
  43. package/dist/kms_encryption-R9auKGW4.mjs +1 -0
  44. package/dist/kms_encryption-xyWi65rZ.cjs +1 -0
  45. package/dist/native.cjs +1 -0
  46. package/dist/native.d.cts +2 -0
  47. package/dist/native.d.mts +2 -0
  48. package/dist/native.mjs +1 -0
  49. package/dist/parallel.cjs +1 -0
  50. package/dist/parallel.d.cts +2 -0
  51. package/dist/parallel.d.mts +2 -0
  52. package/dist/parallel.mjs +1 -0
  53. package/dist/plugin-C9Kd9coY.d.cts +16 -0
  54. package/dist/plugin-CE94-p8P.d.mts +16 -0
  55. package/dist/resourceLimits-C1HHDwXQ.mjs +1 -0
  56. package/dist/resourceLimits-CI0Qrqdf.cjs +1 -0
  57. package/dist/types-Bytga6zd.d.mts +155 -0
  58. package/dist/types-ia4x-Dvp.d.cts +155 -0
  59. package/dist/validation-CqmhNHdW.d.cts +32 -0
  60. package/dist/validation-D17IkoHy.d.mts +32 -0
  61. package/dist/validation-P5WRSAUK.mjs +1 -0
  62. package/dist/validation-pEeJmCad.cjs +1 -0
  63. package/dist/validation.cjs +1 -0
  64. package/dist/validation.d.cts +2 -0
  65. package/dist/validation.d.mts +2 -0
  66. package/dist/validation.mjs +1 -0
  67. package/dist/worker-CbuCpSNc.d.cts +37 -0
  68. package/dist/worker-CgCC-BWG.d.mts +37 -0
  69. package/dist/worker-I_kqxWeK.cjs +1 -0
  70. package/dist/worker-c0_VZ9c7.mjs +1 -0
  71. package/package.json +120 -23
  72. package/SECURITY.md +0 -41
  73. package/dist/index.d.mts.map +0 -1
  74. package/dist/index.mjs.map +0 -1
  75. package/docs/architecture.md +0 -124
  76. package/docs/encryption-v4-migration.md +0 -45
  77. package/docs/enterprise.md +0 -280
package/dist/index.mjs CHANGED
@@ -1,3 +1 @@
1
- import{createRequire as e}from"node:module";import{createCipheriv as t,createDecipheriv as n,createHmac as r,hkdfSync as i,randomBytes as a,randomUUID as o,timingSafeEqual as s}from"node:crypto";import{pipeline as c}from"node:stream/promises";import{Duplex as l,PassThrough as u,Readable as d,Transform as f,Writable as p,compose as m}from"node:stream";import{Packr as h,PackrStream as g,Unpackr as _,UnpackrStream as v}from"msgpackr";import"zod";import y from"node:path";import{closeSync as b,constants as x,existsSync as S,fstatSync as C,openSync as ee,realpathSync as w}from"node:fs";import{EventEmitter as te}from"node:events";import{brotliCompress as ne,brotliDecompress as re,constants as T,createBrotliCompress as ie,createBrotliDecompress as ae,createGunzip as oe,createGzip as se,gunzip as ce,gzip as le}from"node:zlib";import{promisify as ue}from"node:util";import{fileURLToPath as de}from"node:url";import{availableParallelism as fe}from"node:os";import{Piscina as pe}from"piscina";function me(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 E=class extends Error{name=`PipeXError`;constructor(e,t,n){super(t,n),this.code=e}},D=class extends E{name=`UnsupportedReverseError`;constructor(e){super(`UNSUPPORTED_REVERSE`,`[PipeX] Plugin ${e} does not support reverse operations`),this.plugin=e}},he=class extends E{name=`UnsupportedStreamingError`;constructor(e){super(`UNSUPPORTED_STREAMING`,`[PipeX] Plugin ${e} does not support stream operations`),this.plugin=e}},O=class extends E{name=`InvalidPluginCapabilityError`;constructor(e,t,n){super(`INVALID_PLUGIN_CAPABILITY`,`[PipeX] Plugin ${e} has an invalid ${t} capability: ${n===`MUST_BE_BOOLEAN`?`must be a boolean when declared`:n===`MISSING_IMPLEMENTATION`?`is declared but its implementation is missing`:`is disabled but its implementation is present`}`),this.plugin=e,this.capability=t,this.issue=n}},k=class extends E{name=`OperationAbortedError`;constructor(e){super(`OPERATION_ABORTED`,`[PipeX] Operation aborted`,e)}},A=class extends E{name=`OperationTimeoutError`;constructor(e){super(`OPERATION_TIMEOUT`,`[PipeX] Operation timed out`,e)}},ge=class extends E{name=`KmsProviderError`;constructor(e,t){super(`KMS_PROVIDER_FAILURE`,`[PipeX] KMS ${e} failed`,t),this.operation=e}},_e=class extends E{name=`KmsAuthenticationError`;constructor(){super(`KMS_AUTHENTICATION_FAILED`,`[PipeX] KMS envelope authentication failed`)}},ve=class extends E{name=`KmsProviderAuthenticationError`;constructor(e){super(`KMS_PROVIDER_AUTHENTICATION_FAILED`,`[PipeX] KMS ${e} authentication failed`),this.operation=e}},ye=class extends E{name=`KmsProviderUnavailableError`;constructor(e){super(`KMS_PROVIDER_UNAVAILABLE`,`[PipeX] KMS ${e} provider unavailable`),this.operation=e}},be=class extends E{name=`UnsupportedKmsOperationError`;constructor(e){super(`UNSUPPORTED_KMS_OPERATION`,`[PipeX] KMS provider does not support ${e}`),this.operation=e}},xe=class extends E{name=`InvalidKmsProviderCapabilityError`;constructor(e,t){super(`INVALID_KMS_PROVIDER_CAPABILITY`,`[PipeX] Invalid KMS ${e} capability: ${t===`MUST_BE_BOOLEAN`?`must be a boolean when declared`:`is declared but its implementation is missing`}`),this.operation=e,this.issue=t}},Se=class extends E{name=`WorkerPoolClosedError`;constructor(){super(`WORKER_POOL_CLOSED`,`[PipeX] Worker pool is closed`)}},Ce=class extends E{name=`WorkerQueueFullError`;constructor(e){super(`WORKER_QUEUE_FULL`,`[PipeX] Worker queue is full (maximum ${e} waiting tasks)`),this.maxQueue=e}},we=class extends E{name=`WorkerPoolCloseError`;constructor(e){super(`WORKER_POOL_CLOSE_FAILURE`,`[PipeX] Worker pool failed to close cleanly`,e)}},Te=class extends E{name=`WorkerTaskError`;constructor(e,t){super(`WORKER_TASK_FAILURE`,`[PipeX] Worker task ${e} failed`,t),this.taskName=e}},j=class e{retryOptions;get reversible(){return this.reverse!==e.prototype.reverse}constructor(e={}){this.options=e}reverse(e,t){throw new D(`${this.name}@${this.version}`)}};const M=Object.freeze({maxInputBytes:64*1024*1024,maxOutputBytes:256*1024*1024,maxFrameBytes:8*1024*1024,maxFrames:1e5,maxConcurrentOperations:32,operationTimeoutMs:5*6e4,maxRetryAttempts:5,maxRetryDelayMs:3e4,maxKmsEncryptedKeyBytes:64*1024,maxKmsKeyIdBytes:512});function N(e){let t=e?.limits??M;return Math.max(t.maxInputBytes,t.maxOutputBytes)}function P(e){return e?.limits?.maxOutputBytes??M.maxOutputBytes}var Ee=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 F(e,t,n=2**53-1){let r=new Ee(t,n),i=r.scan(Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength));return r.finish(),i.length}function I(e,t){let n=new Ee(e,t),r=[],i=0;return new f({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 De=new WeakMap;function Oe(e,t){t>0&&De.set(e,Date.now()+t)}function ke(e){return e.reason instanceof A||e.reason instanceof k?e.reason:e.reason instanceof Error&&e.reason.name===`TimeoutError`?new A:new k}function L(e){if(!e)return;if(e.aborted)throw ke(e);let t=De.get(e);if(t!==void 0&&Date.now()>=t)throw new A}async function R(e,t,n){let r=Promise.resolve(e);return n?.(r),t?new Promise((e,n)=>{let i=!1,a,o=()=>{t.removeEventListener(`abort`,c),a&&clearTimeout(a)},s=e=>{i||(i=!0,o(),n(e))},c=()=>s(ke(t));t.addEventListener(`abort`,c,{once:!0});let l=De.get(t);l!==void 0&&(a=setTimeout(()=>s(new A),Math.max(0,l-Date.now()))),r.then(n=>{if(!i){try{L(t)}catch(e){s(e);return}i=!0,o(),e(n)}},s);try{L(t)}catch(e){s(e)}}):r}function z(e){try{Promise.resolve(e()).catch(()=>void 0)}catch{}}function Ae(e){if(e)return{info:(t,n)=>z(()=>e.info(t,n)),warn:(t,n)=>z(()=>e.warn(t,n)),error:(t,n)=>z(()=>e.error(t,n)),debug:(t,n)=>z(()=>e.debug(t,n))}}function je(e){if(e)return{startSpan(t,n){let r;try{let i=e.startSpan(t,n);i&&typeof i.then==`function`?z(()=>i):r=i}catch{}let i=!1,a={setAttribute(e,t){return z(()=>r?.setAttribute(e,t)),a},addEvent(e,t){return z(()=>r?.addEvent(e,t)),a},end(){i||(i=!0,z(()=>r?.end()))}};return a}}}async function Me(e,t,n,r){n=Ae(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++){L(r?.signal);try{return await R(e(),r?.signal,r?.track)}catch(e){if(L(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 Ne=`__pipex_v`,B=new h({useRecords:!1,moreTypes:!0,structuredClone:!1,bundleStrings:!1}),V=new _({useRecords:!1,structuredClone:!1}),Pe=256*1024*1024,H=64*1024;function Fe(e){return typeof e.createStream==`function`}function Ie(e){let t=`${e.name}@${e.version}`,n=e.reversible,r=e.streaming,i=e.reverse,a=e.createStream,o=typeof i==`function`&&i!==j.prototype.reverse;if(n!==void 0&&typeof n!=`boolean`)throw new O(t,`reversible`,`MUST_BE_BOOLEAN`);if(r!==void 0&&typeof r!=`boolean`)throw new O(t,`streaming`,`MUST_BE_BOOLEAN`);if(n===!0&&!o)throw new O(t,`reversible`,`MISSING_IMPLEMENTATION`);if(r===!1&&typeof a==`function`)throw new O(t,`streaming`,`CONFLICTING_IMPLEMENTATION`);let s=n!==!1&&o,c=r!==!1;return Object.freeze({process:!0,reverse:s,streaming:c,streamMode:c?typeof a==`function`?`native`:`fallback`:`none`})}function Le(e,t){let n=Ie(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 Re(e){return Le(e,`reverse`)}function ze(e){let t=e.find(e=>!Re(e));if(t)throw new D(`${t.name}@${t.version}`)}function Be(e){let t=e.find(e=>!Le(e,`stream`));if(t)throw new he(`${t.name}@${t.version}`)}function Ve(e){return e===null?`null`:Buffer.isBuffer(e)?`buffer`:Array.isArray(e)?`array`:typeof e==`object`?`object`:typeof e}function He(e){return Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):typeof e==`object`&&e?B.pack(e):typeof e==`number`||typeof e==`boolean`?Buffer.from(String(e)):Buffer.from(String(e??``),`utf-8`)}const Ue=Object.freeze([`buffer`,`object`,`array`,`string`,`number`,`boolean`,`null`,`undefined`,`bigint`,`json`]);function U(e){if(typeof e!=`string`||!Ue.includes(e))throw Error(`[PipeX] Unsupported original type`)}function We(e,t,n=M.maxFrameBytes){if(U(t),!Buffer.isBuffer(e))throw Error(`[PipeX] Invalid binary payload`);switch(t){case`array`:case`object`:{F(e,n,1);let r;try{r=V.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 Ge(e,t={},n,r,i,a){return{requestId:e,timestamp:Date.now(),metadata:t,logger:n,span:r,signal:i,limits:a}}function Ke(e){return{__pipex_v:1,plugins:e.map(e=>`${e.name}@${e.version}`),ts:Date.now()}}function qe(e){let t=!1,n=Buffer.from(B.pack(e));return new f({transform(e,r,i){t||(t=!0,this.push(n)),i(null,e)},flush(e){t||this.push(n),e()}})}function Je(e){let t=!1;return new f({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){if(!t&&(t=!0,me(n))){try{e(n),i()}catch(e){i(e)}return}i(null,n)}})}var Ye=class extends v{#e=0;#t;constructor(e={},t=M.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 Xe(){return new g({useRecords:!1,moreTypes:!0,structuredClone:!1,bundleStrings:!1})}function Ze(e=M.maxInputBytes){return new Ye({useRecords:!1,structuredClone:!1},e)}function W(e,t){let n=0;return new f({transform(r,i,a){if(r.length>e-n){a(Error(`[PipeX] ${t} exceeds ${e} bytes`));return}n+=r.length,a(null,r)}})}function G(e){let t=0;return new f({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 K(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 Qe(e,t){return new f({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){try{K(n,e,t),i(null,n)}catch(e){i(e)}}})}function $e(e,t,n,r,i,a,s){r=Ae(r),i=je(i);let c=s?.requestId??`stream-${o()}`;return new f({async transform(o,l,u){let d=i?.startSpan(`plugin:${e.name}`,{requestId:c});d?.setAttribute(`plugin.version`,e.version),d?.setAttribute(`mode`,t?`reverse`:`process`);try{s?.signal.throwIfAborted();let i=Ge(c,{},r,d,s?.signal,s?.limits);if(t&&!Re(e))throw new D(`${e.name}@${e.version}`);let a=t?e.reverse.bind(e):e.process.bind(e),l=await Me(()=>a(o,i),e.retryOptions,r,{signal:s?.signal,limits:s?.limits,track:s?.track}),f=s?.limits.maxOutputBytes??M.maxOutputBytes;if(!Buffer.isBuffer(l)||l.length>f)throw Error(`[PipeX] Plugin output exceeds ${f} bytes`);n?.(l.length),d?.addEvent(`processed`,{bytes:l.length}),u(null,l)}catch(t){let n=t instanceof Error?t:Error(String(t));if(r?.error(`[PipeX] Plugin ${e.name} failed after retries`,{requestId:c,error:n.message}),d?.setAttribute(`error`,!0),d?.addEvent(`error`,{message:n.message}),a&&a.writable){r?.warn(`[PipeX] Diverting failed chunk to DLQ`,{requestId:c,plugin:e.name});try{a.write(o)||await new Promise((e,t)=>{let n=()=>{c(),e()},r=e=>{c(),t(e)},i=()=>{c(),t(s?.signal.reason instanceof Error?s.signal.reason:Error(`[PipeX] Operation aborted`))},o=()=>{c(),t(Error(`[PipeX] Stream closed while writing to DLQ`))},c=()=>{a.off(`drain`,n),a.off(`error`,r),s?.signal.removeEventListener(`abort`,i),this.off(`close`,o)};a.once(`drain`,n),a.once(`error`,r),this.once(`close`,o),s?.signal.aborted?i():s?.signal.addEventListener(`abort`,i,{once:!0})}),u(n)}catch(e){u(e)}}else u(n)}finally{d?.end()}}})}function et(){return new f({writableObjectMode:!0,readableObjectMode:!1,transform(e,t,n){try{n(null,JSON.stringify(e)+`
2
- `)}catch(e){n(Error(`[PipeX] NDJSON: ${e.message}`))}}})}function q(e,t,n=!1,r,i,a,o,s){return i=Ae(i),a=je(a),Be(e),n&&ze(e),(n?[...e].reverse():e).flatMap((e,c)=>{let l=Fe(e)?e.createStream(t,s):$e(e,n,r,i,a,o,s),u=W(s?.limits.maxOutputBytes??M.maxOutputBytes,`output after plugin ${e.name}#${c}`);if(!Fe(e))return[l,u];let d=a?.startSpan(`plugin:${e.name}`,{requestId:s?.requestId??`stream`}),p=!1,m=e=>{p||(p=!0,e&&d?.setAttribute(`error`,!0),d?.end())};return[l,new f({transform(e,t,n){r?.(e.length),d?.addEvent(`processed`,{bytes:e.length}),n(null,e)},final(e){m(),e()},destroy(e,t){m(e),t(e)}}),u]})}async function J(e,t,n,r){await c(e,...t,n,r??{})}function tt(e,t){let n=y.relative(t,e);if(n===`..`||n.startsWith(`..${y.sep}`)||y.isAbsolute(n))throw Error(`[PipeX] Path is outside the allowed root`)}function nt(e,t){let n=y.resolve(e);if(!S(n))throw Error(`[PipeX] File not found: ${n}`);let r=w.native(y.resolve(t??process.cwd())),i=w.native(n);return tt(i,r),i}function rt(e,t){let n=w.native(y.resolve(t??process.cwd())),r=y.resolve(e),i=w.native(y.dirname(r));tt(i,n);let a=y.join(i,y.basename(r));return S(a)&&tt(w.native(a),n),a}let it;const at=()=>it??=e(import.meta.url)(`koffi`),Y=e=>{throw Error(`[PipeX] Secure file `+e+` failed`)},ot=e=>{let t=y.parse(e).root;return e.slice(t.length).split(y.sep).filter(Boolean)};function st(e,t,n){let r=w.native(y.resolve(n??process.cwd())),i=nt(e,r),a=rt(t,r);if(i===a)throw Error(`[PipeX] Input and output must be different files`);return process.platform===`win32`?ut(i,a,r):pt(i,a)}let ct;function lt(){let e=at(),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 ut(e,t,n){let r=ct??=lt(),i=[],a=new Map,s=new Set,c=!1,l=!1,u,f,m=e=>{let t=Buffer.alloc(52);return r.info(e,t)||Y(`handle inspection`),t},h=(e,t,n,a,o)=>{let s=r.open(e,t,n,null,a,2097152|(o?33554432:128),null);BigInt(s)===-1n&&Y(`open`),i.push(s);let c=m(s).readUInt32LE(0);return(c&1024||!!(c&16)!==o||r.type(s)!==1)&&Y(`file type validation`),s},g=(e,t,n,a,o,s=!1)=>{(!t||t===`.`||t===`..`||/[\\/:]/.test(t))&&Y(`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;Y(`relative open`)}let u=c[0];i.push(u),a&&(f=u);let d=m(u).readUInt32LE(0);return(d&1024||!!(d&16)!==o||r.type(u)!==1)&&Y(`relative type validation`),u},_=(e,t)=>{let r=``,i=t;for(let t of ot(y.relative(n,y.dirname(e)))){r=y.join(r,t);let e=a.get(r.toLowerCase());e===void 0?(i=g(i,t,2147483648,!1,!0),a.set(r.toLowerCase(),i)):i=e}return i},v,b=()=>{for(let e of i.reverse())r.close(e);i.length=0};try{let a=h(n,2147483648,3,3,!0),s=Buffer.alloc(65536),c=r.finalPath(a,s,s.length/2,0);(!c||c>=s.length/2)&&Y(`root identity validation`),y.normalize((e=>e.startsWith(`\\\\?\\UNC\\`)?`\\\\`+e.slice(8):e.startsWith(`\\\\?\\`)?e.slice(4):e)(s.subarray(0,c*2).toString(`utf16le`))).toLowerCase()!==y.normalize(n).toLowerCase()&&Y(`root identity validation`);let l=_(e,a);v=_(t,a),u=g(l,y.basename(e),2147483648,!1,!1);let d=g(v,y.basename(t),2147483648,!1,!1,!0);if(d!==void 0)try{let e=m(u),t=m(d);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&&Y(`output reparse validation`)}finally{r.close(d),i.pop()}let p=`.pipex-`+o()+`.tmp`;f=g(v,p,1073807488,!0,!1)}catch(e){throw f!==void 0&&r.setInfo(f,4,Buffer.from([1]),1),b(),e}let x=(e,t)=>{let n=[0],i=new Promise((i,a)=>{(e?r.write:r.read).async(e?f:u,t,t.length,n,null,(t,r)=>{t||!r?a(Error(`[PipeX] Secure file `+(e?`write`:`read`)+` failed`)):i(n[0])})});return s.add(i),i.then(()=>s.delete(i),()=>s.delete(i)),i},S=!1,C=new d({highWaterMark:H,read(){if(S)return;S=!0;let e=Buffer.allocUnsafe(H);x(!1,e).then(t=>{S=!1,this.destroyed||this.push(t?e.subarray(0,t):null)},e=>{S=!1,this.destroy(e)})}}),ee=new p({highWaterMark:H,write(e,t,n){let r=(async()=>{let t=0;for(;t<e.length;){l&&Y(`write after disposal`);let n=await x(!0,e.subarray(t));n||Y(`write progress`),t+=n}})();s.add(r),r.then(()=>{s.delete(r),n()},e=>{s.delete(r),n(e)})}});return{source:C,destination:ee,commit(){(l||c)&&Y(`commit state`);let e=r.pointerBytes,n=e===8?8:4,i=n+e,a=i+4,o=Buffer.from(y.basename(t)+`\0`,`utf16le`),s=Buffer.alloc(a+o.length);s[0]=1,e===8?s.writeBigUInt64LE(BigInt(v),n):s.writeUInt32LE(Number(v),n),s.writeUInt32LE(o.length-2,i),o.copy(s,a);let u=r.setRelativeInfo(f,{},s,s.length,10);u<0&&Y(`atomic rename status `+(u>>>0).toString(16)),c=!0},async dispose(){l||(l=!0,C.destroy(),ee.destroy(),await Promise.allSettled([...s]),c||r.setInfo(f,4,Buffer.from([1]),1),b())}}}let dt;function ft(){let e=at().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 pt(e,t){let n=dt??=ft(),r=[],i=x.O_NOFOLLOW,a=x.O_DIRECTORY;(!i||!a)&&Y(`platform support`);let s=()=>{for(let e of r.reverse())try{b(e)}catch{}r.length=0},c=(e,t,a,o=0)=>{let s=n.openat(e,t,a|i,o);return s<0&&Y(`relative open`),r.push(s),n.fcntl(s,2,1)<0&&Y(`descriptor inheritance protection`),s},l=e=>{let t=ee(y.parse(e).root,x.O_RDONLY|a);r.push(t);for(let n of ot(y.dirname(e)))t=c(t,n,x.O_RDONLY|a);return t},u=`.pipex-`+o(),f,m,h,g,_=!1,v=!1,S=!1,w=new Set,te=process.platform===`linux`?512:process.platform===`darwin`?128:process.platform===`openbsd`?8:2048,ne=()=>{m!==void 0&&!_&&n.unlinkat(m,`data`,0),f!==void 0&&S&&n.unlinkat(f,u,te),s()};try{let r=l(e);f=l(t),h=c(r,y.basename(e),x.O_RDONLY|x.O_NONBLOCK);let o=C(h,{bigint:!0});o.isFile()||Y(`input type validation`);let s=n.openat(f,y.basename(t),x.O_RDONLY|i|x.O_NONBLOCK,0);if(s>=0)try{let e=C(s,{bigint:!0});if(o.dev===e.dev&&o.ino===e.ino)throw Error(`[PipeX] Input and output must be different files`)}finally{b(s)}n.mkdirat(f,u,448)!==0&&Y(`temporary directory creation`),S=!0,m=c(f,u,x.O_RDONLY|a);let d=C(m);(d.mode&63||d.uid!==process.geteuid?.())&&Y(`temporary directory permissions`),g=c(m,`data`,x.O_WRONLY|x.O_CREAT|x.O_EXCL,384)}catch(e){throw ne(),e}let re=(e,t)=>{let r=new Promise((r,i)=>{(e?n.write:n.read).async(e?g:h,t,t.length,(e,t)=>{e||t<0?i(Error(`[PipeX] Secure relative file I/O failed`)):r(Number(t))})});return w.add(r),r.then(()=>w.delete(r),()=>w.delete(r)),r},T=!1,ie=new d({highWaterMark:H,read(){if(T)return;T=!0;let e=Buffer.allocUnsafe(H);re(!1,e).then(t=>{T=!1,this.destroyed||this.push(t?e.subarray(0,t):null)},e=>{T=!1,this.destroy(e)})}}),ae=new p({highWaterMark:H,write(e,t,n){let r=(async()=>{let t=0;for(;t<e.length;){v&&Y(`write after disposal`);let n=await re(!0,e.subarray(t));n||Y(`relative write progress`),t+=n}})();w.add(r),r.then(()=>{w.delete(r),n()},e=>{w.delete(r),n(e)})}});return{source:ie,destination:ae,commit(){(v||_)&&Y(`commit state`),n.renameat(m,`data`,f,y.basename(t))!==0&&Y(`atomic relative rename`),_=!0},async dispose(){v||(v=!0,ie.destroy(),ae.destroy(),await Promise.allSettled([...w]),ne())}}}var mt=class{#e;constructor(e){this.#e=e}async#t(e,t,n,r,i){let a=st(e,t,n);try{await i(a.source,a.destination),L(r),a.commit()}finally{await a.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(e,t,n,r={}){let i=this.#e.createOperationSignal(r);L(i);let a=this.#e.startRequest();try{if(this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw file streams`);await this.#t(e,t,n,i,async(e,t)=>{let n=this.#n(a,i);await J(e,[W(this.#e.limits.maxInputBytes,`input`),...q(this.#e.plugins,`compress`,!1,e=>this.#e.emitProgress(e,a),this.#e.logger,this.#e.tracer,this.#e.dlq,n),W(this.#e.limits.maxOutputBytes,`output`)],t,{signal:i})}),await R(this.#e.emitAudit({requestId:a,operation:`process`,metadata:{controller:`file`}}),i,e=>this.#e.trackWork(a,e)),L(i),this.#e.endRequest(a)}catch(e){throw this.#e.emitError(e,a),e}}async reverse(e,t,n,r={}){let i=this.#e.createOperationSignal(r);L(i);let a=this.#e.startRequest();try{if(this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw file streams`);await this.#t(e,t,n,i,async(e,t)=>{let n=this.#n(a,i);await J(e,[W(this.#e.limits.maxInputBytes,`input`),...q(this.#e.plugins,`decompress`,!0,e=>this.#e.emitProgress(e,a),this.#e.logger,this.#e.tracer,this.#e.dlq,n),W(this.#e.limits.maxOutputBytes,`output`)],t,{signal:i})}),await R(this.#e.emitAudit({requestId:a,operation:`reverse`,metadata:{controller:`file`}}),i,e=>this.#e.trackWork(a,e)),L(i),this.#e.endRequest(a)}catch(e){throw this.#e.emitError(e,a),e}}async pack(e,t,n,r={}){let i=this.#e.createOperationSignal(r);L(i);let a=this.#e.startRequest();try{await this.#t(e,t,n,i,async(e,t)=>{await J(e,[W(this.#e.limits.maxInputBytes,`input`),G(this.#e.limits.maxFrames),Qe(this.#e.limits.maxFrameBytes,`MessagePack frame`),Xe(),qe(Ke([])),I(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),W(this.#e.limits.maxOutputBytes,`output`)],t,{signal:i})}),await R(this.#e.emitAudit({requestId:a,operation:`pack`,metadata:{controller:`file`}}),i,e=>this.#e.trackWork(a,e)),L(i),this.#e.endRequest(a)}catch(e){throw this.#e.emitError(e,a),e}}async unpack(e,t,n,r={}){let i=this.#e.createOperationSignal(r);L(i);let a=this.#e.startRequest();try{await this.#t(e,t,n,i,async(e,t)=>{let n=Ze(this.#e.limits.maxInputBytes),r=Je(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,a)}),o=et(),s=new f({writableObjectMode:!0,readableObjectMode:!0,transform:(e,t,n)=>{try{this.#e.validate(e),n(null,e)}catch(e){n(e)}}});await J(e,[W(this.#e.limits.maxInputBytes,`input`),I(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),n,r,G(this.#e.limits.maxFrames),s,o,W(this.#e.limits.maxOutputBytes,`output`)],t,{signal:i})}),await R(this.#e.emitAudit({requestId:a,operation:`unpack`,metadata:{controller:`file`}}),i,e=>this.#e.trackWork(a,e)),L(i),this.#e.endRequest(a)}catch(e){throw this.#e.emitError(e,a),e}}},ht=class{#e;constructor(e){this.#e=e}pack(e){try{K(e,Math.min(this.#e.limits.maxInputBytes,this.#e.limits.maxFrameBytes),`Serialization input`);let t=B.pack(e);if(t.length>this.#e.limits.maxInputBytes)throw Error(`[PipeX] Packed input exceeds configured limit`);if(F(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:Error(`[PipeX] binary.pack failed`)}}unpack(e){try{if(e.byteLength>this.#e.limits.maxInputBytes)throw Error(`[PipeX] Serialized input exceeds configured limit`);return F(e,this.#e.limits.maxFrameBytes,1),V.unpack(e)}catch(e){throw e instanceof Error&&e.message.startsWith(`[PipeX]`)?e:Error(`[PipeX] binary.unpack failed: invalid MessagePack input`)}}#t=new WeakMap;async run(e,t={}){let n=this.#e.createOperationSignal(t);L(n);let r=Ve(e);U(r);let i=this.#e.plugins,a=[...this.#e.pipeline],o=this.#e.limits,s=this.#e.startRequest({operation:`run`}),c=Date.now(),l=this.#e.tracer?.startSpan(`binary:run`,{requestId:s});try{l?.setAttribute(`input.type`,r),this.#e.validate(e),K(e,o.maxInputBytes,`Input`);let t=He(e);if(t.length>o.maxInputBytes)throw Error(`[PipeX] Input exceeds configured limit`);(r===`object`||r===`array`)&&F(t,o.maxFrameBytes,1);let u=Object.create(null);for(let e of i){let i=Date.now(),a=this.#e.tracer?.startSpan(`plugin:${e.name}`,{requestId:s});try{a?.setAttribute(`mode`,`process`);let i=Ge(s,{originalType:r},this.#e.logger,a,n,o);if(t=await Me(()=>e.process(t,i),e.retryOptions,this.#e.logger,{signal:n,limits:o,track:e=>this.#e.trackWork(s,e)}),!Buffer.isBuffer(t)||t.length>o.maxOutputBytes)throw Error(`[PipeX] Plugin output exceeds configured limit`)}catch(e){throw a?.setAttribute(`error`,!0),e}finally{a?.end()}u[e.name]=Date.now()-i,this.#e.emit(`plugin:after`,e.name,u[e.name])}if(t.length>o.maxOutputBytes)throw Error(`[PipeX] Output exceeds configured limit`);L(n);let d=Date.now()-c;await R(this.#e.emitAudit({requestId:s,operation:`process`,metadata:{inputType:r,durationMs:d}}),n,e=>this.#e.trackWork(s,e)),L(n),this.#t.set(t,r);let f={data:t,originalType:r,pipeline:a,metrics:{durationMs:d,steps:u}};return l?.setAttribute(`duration_ms`,d),this.#e.endRequest(s,d),f}catch(e){throw l?.setAttribute(`error`,!0),this.#e.emitError(e,s),e}finally{l?.end(),this.#e.releaseRequest(s)}}async undo(e,t,n={}){let r=Buffer.isBuffer(e),i,a,o;if(r)U(t),i=e,a=t,o=n;else{let n=e;if(!n||typeof n!=`object`||!Buffer.isBuffer(n.data)||!Array.isArray(n.pipeline)||n.pipeline.length>256||!n.pipeline.every(e=>typeof e==`string`&&e.length<=512)||!n.metrics||!Number.isFinite(n.metrics.durationMs)||n.metrics.durationMs<0||!n.metrics.steps||typeof n.metrics.steps!=`object`||Array.isArray(n.metrics.steps)||!Object.values(n.metrics.steps).every(e=>typeof e==`number`&&Number.isFinite(e)&&e>=0))throw Error(`[PipeX] Invalid EngineResult`);if(U(n.originalType),t!==void 0&&(typeof t!=`object`||!t))throw Error(`[PipeX] Invalid undo options`);let r=t,s=r?.expectedType??this.#t.get(n.data);if(s===void 0)throw Error(`[PipeX] Transported EngineResult requires a trusted expectedType`);if(U(s),s!==n.originalType)throw Error(`[PipeX] Result type does not match the expected type`);i=n.data,a=s,o=r??{}}let s=this.#e.createOperationSignal(o);L(s);let c=this.#e.plugins;ze(c);let l=this.#e.limits;if(i.length>l.maxInputBytes)throw Error(`[PipeX] Undo input exceeds configured limit`);let u=this.#e.startRequest({operation:`undo`,originalType:a}),d=this.#e.tracer?.startSpan(`binary:undo`,{requestId:u});try{if(r&&c.length===0&&i.length>0){let e;try{e=this.unpackWithManifest(i)}catch{}if(e){if(e.manifest.plugins.length!==0)throw Error(`[PipeX] Manifest plugin chain does not match the configured engine`);if(Ve(e.data)!==a)throw Error(`[PipeX] Manifest data does not match the expected type`);i=He(e.data)}}for(let e of[...c].reverse()){let t=this.#e.tracer?.startSpan(`plugin:${e.name}`,{requestId:u});try{t?.setAttribute(`mode`,`reverse`);let n=Ge(u,{originalType:a},this.#e.logger,t,s,l);if(i=await Me(()=>e.reverse(i,n),e.retryOptions,this.#e.logger,{signal:s,limits:l,track:e=>this.#e.trackWork(u,e)}),!Buffer.isBuffer(i)||i.length>l.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(i.length>l.maxOutputBytes)throw Error(`[PipeX] Output exceeds configured limit`);L(s);let e=We(i,a,l.maxFrameBytes);return this.#e.validate(e),L(s),await R(this.#e.emitAudit({requestId:u,operation:`reverse`,metadata:{originalType:a}}),s,e=>this.#e.trackWork(u,e)),L(s),this.#e.endRequest(u),e}catch(e){throw d?.setAttribute(`error`,!0),this.#e.emitError(e,u),e}finally{d?.end(),this.#e.releaseRequest(u)}}packWithManifest(e){if(this.#e.plugins.length>0)throw Error(`[PipeX] packWithManifest is serialization-only; use binary.run for plugin transforms`);let t=Ke([]);K(e,Math.min(this.#e.limits.maxInputBytes,this.#e.limits.maxFrameBytes),`Serialization input`);let n=B.pack(t),r=B.pack(e);if(F(n,this.#e.limits.maxFrameBytes,1),F(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`);F(e,this.#e.limits.maxFrameBytes,2);let t=[];try{V.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(!me(t[0]))throw Error(`[PipeX] binary.unpackWithManifest: first frame is not a PipeXManifest`);return{manifest:t[0],data:t[1]}}},gt=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 l.from({writable:e,readable:t})}#r(e,t,n){let r=this.#e.createOperationSignal(n);if(L(r),this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw byte streams`);let i=this.#e.startRequest(),a=this.#t(i,r),o=t?`decompress`:`compress`,s;try{s=q(this.#e.plugins,o,t,e=>this.#e.emitProgress(e,i),this.#e.logger,this.#e.tracer,this.#e.dlq,a)}catch(e){throw this.#e.emitError(e,i),e}let c=new u,l,d=new p({write(e,t,n){c.write(e,t,n)},final(e){l=e,c.end()},destroy(e,t){l=void 0,c.destroyed||c.destroy(e??void 0),t(e)}}),f=e=>{let t=l;l=void 0,t?t(e):e&&!d.destroyed&&d.destroy(e)};return J(c,[W(this.#e.limits.maxInputBytes,`input`),...s,W(this.#e.limits.maxOutputBytes,`output`)],e,{signal:r}).then(async()=>{await R(this.#e.emitAudit({requestId:i,operation:t?`reverse`:`process`,metadata:{controller:`stream`}}),r,e=>this.#e.trackWork(i,e)),L(r),this.#e.endRequest(i),f()}).catch(e=>{let t=e instanceof Error?e:Error(String(e));this.#e.emitError(t,i),f(t)}),d}into(e,t={}){return this.#r(e,!1,t)}reverseInto(e,t={}){return this.#r(e,!0,t)}pack(e={}){let t=this.#e.createOperationSignal(e);L(t);let n=this.#e.startRequest({operation:`pack`}),r=new u({objectMode:!0}),i=new u,a=[G(this.#e.limits.maxFrames),Qe(this.#e.limits.maxFrameBytes,`MessagePack frame`),Xe(),qe(Ke([])),I(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),W(this.#e.limits.maxOutputBytes,`output`)],o=this.#n(r,i);return J(r,a,i,{signal:t}).then(async()=>{await R(this.#e.emitAudit({requestId:n,operation:`pack`,metadata:{controller:`stream`}}),t,e=>this.#e.trackWork(n,e)),L(t),this.#e.endRequest(n)}).catch(e=>{this.#e.emitError(e,n),o.destroy(e instanceof Error?e:Error(String(e)))}),o}unpack(e={}){let t=this.#e.createOperationSignal(e);L(t);let n=this.#e.startRequest({operation:`unpack`}),r=new u,i=new u({objectMode:!0}),a=Ze(this.#e.limits.maxInputBytes),o=Je(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,n)}),s=new f({writableObjectMode:!0,readableObjectMode:!0,transform:(e,t,n)=>{try{this.#e.validate(e),n(null,e)}catch(e){n(e)}}}),c=[W(this.#e.limits.maxInputBytes,`input`),I(this.#e.limits.maxFrameBytes,Math.min(2**53-1,this.#e.limits.maxFrames+1)),a,o,G(this.#e.limits.maxFrames),s],l=this.#n(r,i);return J(r,c,i,{signal:t}).then(async()=>{await R(this.#e.emitAudit({requestId:n,operation:`unpack`,metadata:{controller:`stream`}}),t,e=>this.#e.trackWork(n,e)),L(t),this.#e.endRequest(n)}).catch(e=>{this.#e.emitError(e,n),l.destroy(e instanceof Error?e:Error(String(e)))}),l}async pipe(e,t,n=!1,r={}){let i=this.#e.createOperationSignal(r);if(L(i),this.#e.schema)throw Error(`[PipeX] Global object schemas cannot validate raw byte streams`);let a=this.#e.startRequest(),o=n?`decompress`:`compress`,s=this.#t(a,i);try{let r=q(this.#e.plugins,o,n,e=>this.#e.emitProgress(e,a),this.#e.logger,this.#e.tracer,this.#e.dlq,s);await J(e,[W(this.#e.limits.maxInputBytes,`input`),...r,W(this.#e.limits.maxOutputBytes,`output`)],t,{signal:i}),await R(this.#e.emitAudit({requestId:a,operation:n?`reverse`:`process`,metadata:{controller:`stream`}}),i,e=>this.#e.trackWork(a,e)),L(i),this.#e.endRequest(a)}catch(e){throw this.#e.emitError(e,a),e}}};const _t=2147483647;var X=class e extends te{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({...M,...e}),this.#p(this.#c),this.file=new mt(this),this.binary=new ht(this),this.stream=new gt(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>_t||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>_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 Oe(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=Ae(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=je(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(Ie(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}`,...Ie(e)})))}startRequest(e={}){if(this.#l.size>=this.#c.maxConcurrentOperations)throw Error(`[PipeX] Maximum concurrent operations exceeded`);let t=o();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)z(()=>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)}};const vt=[`encrypt`,`decrypt`,`generateDataKey`];function yt(e){if(!e||typeof e!=`object`)throw TypeError(`[PipeX] Invalid KMS provider`);if(e.capabilities!==void 0&&(!e.capabilities||typeof e.capabilities!=`object`))throw TypeError(`[PipeX] Invalid KMS provider capabilities`);let t={};for(let n of vt){let r=e.capabilities?.[n],i=typeof e[n]==`function`;if(r!==void 0&&typeof r!=`boolean`)throw new xe(n,`MUST_BE_BOOLEAN`);if(r===!0&&!i)throw new xe(n,`MISSING_IMPLEMENTATION`);t[n]=r??i}return Object.freeze(t)}function bt(e,t){if(!vt.includes(t))throw TypeError(`[PipeX] Unknown KMS operation`);return yt(e)[t]}function xt(e,t){if(!bt(e,t))throw new be(t)}const St={sha256:32,sha512:64};var Ct=class extends j{name=`hashing`;version=`3.0.0`;constructor(e){if(super(e),this.options=e,!(e.algorithm in St))throw Error(`[PipeX] Hashing: unknown algorithm`);if(!e.secret||e.secret.length<16)throw Error(`[PipeX] Hashing: Secret must be at least 16 characters`)}async process(e,t){let n=N(t),i=P(t),a=St[this.options.algorithm];if(e.length>n)throw Error(`[PipeX] Hashing input exceeds ${n} bytes`);if(e.length>i-a)throw Error(`[PipeX] Hashing output exceeds ${i} bytes`);t.metadata??={};let o=r(this.options.algorithm,this.options.secret).update(e).digest();return t.metadata.hmac=o.toString(`hex`),Buffer.concat([e,o])}async reverse(e,t){let n=St[this.options.algorithm],i=N(t),a=P(t);if(e.length>i)throw Error(`[PipeX] Hashing input exceeds ${i} bytes`);if(e.length<n)throw Error(`[PipeX] Hashing reverse: data too short`);if(e.length-n>a)throw Error(`[PipeX] Hashing output exceeds ${a} bytes`);let o=e.subarray(0,e.length-n),c=e.subarray(e.length-n),l=r(this.options.algorithm,this.options.secret).update(o).digest();try{if(!s(c,l))throw Error(`[PipeX] Hashing: HMAC verification failed`);return t.metadata??={},t.metadata.verified_hmac=c.toString(`hex`),o}finally{l.fill(0)}}createStream(e,t){let{algorithm:n,secret:i}=this.options,a=r(n,i),o=St[n],c=N(t),l=P(t);if(e===`compress`){let e=0;return new f({construct(e){e(l<o?Error(`[PipeX] Hashing output exceeds ${l} bytes`):void 0)},transform(t,n,r){if(t.length>c-e)return r(Error(`[PipeX] Hashing input exceeds ${c} bytes`));if(t.length>l-o-e)return r(Error(`[PipeX] Hashing output exceeds ${l} bytes`));e+=t.length,a.update(t),this.push(t),r()},flush(e){this.push(a.digest()),e()}})}else{let e=[],t=0;return new f({transform(n,r,i){if(n.length>c-t)return i(Error(`[PipeX] Hashing input exceeds ${c} bytes`));t+=n.length,e.push(n),i()},flush(n){let r=Buffer.concat(e,t);e=[];let i;try{if(r.length<o)throw Error(`[PipeX] Hashing stream: No HMAC found`);let e=r.subarray(0,r.length-o);if(e.length>l)throw Error(`[PipeX] Hashing output exceeds ${l} bytes`);let t=r.subarray(r.length-o);if(a.update(e),i=a.digest(),!s(t,i))throw Error(`[PipeX] Hashing stream: HMAC verification failed`);let c=Buffer.from(e);r.fill(0),this.push(c),n()}catch(e){r.fill(0),n(e)}finally{i?.fill(0)}},destroy(t,n){e=[],n(t)}})}}};const Z=Buffer.from(`PXAE`),wt={"aes-256-gcm":1,"chacha20-poly1305":2},Tt={1:`aes-256-gcm`,2:`chacha20-poly1305`};function Et(e){return{maxInputBytes:N(e),maxOutputBytes:P(e),maxFrameBytes:e?.limits?.maxFrameBytes??M.maxFrameBytes,maxFrames:e?.limits?.maxFrames??M.maxFrames}}function Dt(e,t){let n=t.maxFrameBytes-29;if(n<1||t.maxFrameBytes<28)throw Error(`[PipeX] Encryption frame limit ${t.maxFrameBytes} bytes is too small`);let r=e.frameSizeBytes??Math.min(65536,n);if(!Number.isSafeInteger(r)||r<1||r>4294967295)throw Error(`[PipeX] Encryption frameSizeBytes must be a positive 32-bit integer`);if(r>n)throw Error(`[PipeX] Encryption frameSizeBytes exceeds the ${t.maxFrameBytes}-byte frame limit`);return r}function Ot(e,t){let n=e===0?0:Math.ceil(e/t);return 28+e+(n+1)*29}function kt(e,t){return e===0?0:Math.ceil(e/t)}function At(e,t,n=a(16)){let r=Buffer.alloc(28);return Z.copy(r,0),r.writeUInt8(1,4),r.writeUInt8(wt[e],5),r.writeUInt16BE(0,6),r.writeUInt32BE(t,8),n.copy(r,12),r}function jt(e,t){if(e.length!==28||!e.subarray(0,4).equals(Z))throw Error(`[PipeX] Decryption failed: invalid framed header`);if(e.readUInt8(4)!==1)throw Error(`[PipeX] Decryption failed: unsupported format version`);let n=Tt[e.readUInt8(5)];if(!n||e.readUInt16BE(6)!==0)throw Error(`[PipeX] Decryption failed: invalid framed header`);let r=e.readUInt32BE(8);if(r<1||r>t.maxFrameBytes-29)throw Error(`[PipeX] Decryption failed: invalid frame size`);return{bytes:e,algorithm:n,frameSizeBytes:r,salt:e.subarray(12,28)}}function Mt(e,t){let n=Buffer.from(`PipeX AEAD framed v1:${t.algorithm}`,`utf8`);return Buffer.from(i(`sha256`,e,t.salt,n,32))}function Nt(e){if(e<0n||e>18446744073709551615n)throw Error(`[PipeX] Encryption frame sequence exhausted`);let t=Buffer.alloc(12);return t.writeBigUInt64BE(e,4),t}function Pt(e,t,n){let r=Buffer.alloc(13);return r.writeUInt8(e,0),r.writeBigUInt64BE(t,1),r.writeUInt32BE(n,9),r}function Q(e,n,r,i,a,o){let s=Pt(n,r,e.length),c=Nt(r);try{let n=t(i,a,c,{authTagLength:16});n.setAAD(Buffer.concat([o,s]));let r=Buffer.concat([n.update(e),n.final()]);return Buffer.concat([s,r,n.getAuthTag()],29+r.length)}finally{c.fill(0)}}function Ft(e,t,r,i,a,o,s){let c=Nt(i),l=n(a,o,c,{authTagLength:16});l.setAAD(Buffer.concat([s,r])),l.setAuthTag(t);let u=l.update(e);try{let e=l.final();return e.length===0?u:Buffer.concat([u,e])}catch{throw u.fill(0),Error(`[PipeX] Decryption failed: authentication failed`)}finally{c.fill(0)}}function It(e,t,r){if(e.length<29)throw Error(`[PipeX] Decryption failed: packet too short`);if(e.length-29>r.maxOutputBytes)throw Error(`[PipeX] Decryption output exceeds ${r.maxOutputBytes} bytes`);let i=Tt[e.readUInt8(0)];if(!i)throw Error(`[PipeX] Decryption failed: unknown legacy algorithm`);let a=n(i,t,e.subarray(1,13),{authTagLength:16});a.setAuthTag(e.subarray(13,29));let o=a.update(e.subarray(29));try{let e=a.final();return e.length===0?o:Buffer.concat([o,e])}catch{throw o.fill(0),Error(`[PipeX] Decryption failed: authentication failed`)}}function Lt(e){return e.length>=Z.length&&e.subarray(0,Z.length).equals(Z)}function Rt(e,t,n){let r=Et(n);if(e.length>r.maxInputBytes)throw Error(`[PipeX] Encryption input exceeds ${r.maxInputBytes} bytes`);let i=Dt(t,r);if(kt(e.length,i)>r.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${r.maxFrames}`);let a=Ot(e.length,i);if(a>r.maxOutputBytes)throw Error(`[PipeX] Encryption output exceeds ${r.maxOutputBytes} bytes`);let o=At(t.algorithm,i),s=jt(o,r),c=Mt(t.key,s),l=[o],u=0n;try{for(let n=0;n<e.length;n+=i)l.push(Q(e.subarray(n,Math.min(e.length,n+i)),1,u++,t.algorithm,c,o));return l.push(Q(Buffer.alloc(0),2,u,t.algorithm,c,o)),Buffer.concat(l,a)}finally{c.fill(0)}}function zt(e,t,n){let r=Et(n);if(e.length>r.maxInputBytes)throw Error(`[PipeX] Decryption input exceeds ${r.maxInputBytes} bytes`);if(e.length===0||!Lt(e)&&e.readUInt8(0)!==Z.readUInt8(0)){if(t.allowLegacyDecrypt===!1)throw Error(`[PipeX] Decryption failed: legacy format disabled`);return It(e,t.key,r)}if(e.length<28)throw Error(`[PipeX] Decryption failed: incomplete framed header`);let i=jt(e.subarray(0,28),r),a=Mt(t.key,i),o=[],s=0,c=28,l=0n,u=0,d=!1;try{for(;c<e.length;){if(d||e.length-c<13)throw Error(`[PipeX] Decryption failed: incomplete or trailing frame`);let t=e.subarray(c,c+13);c+=13;let n=t.readUInt8(0),f=t.readBigUInt64BE(1),p=t.readUInt32BE(9);if(f!==l)throw Error(`[PipeX] Decryption failed: invalid frame sequence`);if(n!==1&&n!==2)throw Error(`[PipeX] Decryption failed: invalid frame type`);if(n===2&&p!==0)throw Error(`[PipeX] Decryption failed: invalid final frame`);if(p>i.frameSizeBytes||p>r.maxFrameBytes-29)throw Error(`[PipeX] Decryption failed: frame length exceeds configured limit`);if(n===1&&u>=r.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${r.maxFrames}`);if(n===1&&p>r.maxOutputBytes-s)throw Error(`[PipeX] Decryption output exceeds ${r.maxOutputBytes} bytes`);if(e.length-c<p+16)throw Error(`[PipeX] Decryption failed: incomplete frame`);let m=e.subarray(c,c+p);c+=p;let h=e.subarray(c,c+16);c+=16;let g=Ft(m,h,t,f,i.algorithm,a,i.bytes);n===2?(g.fill(0),d=!0):(u++,s+=g.length,o.push(g)),l++}if(!d)throw Error(`[PipeX] Decryption failed: missing authenticated final frame`);let t=Buffer.concat(o,s);for(let e of o)e.fill(0);return t}catch(e){for(let e of o)e.fill(0);throw e}finally{a.fill(0)}}function Bt(e,t){let n=Et(t),r=Dt(e,n);if(Ot(0,r)>n.maxOutputBytes)throw Error(`[PipeX] Encryption output exceeds ${n.maxOutputBytes} bytes`);let i=At(e.algorithm,r),a=jt(i,n),o=Mt(e.key,a),s=Buffer.alloc(r),c=0,l=0,u=0,d=0n,p=!1,m=()=>{s.fill(0),o.fill(0)};return new f({transform(t,a,f){try{let a=Buffer.isBuffer(t)?t:Buffer.from(t);if(a.length>n.maxInputBytes-l)throw Error(`[PipeX] Encryption input exceeds ${n.maxInputBytes} bytes`);let m=l+a.length;if(kt(m,r)>n.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${n.maxFrames}`);if(Ot(m,r)>n.maxOutputBytes)throw Error(`[PipeX] Encryption output exceeds ${n.maxOutputBytes} bytes`);l=m,p||=(this.push(i),!0);let h=0;for(;h<a.length;){let t=Math.min(r-c,a.length-h);if(a.copy(s,c,h,h+t),c+=t,h+=t,c===r){if(++u>n.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${n.maxFrames}`);this.push(Q(s,1,d++,e.algorithm,o,i)),s.fill(0),c=0}}f()}catch(e){m(),f(e)}},flush(t){try{if(p||=(this.push(i),!0),c>0){if(++u>n.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${n.maxFrames}`);this.push(Q(s.subarray(0,c),1,d++,e.algorithm,o,i))}this.push(Q(Buffer.alloc(0),2,d,e.algorithm,o,i)),m(),t()}catch(e){m(),t(e)}},destroy(e,t){m(),t(e)}})}function Vt(e,t){let n=Et(t),r=`unknown`,i=0,a=0,o=Buffer.alloc(28),s=0,c,l,u=Buffer.alloc(13),d=0,p,m=0,h=0n,g=0,_=!1,v=[],y=()=>{l?.fill(0),p?.fill(0),o.fill(0),u.fill(0),v=[]},b=(t,r)=>{let i=0;for(;i<t.length;){if(_)throw Error(`[PipeX] Decryption failed: trailing data after final frame`);if(!c){let r=Math.min(28-s,t.length-i);t.copy(o,s,i,i+r),s+=r,i+=r,s===28&&(c=jt(o,n),l=Mt(e.key,c));continue}if(d<13){let e=Math.min(13-d,t.length-i);if(t.copy(u,d,i,i+e),d+=e,i+=e,d<13)continue;let r=u.readUInt8(0),o=u.readBigUInt64BE(1),s=u.readUInt32BE(9);if(o!==h)throw Error(`[PipeX] Decryption failed: invalid frame sequence`);if(r!==1&&r!==2)throw Error(`[PipeX] Decryption failed: invalid frame type`);if(r===2&&s!==0)throw Error(`[PipeX] Decryption failed: invalid final frame`);if(s>c.frameSizeBytes||s>n.maxFrameBytes-29)throw Error(`[PipeX] Decryption failed: frame length exceeds configured limit`);if(r===1&&g>=n.maxFrames)throw Error(`[PipeX] Encryption frame count exceeds ${n.maxFrames}`);if(r===1&&s>n.maxOutputBytes-a)throw Error(`[PipeX] Decryption output exceeds ${n.maxOutputBytes} bytes`);p=Buffer.alloc(s+16),m=0}let f=Math.min(p.length-m,t.length-i);if(t.copy(p,m,i,i+f),m+=f,i+=f,m<p.length)continue;let v=u.readUInt8(0),y=u.readBigUInt64BE(1),b=u.readUInt32BE(9),x=Ft(p.subarray(0,b),p.subarray(b),u,y,c.algorithm,l,c.bytes);v===2?(x.fill(0),_=!0):(g++,a+=x.length,r.push(x)),h++,p.fill(0),p=void 0,m=0,u.fill(0),d=0}};return new f({transform(t,a,o){try{let a=Buffer.isBuffer(t)?t:Buffer.from(t);if(a.length>n.maxInputBytes-i)throw Error(`[PipeX] Decryption input exceeds ${n.maxInputBytes} bytes`);if(i+=a.length,a.length===0)return o();if(r===`unknown`&&(r=a.readUInt8(0)===Z.readUInt8(0)?`framed`:`legacy`,r===`legacy`&&e.allowLegacyDecrypt===!1))throw Error(`[PipeX] Decryption failed: legacy format disabled`);r===`legacy`?v.push(a):b(a,this),o()}catch(e){y(),o(e)}},flush(t){try{if(r===`legacy`){let r=It(Buffer.concat(v,i),e.key,n);return this.push(r),y(),t()}if(r!==`framed`||!c||d!==0||p)throw Error(`[PipeX] Decryption failed: incomplete encrypted stream`);if(!_)throw Error(`[PipeX] Decryption failed: missing authenticated final frame`);y(),t()}catch(e){y(),t(e)}},destroy(e,t){y(),t(e)}})}var Ht=class extends j{name=`encryption`;version=`4.0.0`;constructor(e){if(super(e),this.options=e,!e||![`aes-256-gcm`,`chacha20-poly1305`].includes(e.algorithm)||!Buffer.isBuffer(e.key)||e.key.length!==32)throw Error(`[PipeX] Encryption: invalid algorithm or key`);if(e.frameSizeBytes!==void 0&&(!Number.isSafeInteger(e.frameSizeBytes)||e.frameSizeBytes<1||e.frameSizeBytes>4294967295))throw Error(`[PipeX] Encryption frameSizeBytes must be a positive 32-bit integer`);if(e.allowLegacyDecrypt!==void 0&&typeof e.allowLegacyDecrypt!=`boolean`)throw Error(`[PipeX] Encryption allowLegacyDecrypt must be a boolean`)}async process(e,t){return Rt(e,this.options,t)}async reverse(e,t){return zt(e,this.options,t)}createStream(e,t){return e===`compress`?Bt(this.options,t):Vt(this.options,t)}};const Ut={none:0,gzip:1,brotli:2},Wt={0:`none`,1:`gzip`,2:`brotli`},Gt=ue(le),Kt=ue(ce),qt=ue(ne),Jt=ue(re);var Yt=class extends j{name=`compression`;version=`3.0.0`;constructor(e){if(super(e),this.options=e,!(e.type in Ut))throw Error(`[PipeX] Compression: unknown type`);if(e.level!==void 0&&!Number.isInteger(e.level))throw Error(`[PipeX] Compression: level must be an integer`);if(e.type===`gzip`&&e.level!==void 0&&(e.level<0||e.level>9))throw Error(`[PipeX] Compression: gzip level must be between 0 and 9`);if(e.type===`brotli`&&e.level!==void 0&&(e.level<0||e.level>11))throw Error(`[PipeX] Compression: Brotli level must be between 0 and 11`);if(e.type===`none`&&e.level!==void 0)throw Error(`[PipeX] Compression: level is not supported when type is none`)}async process(e,t){let n=N(t),r=P(t);if(e.length>n)throw Error(`[PipeX] Compression input exceeds ${n} bytes`);let{type:i,level:a}=this.options,o=Buffer.from([Ut[i]]);if(e.length>r-o.length&&i===`none`||r<=o.length&&i!==`none`)throw Error(`[PipeX] Compression output exceeds ${r} bytes`);let s;return s=i===`gzip`?await Gt(e,{level:a??6,maxOutputLength:r-o.length}):i===`brotli`?await qt(e,{params:{[T.BROTLI_PARAM_QUALITY]:a??11},maxOutputLength:r-o.length}):e,Buffer.concat([o,s])}async reverse(e,t){let n=N(t),r=P(t);if(e.length>n)throw Error(`[PipeX] Compression input exceeds ${n} bytes`);if(e.length<1)throw Error(`[PipeX] Compression reverse: packet too short`);let i=Wt[e.readUInt8(0)],a=e.subarray(1);if(i===`gzip`)return await Kt(a,{maxOutputLength:r});if(i===`brotli`)return await Jt(a,{maxOutputLength:r});if(i!==`none`)throw Error(`[PipeX] Compression: unknown type`);if(a.length>r)throw Error(`[PipeX] Compression output exceeds ${r} bytes`);return a}createStream(e,t){let{type:n,level:r}=this.options,i=N(t),a=P(t);if(e===`compress`){let e=n===`gzip`?se({level:r??6}):n===`brotli`?ie({params:{[T.BROTLI_PARAM_QUALITY]:r??11}}):new u,t=!1,o=new f({transform(e,r,i){t||(t=!0,this.push(Buffer.from([Ut[n]]))),i(null,e)},flush(e){t||this.push(Buffer.from([Ut[n]])),e()}});return m(W(i,`compression input`),e,o,W(a,`compression output`))}return l.from(async function*(e){let t=e[Symbol.asyncIterator](),n,r=0,o=0;for(;!n;){let e=await t.next();if(e.done)throw Error(`[PipeX] Stream decompression: packet too short`);let a=Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value);if(a.length>i-r)throw Error(`[PipeX] Compression input exceeds ${i} bytes`);r+=a.length,a.length>0&&(n=a)}let s=Wt[n.readUInt8(0)];if(!s)throw Error(`[PipeX] Stream decompression: unknown type`);let c=s===`gzip`?oe():s===`brotli`?ae():new u;async function*l(){let e=n.subarray(1);for(e.length>0&&(yield e);;){let e=await t.next();if(e.done)return;let n=Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value);if(n.length>i-r)throw Error(`[PipeX] Compression input exceeds ${i} bytes`);r+=n.length,n.length>0&&(yield n)}}try{for await(let e of m(d.from(l()),c)){let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(t.length>a-o)throw Error(`[PipeX] Compression output exceeds ${a} bytes`);o+=t.length,yield t}}finally{c.destroy();try{await t.return?.()}catch{}}})}},Xt=class extends j{name=`benchmark`;version=`2.0.0`;async process(e,t){t.metadata??={};let n=t.metadata[`benchmark:start`]||Date.now();return t.metadata[`benchmark:in_bytes`]=e.length,t.metadata[`benchmark:start`]=n,e}async reverse(e,t){t.metadata??={},t.metadata[`benchmark:out_bytes`]=e.length;let n=t.metadata[`benchmark:start`];return n&&(t.metadata[`benchmark:duration_ms`]=Date.now()-n),e}};const Zt=2147483647,Qt=1e5,$t=Math.max(1,Math.min(4,fe()));function en(e,t,n=!1){if(e!==void 0&&(!Number.isSafeInteger(e)||e<+!n))throw Error(`[PipeX] Worker pool ${t} must be ${n?`a non-negative`:`a positive`} integer`)}function tn(e,t){let n=t??e.limits?.operationTimeoutMs??M.operationTimeoutMs;if(!Number.isSafeInteger(n)||n<0||n>Zt)throw Error(`[PipeX] Invalid worker task timeout`);if(n===0)return{signal:e.signal,cleanup(){}};let r=new AbortController,i=setTimeout(()=>{r.abort(new DOMException(`Worker task timed out`,`TimeoutError`))},n);return i.unref(),{signal:e.signal?AbortSignal.any([e.signal,r.signal]):r.signal,cleanup(){clearTimeout(i)}}}function nn(e){return e.reason instanceof Error&&e.reason.name===`TimeoutError`?new A({cause:e.reason}):new k({cause:e.reason})}var rn=class extends j{name=`worker-pool`;version=`5.0.0`;#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=!0;#u=0;#d;#f;#p=new Set;#m;constructor(e){if(super(e),!e||!(typeof e.filename==`string`||e.filename instanceof URL))throw Error(`[PipeX] Worker pool requires a worker filename`);if(en(e.maxThreads,`maxThreads`),en(e.maxQueue,`maxQueue`),en(e.taskTimeoutMs,`taskTimeoutMs`,!0),en(e.closeTimeoutMs,`closeTimeoutMs`,!0),e.maxThreads!==void 0&&e.maxThreads>128)throw Error(`[PipeX] Worker pool maxThreads cannot exceed 128`);if(e.maxQueue!==void 0&&e.maxQueue>Qt)throw Error(`[PipeX] Worker pool maxQueue cannot exceed ${Qt}`);if(e.taskTimeoutMs!==void 0&&e.taskTimeoutMs>Zt)throw Error(`[PipeX] Worker pool taskTimeoutMs exceeds the supported timer range`);if(e.closeTimeoutMs!==void 0&&e.closeTimeoutMs>Zt)throw Error(`[PipeX] Worker pool closeTimeoutMs exceeds the supported timer range`);for(let[t,n]of[[`processName`,e.processName],[`reverseName`,e.reverseName]])if(n!==void 0&&(typeof n!=`string`||n.length===0||n.length>128))throw Error(`[PipeX] Worker pool ${t} must be a non-empty export name`);let t=e.filename instanceof URL?de(e.filename):e.filename;this.#t=e.processName,this.#n=e.reverseName,this.#r=e.taskTimeoutMs,this.#i=e.maxThreads??$t,this.#a=e.maxQueue??64,this.#o=this.#i+this.#a,this.#s=e.closeTimeoutMs??3e4,this.#c=!!e.reverseName,this.#e=new pe({filename:t,minThreads:0,maxThreads:this.#i,maxQueue:this.#a,closeTimeout:this.#s}),this.#m=e=>{this.#f||(this.#f=new Te(`worker-thread`,{cause:e}),this.#l=!1,this.#e.destroy().catch(()=>void 0))},this.#e.on(`error`,this.#m)}get reversible(){return this.#c}async#h(e,t,n){if(this.#f)throw this.#f;if(!this.#l)throw new Se;let r=N(t);if(e.length>r)throw Error(`[PipeX] Worker input exceeds ${r} bytes`);if(this.#u>=this.#o)throw new Ce(this.#a);let i=tn(t,this.#r);this.#u++;try{i.signal?.throwIfAborted();let r=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),a=await this.#e.run(r,{transferList:[r],signal:i.signal,name:n});if(!(a instanceof ArrayBuffer)&&!ArrayBuffer.isView(a))throw Error(`worker returned a non-binary value`);let o=a instanceof ArrayBuffer?Buffer.from(a):Buffer.from(a.buffer,a.byteOffset,a.byteLength),s=P(t);if(o.length>s)throw Error(`[PipeX] Worker output exceeds ${s} bytes`);return o}catch(e){throw i.signal?.aborted?nn(i.signal):e instanceof Se||e instanceof Ce?e:e instanceof Error&&(e.message===`Task queue is at limit`||e.message===`No task queue available and all Workers are busy`)?new Ce(this.#a):new Te(n??`default`,{cause:e})}finally{if(i.cleanup(),this.#u--,this.#u===0){for(let e of this.#p)e();this.#p.clear()}}}process(e,t){return this.#h(e,t,this.#t)}reverse(e,t){if(!this.#n)throw new D(`${this.name}@${this.version}`);return this.#h(e,t,this.#n)}createStream(e,t){if(e===`decompress`&&!this.#n)throw new D(this.name);let n=new AbortController,r=t?.signal?AbortSignal.any([t.signal,n.signal]):n.signal,i=t?.limits??M,a=Math.min(i.maxFrameBytes,4294967294),o=Buffer.from([80,88,87,75,1]),s=Buffer.from([255,255,255,255]),c=0,l=0,u=0,d=!1,p=!1,m=Buffer.alloc(o.length),h=0,g,_=0,v=this,y=(e,t)=>{if(t.length>i.maxOutputBytes-l)throw Error(`[PipeX] Worker stream output exceeds configured limit`);l+=t.length,e.push(t)},b=async n=>{if(++u>i.maxFrames)throw Error(`[PipeX] Worker frame count exceeds configured limit`);let o={requestId:t?.requestId??`worker-stream`,timestamp:Date.now(),signal:r,limits:i,logger:t?.logger,metadata:{}},s=e===`decompress`?v.reverse(n,o):v.process(n,o);t?.track?.(s);let c=await s;if(r.throwIfAborted(),c.length>a)throw Error(`[PipeX] Worker frame exceeds configured limit`);return c};return new f({transform(n,i,s){let l=this;(async()=>{if(r.throwIfAborted(),n.length>N(t)-c)throw Error(`[PipeX] Worker stream input exceeds configured limit`);if(c+=n.length,e===`compress`){d||=(y(l,o),!0);for(let e=0;e<n.length;e+=a){let t=await b(n.subarray(e,e+a)),r=Buffer.alloc(4);r.writeUInt32BE(t.length),y(l,r),y(l,t)}return}let i=0;for(;i<n.length;){if(p)throw Error(`[PipeX] Worker stream has trailing bytes`);if(!g){let e=Math.min(m.length-h,n.length-i);if(n.copy(m,h,i,i+e),h+=e,i+=e,h!==m.length)continue;if(!d){if(!m.equals(o))throw Error(`[PipeX] Invalid worker stream format`);d=!0,m=Buffer.alloc(4),h=0;continue}let t=m.readUInt32BE();if(h=0,t===4294967295){p=!0;continue}if(t>a)throw Error(`[PipeX] Worker frame exceeds configured limit`);g=Buffer.alloc(t),_=0}let e=Math.min(g.length-_,n.length-i);n.copy(g,_,i,i+e),_+=e,i+=e,_===g.length&&(y(l,await b(g)),g=void 0,_=0)}})().then(()=>s(),e=>s(e))},flush(t){try{if(r.throwIfAborted(),e===`compress`)d||y(this,o),y(this,s);else if(!p||g||h)throw Error(`[PipeX] Incomplete worker stream`);t()}catch(e){t(e)}},destroy(e,t){r.aborted||n.abort(e??new DOMException(`Worker stream destroyed`,`AbortError`)),g=void 0,t(e)}})}async close(e={}){if(!e||e.force!==void 0&&typeof e.force!=`boolean`)throw TypeError(`[PipeX] Worker pool close force must be a boolean`);return this.#d?this.#d:(this.#l=!1,this.#d=(async()=>{try{if(this.#f)await this.#e.destroy();else if(e.force)await this.#e.destroy();else if(this.#u>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),e()},r=setTimeout(()=>{this.#p.delete(n),t(new we)},this.#s);this.#p.add(n)}),await this.#e.close({force:!1}),this.#f)throw this.#f}catch(e){throw await this.#e.destroy().catch(()=>void 0),e instanceof we?e:new we({cause:e})}finally{this.#e.removeListener(`error`,this.#m)}})(),this.#d)}},an=class extends j{name=`validation`;version=`1.0.0`;constructor(e){super(e),this.options=e}async process(e,t){return this.validate(e,Math.min(N(t),P(t)),t.limits?.maxFrameBytes),e}async reverse(e,t){let n=Math.min(N(t),P(t));if(e.length>n)throw Error(`[PipeX] Validation input exceeds ${n} bytes`);return this.options.validateOnReverse&&this.validate(e,n,t.limits?.maxFrameBytes),e}validate(e,t,n=M.maxFrameBytes){if(e.length>t)throw Error(`[PipeX] Validation input exceeds ${t} bytes`);F(e,n,1);let r;try{r=V.unpack(e)}catch{throw Error(`[PipeX] Validation: invalid MessagePack input`)}if(!this.options.schema.safeParse(r).success)throw Error(`[PipeX] Validation failed`)}createStream(e=`compress`,t){let n=[],r=0,i=Math.min(N(t),P(t));return new f({transform(e,t,a){if(e.length>i-r)return a(Error(`[PipeX] Validation input exceeds ${i} bytes`));r+=e.length,n.push(e),a()},flush:a=>{try{let o=Buffer.concat(n,r);(e!==`decompress`||this.options.validateOnReverse)&&this.validate(o,i,t?.limits?.maxFrameBytes),a(null,o)}catch(e){a(e)}}})}};const $=Buffer.from(`PXKM`);function on(e){let t={cause:e.reason};return e.reason instanceof Error&&e.reason.name===`TimeoutError`?new A(t):new k(t)}async function sn(e,t,n){if(!t)return e;if(t.aborted)throw e.then(e=>{try{n?.(e)}catch{}},()=>void 0),on(t);return new Promise((r,i)=>{let a=!1,o=()=>{a=!0,i(on(t))};t.addEventListener(`abort`,o,{once:!0}),e.then(e=>{if(t.removeEventListener(`abort`,o),a)try{n?.(e)}catch{}else r(e)},e=>{t.removeEventListener(`abort`,o),a||i(e)})})}function cn(e){let t=e.limits?.operationTimeoutMs??M.operationTimeoutMs;if(!Number.isSafeInteger(t)||t<0||t>2147483647)throw Error(`[PipeX] Invalid KMS provider timeout`);if(t===0)return{signal:e.signal,cleanup(){}};let n=new AbortController,r=setTimeout(()=>{n.abort(new DOMException(`KMS provider operation timed out`,`TimeoutError`))},t);return{signal:e.signal?AbortSignal.any([e.signal,n.signal]):n.signal,cleanup(){clearTimeout(r)}}}function ln(e,t){return t instanceof k||t instanceof A?t:t instanceof ve?new ve(e):t instanceof ye?new ye(e):new ge(e)}async function un(e,t,n,r,i){xt(e,t);let a=cn(n);try{if(a.signal?.aborted)throw on(a.signal);return await sn(r(a.signal),a.signal,i)}catch(e){throw a.signal?.aborted?on(a.signal):ln(t,e)}finally{a.cleanup()}}var dn=class extends j{name=`kms-encryption`;version=`2.1.0`;streaming=!1;get providerCapabilities(){return yt(this.options.kms)}get reversible(){return this.providerCapabilities.decrypt}constructor(e){if(super(e),this.options=e,!e||!e.kms||typeof e.keyId!=`string`||e.keyId.length===0)throw Error(`[PipeX] KMS Encryption: invalid provider or keyId`);if(e.allowLegacyDecrypt!==void 0&&typeof e.allowLegacyDecrypt!=`boolean`)throw Error(`[PipeX] KMS Encryption allowLegacyDecrypt must be a boolean`);yt(e.kms),xt(e.kms,`generateDataKey`)}async process(e,n){let r=N(n),i=P(n),o=n.limits?.maxKmsEncryptedKeyBytes??M.maxKmsEncryptedKeyBytes,s=n.limits?.maxKmsKeyIdBytes??M.maxKmsKeyIdBytes;if(Buffer.byteLength(this.options.keyId)>s)throw Error(`[PipeX] KMS key identifier exceeds the configured limit`);if(e.length>r)throw Error(`[PipeX] KMS encryption input exceeds ${r} bytes`);if(e.length>4294967295)throw Error(`[PipeX] KMS encryption input exceeds the format limit`);if(e.length>i-45)throw Error(`[PipeX] KMS encryption output exceeds ${i} bytes`);let{kms:c,keyId:l}=this.options,u=await un(c,`generateDataKey`,n,e=>c.generateDataKey(l,{signal:e}),e=>{Buffer.isBuffer(e?.plaintext)&&e.plaintext.fill(0)}),d=u?.plaintext;try{let n=u?.ciphertext;if(!Buffer.isBuffer(d)||d.length!==32)throw Error(`[PipeX] KMS generated an invalid data key`);if(!Buffer.isBuffer(n)||n.length<1||n.length>o)throw Error(`[PipeX] KMS generated an invalid encrypted key`);let r=28+n.length+16;if(e.length>i-r)throw Error(`[PipeX] KMS encryption output exceeds ${i} bytes`);let s=r+e.length,c=a(12),l=t(`aes-256-gcm`,d,c,{authTagLength:16}),f=Buffer.alloc(28);$.copy(f,0),f.writeUInt8(1,4),f.writeUInt8(1,5),f.writeUInt16BE(0,6),f.writeUInt32BE(n.length,8),f.writeUInt32BE(e.length,12),c.copy(f,16),l.setAAD(Buffer.concat([f,n]));let p=Buffer.concat([l.update(e),l.final()]),m=l.getAuthTag();return Buffer.concat([f,n,p,m],s)}finally{Buffer.isBuffer(d)&&d.fill(0)}}async reverse(e,t){let{kms:r,keyId:i}=this.options;xt(r,`decrypt`);let a=N(t),o=P(t),s=t.limits?.maxKmsEncryptedKeyBytes??M.maxKmsEncryptedKeyBytes,c=t.limits?.maxKmsKeyIdBytes??M.maxKmsKeyIdBytes;if(Buffer.byteLength(i)>c)throw Error(`[PipeX] KMS key identifier exceeds the configured limit`);if(e.length>a)throw Error(`[PipeX] KMS decryption input exceeds ${a} bytes`);if(e.length===0)throw Error(`[PipeX] KMS Decryption: Packet too short`);let l=e.length>=$.length&&e.subarray(0,$.length).equals($);if(!l&&e.readUInt8(0)===$.readUInt8(0))throw Error(`[PipeX] KMS Decryption: incomplete framed header`);if(!l&&this.options.allowLegacyDecrypt===!1)throw Error(`[PipeX] KMS Decryption: legacy format disabled`);let u,d,f,p,m;if(l){if(e.length<45)throw Error(`[PipeX] KMS Decryption: incomplete framed envelope`);if(e.readUInt8(4)!==1)throw Error(`[PipeX] KMS Decryption: unsupported format version`);if(e.readUInt8(5)!==1||e.readUInt16BE(6)!==0)throw Error(`[PipeX] KMS Decryption: invalid framed envelope`);let t=e.readUInt32BE(8),n=e.readUInt32BE(12);if(t<1||t>s)throw Error(`[PipeX] KMS Decryption: invalid key envelope`);if(28+t+n+16!==e.length)throw Error(`[PipeX] KMS Decryption: invalid envelope length`);if(n>o)throw Error(`[PipeX] KMS decryption output exceeds ${o} bytes`);d=e.subarray(16,28),u=e.subarray(28,28+t),p=e.subarray(28+t,e.length-16),f=e.subarray(e.length-16),m=e.subarray(0,28+t)}else{if(e.length<4)throw Error(`[PipeX] KMS Decryption: Packet too short`);let t=e.readUInt32BE(0);if(t<1||t>s||e.length<4+t+12+16)throw Error(`[PipeX] KMS Decryption: invalid key envelope`);u=e.subarray(4,4+t),d=e.subarray(4+t,4+t+12),f=e.subarray(4+t+12,4+t+12+16),p=e.subarray(4+t+12+16)}if(p.length>o)throw Error(`[PipeX] KMS decryption output exceeds ${o} bytes`);let h=await un(r,`decrypt`,t,e=>r.decrypt(u,i,{signal:e}),e=>{Buffer.isBuffer(e)&&e.fill(0)});try{if(!Buffer.isBuffer(h)||h.length!==32)throw Error(`[PipeX] KMS Decryption: invalid data key length`);let e=n(`aes-256-gcm`,h,d,{authTagLength:16});m&&e.setAAD(m),e.setAuthTag(f);let t=e.update(p);try{let n=e.final();return n.length===0?t:Buffer.concat([t,n])}catch{throw t.fill(0),new _e}}finally{Buffer.isBuffer(h)&&h.fill(0)}}};const fn={Hashing:Ct,Encryption:Ht,Compression:Yt,Benchmark:Xt,WorkerPool:rn,Validation:an,KmsEncryption:dn};X.registerPlugin(`hashing`,Ct),X.registerPlugin(`encryption`,Ht),X.registerPlugin(`compression`,Yt),X.registerPlugin(`benchmark`,Xt),X.registerPlugin(`worker-pool`,rn),X.registerPlugin(`validation`,an),X.registerPlugin(`kms-encryption`,dn);export{j as BasePlugin,Xt as BenchmarkPlugin,Yt as CompressionPlugin,H as DEFAULT_HIGH_WATER,M as DEFAULT_LIMITS,X as DataEngine,Ht as EncryptionPlugin,Ye as GuardedUnpackrStream,Ct as HashingPlugin,xe as InvalidKmsProviderCapabilityError,O as InvalidPluginCapabilityError,_e as KmsAuthenticationError,dn as KmsEncryptionPlugin,ve as KmsProviderAuthenticationError,ge as KmsProviderError,ye as KmsProviderUnavailableError,Pe as MAX_FRAME_BYTES,Ue as ORIGINAL_TYPES,k as OperationAbortedError,A as OperationTimeoutError,B as PACKR,Ne as PIPEX_MANIFEST_KEY,E as PipeXError,fn as Plugins,V as UNPACKR,be as UnsupportedKmsOperationError,D as UnsupportedReverseError,he as UnsupportedStreamingError,an as ValidationPlugin,we as WorkerPoolCloseError,Se as WorkerPoolClosedError,rn as WorkerPoolPlugin,Ce as WorkerQueueFullError,Te as WorkerTaskError,nt as assertExists,K as assertKnownValueByteLimit,F as assertMessagePackFrameLimits,U as assertOriginalType,ze as assertReversiblePipeline,Be as assertStreamingPipeline,W as buildByteLimitTransform,$e as buildFallbackTransform,I as buildFrameLimitTransform,Qe as buildKnownValueByteLimitTransform,Ke as buildManifest,Je as buildManifestExtractTransform,qe as buildManifestHeaderTransform,et as buildNdjsonTransform,G as buildObjectLimitTransform,q as buildTransformChain,Xe as createPackrStream,Ze as createUnpackrStream,Ve as detectType,We as fromBuffer,yt as getKmsProviderCapabilities,Ie as getPluginCapabilities,Fe as hasStreamSupport,me as isManifest,Ge as makeContext,rt as resolveOutputPath,J as runPipeline,bt as supportsKmsOperation,Le as supportsOperation,Re as supportsReverse,He as toBuffer,Me as withRetry};
3
- //# sourceMappingURL=index.mjs.map
1
+ import{A as e,C as t,D as n,E as r,H as i,M as a,N as ee,O as o,P as s,S as c,T as l,U as te,V as ne,_ as re,a as ie,b as ae,c as oe,d as se,f as ce,g as u,h as d,i as f,j as p,k as m,l as h,m as g,n as _,o as v,p as y,r as b,s as x,t as S,u as C,v as w,w as T,x as E,y as D}from"./core-BOdvxKBq.mjs";import{C as O,D as k,E as A,O as j,S as M,T as N,_ as P,a as F,b as I,c as le,d as L,f as R,g as z,h as B,i as V,l as H,m as U,o as W,p as ue,s as de,t as fe,u as pe,v as me,w as he,x as ge,y as _e}from"./resourceLimits-C1HHDwXQ.mjs";import{t as G}from"./dataEngine-4m6GTOLe.mjs";import{n as ve,r as ye,t as K}from"./kms_encryption-R9auKGW4.mjs";import{t as q}from"./hashing-ChrADfcH.mjs";import{t as J}from"./encryption-CqxtoqAD.mjs";import{t as Y}from"./compression-2mm0MhWY.mjs";import{t as X}from"./worker-c0_VZ9c7.mjs";import{t as Z}from"./validation-P5WRSAUK.mjs";var Q=class e{constructor(e){this.transforms=e}static from(t){return new e([t])}pipe(t){return new e([...this.transforms,t])}async run(e,t={}){let n=e,r=t.signal,i=()=>{if(r?.aborted)throw new z};i();for(let e of this.transforms){i();let a=Promise.resolve(e(n,t));n=r?await new Promise((e,t)=>{let n=()=>t(new z);r.addEventListener(`abort`,n,{once:!0}),a.then(e,t).finally(()=>r.removeEventListener(`abort`,n)).catch(()=>{}),r.aborted&&n()}):await a}return i(),n}};function be(e){return Q.from(e)}var $=class extends V{name=`benchmark`;version=`2.0.0`;async process(e,t){t.metadata??={};let n=t.metadata[`benchmark:start`]||Date.now();return t.metadata[`benchmark:in_bytes`]=e.length,t.metadata[`benchmark:start`]=n,e}async reverse(e,t){t.metadata??={},t.metadata[`benchmark:out_bytes`]=e.length;let n=t.metadata[`benchmark:start`];return n&&(t.metadata[`benchmark:duration_ms`]=Date.now()-n),e}};const xe={Hashing:q,Encryption:J,Compression:Y,Benchmark:$,WorkerPool:X,Validation:Z,KmsEncryption:K};G.registerPlugin(`hashing`,q),G.registerPlugin(`encryption`,J),G.registerPlugin(`compression`,Y),G.registerPlugin(`benchmark`,$),G.registerPlugin(`worker-pool`,X),G.registerPlugin(`validation`,Z),G.registerPlugin(`kms-encryption`,K);export{F as AuthenticationError,V as BasePlugin,$ as BenchmarkPlugin,W as CompressionError,Y as CompressionPlugin,S as DEFAULT_HIGH_WATER,fe as DEFAULT_LIMITS,G as DataEngine,de as EncryptionError,J as EncryptionPlugin,_ as GuardedUnpackrStream,le as HashingError,q as HashingPlugin,H as InvalidKeyError,pe as InvalidKmsProviderCapabilityError,L as InvalidPluginCapabilityError,R as KmsAuthenticationError,K as KmsEncryptionPlugin,ue as KmsProviderAuthenticationError,U as KmsProviderError,B as KmsProviderUnavailableError,b as MAX_FRAME_BYTES,f as ORIGINAL_TYPES,z as OperationAbortedError,P as OperationTimeoutError,ie as PACKR,v as PIPEX_MANIFEST_KEY,me as PipeXError,_e as PipelineAbortedError,xe as Plugins,Q as TypedPipeline,x as UNPACKR,I as UnsupportedAlgorithmError,ge as UnsupportedKmsOperationError,M as UnsupportedReverseError,O as UnsupportedStreamingError,he as ValidationError,Z as ValidationPlugin,N as WorkerPoolCloseError,A as WorkerPoolClosedError,X as WorkerPoolPlugin,k as WorkerQueueFullError,j as WorkerTaskError,oe as assertExists,h as assertKnownValueByteLimit,ne as assertMessagePackFrameLimits,C as assertOriginalType,se as assertReversiblePipeline,ce as assertStreamingPipeline,y as buildByteLimitTransform,g as buildFallbackTransform,i as buildFrameLimitTransform,d as buildKnownValueByteLimitTransform,u as buildManifest,re as buildManifestExtractTransform,w as buildManifestHeaderTransform,D as buildNdjsonTransform,ae as buildObjectLimitTransform,E as buildTransformChain,c as createPackrStream,t as createUnpackrStream,T as detectType,l as fromBuffer,ve as getKmsProviderCapabilities,r as getPluginCapabilities,n as hasStreamSupport,te as isManifest,o as makeContext,m as resolveOutputPath,e as runPipeline,ye as supportsKmsOperation,p as supportsOperation,a as supportsReverse,ee as toBuffer,be as typedPipeline,s as withRetry};
package/dist/kms.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./kms_encryption-xyWi65rZ.cjs`);exports.KmsEncryptionPlugin=e.t;
package/dist/kms.d.cts ADDED
@@ -0,0 +1,3 @@
1
+ import { c as KmsOperation, d as KmsRequestOptions, l as KmsProvider, u as KmsProviderCapabilities } from "./types-ia4x-Dvp.cjs";
2
+ import { n as KmsEncryptionPlugin, t as KmsEncryptionOptions } from "./kms_encryption-Dh1LEHhk.cjs";
3
+ export { type KmsEncryptionOptions, KmsEncryptionPlugin, type KmsOperation, type KmsProvider, type KmsProviderCapabilities, type KmsRequestOptions };
package/dist/kms.d.mts ADDED
@@ -0,0 +1,3 @@
1
+ import { c as KmsOperation, d as KmsRequestOptions, l as KmsProvider, u as KmsProviderCapabilities } from "./types-Bytga6zd.mjs";
2
+ import { n as KmsEncryptionPlugin, t as KmsEncryptionOptions } from "./kms_encryption-Da-KqjKI.mjs";
3
+ export { type KmsEncryptionOptions, KmsEncryptionPlugin, type KmsOperation, type KmsProvider, type KmsProviderCapabilities, type KmsRequestOptions };
package/dist/kms.mjs ADDED
@@ -0,0 +1 @@
1
+ import{t as e}from"./kms_encryption-R9auKGW4.mjs";export{e as KmsEncryptionPlugin};
@@ -0,0 +1,33 @@
1
+ import { _ as ProcessorContext, l as KmsProvider, u as KmsProviderCapabilities } from "./types-Bytga6zd.mjs";
2
+ import { t as BasePlugin } from "./plugin-CE94-p8P.mjs";
3
+
4
+ //#region src/plugin/kms_encryption.d.ts
5
+ interface KmsEncryptionOptions {
6
+ kms: KmsProvider;
7
+ keyId: string;
8
+ /** Temporarily accept the unversioned v1 envelope while migrating. Defaults to false. */
9
+ allowLegacyDecrypt?: boolean;
10
+ }
11
+ /**
12
+ * KmsEncryptionPlugin — Enterprise-grade encryption using Envelope Encryption.
13
+ *
14
+ * 1. Generate a data key via KMS.
15
+ * 2. Encrypt data locally using the plaintext data key.
16
+ * 3. Prepend the encrypted data key (ciphertext) to the payload.
17
+ *
18
+ * Packet format: [PXKM][version][algorithm][flags][key_len][ciphertext_len]
19
+ * [12B IV][Encrypted Data Key][Ciphertext][16B Tag]
20
+ */
21
+ declare class KmsEncryptionPlugin extends BasePlugin {
22
+ protected options: KmsEncryptionOptions;
23
+ readonly name = "kms-encryption";
24
+ readonly version = "2.1.0";
25
+ readonly streaming = false;
26
+ get providerCapabilities(): Readonly<KmsProviderCapabilities>;
27
+ get reversible(): boolean;
28
+ constructor(options: KmsEncryptionOptions);
29
+ process(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
30
+ reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
31
+ }
32
+ //#endregion
33
+ export { KmsEncryptionPlugin as n, KmsEncryptionOptions as t };
@@ -0,0 +1,33 @@
1
+ import { _ as ProcessorContext, l as KmsProvider, u as KmsProviderCapabilities } from "./types-ia4x-Dvp.cjs";
2
+ import { t as BasePlugin } from "./plugin-C9Kd9coY.cjs";
3
+
4
+ //#region src/plugin/kms_encryption.d.ts
5
+ interface KmsEncryptionOptions {
6
+ kms: KmsProvider;
7
+ keyId: string;
8
+ /** Temporarily accept the unversioned v1 envelope while migrating. Defaults to false. */
9
+ allowLegacyDecrypt?: boolean;
10
+ }
11
+ /**
12
+ * KmsEncryptionPlugin — Enterprise-grade encryption using Envelope Encryption.
13
+ *
14
+ * 1. Generate a data key via KMS.
15
+ * 2. Encrypt data locally using the plaintext data key.
16
+ * 3. Prepend the encrypted data key (ciphertext) to the payload.
17
+ *
18
+ * Packet format: [PXKM][version][algorithm][flags][key_len][ciphertext_len]
19
+ * [12B IV][Encrypted Data Key][Ciphertext][16B Tag]
20
+ */
21
+ declare class KmsEncryptionPlugin extends BasePlugin {
22
+ protected options: KmsEncryptionOptions;
23
+ readonly name = "kms-encryption";
24
+ readonly version = "2.1.0";
25
+ readonly streaming = false;
26
+ get providerCapabilities(): Readonly<KmsProviderCapabilities>;
27
+ get reversible(): boolean;
28
+ constructor(options: KmsEncryptionOptions);
29
+ process(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
30
+ reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
31
+ }
32
+ //#endregion
33
+ export { KmsEncryptionPlugin as n, KmsEncryptionOptions as t };
@@ -0,0 +1 @@
1
+ import{_ as e,f as t,g as n,h as r,i,m as a,n as o,p as s,r as c,t as l,u,x as d}from"./resourceLimits-C1HHDwXQ.mjs";import{createCipheriv as f,createDecipheriv as p,randomBytes as m}from"node:crypto";const h=[`encrypt`,`decrypt`,`generateDataKey`];function g(e){if(!e||typeof e!=`object`)throw TypeError(`[PipeX] Invalid KMS provider`);if(e.capabilities!==void 0&&(!e.capabilities||typeof e.capabilities!=`object`))throw TypeError(`[PipeX] Invalid KMS provider capabilities`);let t={};for(let n of h){let r=e.capabilities?.[n],i=typeof e[n]==`function`;if(r!==void 0&&typeof r!=`boolean`)throw new u(n,`MUST_BE_BOOLEAN`);if(r===!0&&!i)throw new u(n,`MISSING_IMPLEMENTATION`);t[n]=r??i}return Object.freeze(t)}function _(e,t){if(!h.includes(t))throw TypeError(`[PipeX] Unknown KMS operation`);return g(e)[t]}function v(e,t){if(!_(e,t))throw new d(t)}const y=Buffer.from(`PXKM`);function b(t){let r={cause:t.reason};return t.reason instanceof Error&&t.reason.name===`TimeoutError`?new e(r):new n(r)}async function x(e,t,n){if(!t)return e;if(t.aborted)throw e.then(e=>{try{n?.(e)}catch{}},()=>void 0),b(t);return new Promise((r,i)=>{let a=!1,o=()=>{a=!0,i(b(t))};t.addEventListener(`abort`,o,{once:!0}),e.then(e=>{if(t.removeEventListener(`abort`,o),a)try{n?.(e)}catch{}else r(e)},e=>{t.removeEventListener(`abort`,o),a||i(e)})})}function S(e){let t=e.limits?.operationTimeoutMs??l.operationTimeoutMs;if(!Number.isSafeInteger(t)||t<0||t>2147483647)throw Error(`[PipeX] Invalid KMS provider timeout`);if(t===0)return{signal:e.signal,cleanup(){}};let n=new AbortController,r=setTimeout(()=>{n.abort(new DOMException(`KMS provider operation timed out`,`TimeoutError`))},t);return{signal:e.signal?AbortSignal.any([e.signal,n.signal]):n.signal,cleanup(){clearTimeout(r)}}}function C(t,i){return i instanceof n||i instanceof e?i:i instanceof s?new s(t):i instanceof r?new r(t):new a(t)}async function w(e,t,n,r,i){v(e,t);let a=S(n);try{if(a.signal?.aborted)throw b(a.signal);return await x(r(a.signal),a.signal,i)}catch(e){throw a.signal?.aborted?b(a.signal):C(t,e)}finally{a.cleanup()}}var T=class extends i{name=`kms-encryption`;version=`2.1.0`;streaming=!1;get providerCapabilities(){return g(this.options.kms)}get reversible(){return this.providerCapabilities.decrypt}constructor(e){if(super(e),this.options=e,!e||!e.kms||typeof e.keyId!=`string`||e.keyId.length===0)throw Error(`[PipeX] KMS Encryption: invalid provider or keyId`);if(e.allowLegacyDecrypt!==void 0&&typeof e.allowLegacyDecrypt!=`boolean`)throw Error(`[PipeX] KMS Encryption allowLegacyDecrypt must be a boolean`);g(e.kms),v(e.kms,`generateDataKey`)}async process(e,t){let n=o(t),r=c(t),i=t.limits?.maxKmsEncryptedKeyBytes??l.maxKmsEncryptedKeyBytes,a=t.limits?.maxKmsKeyIdBytes??l.maxKmsKeyIdBytes;if(Buffer.byteLength(this.options.keyId)>a)throw Error(`[PipeX] KMS key identifier exceeds the configured limit`);if(e.length>n)throw Error(`[PipeX] KMS encryption input exceeds ${n} bytes`);if(e.length>4294967295)throw Error(`[PipeX] KMS encryption input exceeds the format limit`);if(e.length>r-45)throw Error(`[PipeX] KMS encryption output exceeds ${r} bytes`);let{kms:s,keyId:u}=this.options,d=await w(s,`generateDataKey`,t,e=>s.generateDataKey(u,{signal:e}),e=>{Buffer.isBuffer(e?.plaintext)&&e.plaintext.fill(0)}),p=d?.plaintext;try{let t=d?.ciphertext;if(!Buffer.isBuffer(p)||p.length!==32)throw Error(`[PipeX] KMS generated an invalid data key`);if(!Buffer.isBuffer(t)||t.length<1||t.length>i)throw Error(`[PipeX] KMS generated an invalid encrypted key`);let n=28+t.length+16;if(e.length>r-n)throw Error(`[PipeX] KMS encryption output exceeds ${r} bytes`);let a=n+e.length,o=m(12),s=f(`aes-256-gcm`,p,o,{authTagLength:16}),c=Buffer.alloc(28);y.copy(c,0),c.writeUInt8(1,4),c.writeUInt8(1,5),c.writeUInt16BE(0,6),c.writeUInt32BE(t.length,8),c.writeUInt32BE(e.length,12),o.copy(c,16),s.setAAD(Buffer.concat([c,t]));let l=Buffer.concat([s.update(e),s.final()]),u=s.getAuthTag();return Buffer.concat([c,t,l,u],a)}finally{Buffer.isBuffer(p)&&p.fill(0)}}async reverse(e,n){let{kms:r,keyId:i}=this.options;v(r,`decrypt`);let a=o(n),s=c(n),u=n.limits?.maxKmsEncryptedKeyBytes??l.maxKmsEncryptedKeyBytes,d=n.limits?.maxKmsKeyIdBytes??l.maxKmsKeyIdBytes;if(Buffer.byteLength(i)>d)throw Error(`[PipeX] KMS key identifier exceeds the configured limit`);if(e.length>a)throw Error(`[PipeX] KMS decryption input exceeds ${a} bytes`);if(e.length===0)throw Error(`[PipeX] KMS Decryption: Packet too short`);let f=e.length>=y.length&&e.subarray(0,y.length).equals(y);if(!f&&e.readUInt8(0)===y.readUInt8(0))throw Error(`[PipeX] KMS Decryption: incomplete framed header`);if(!f&&this.options.allowLegacyDecrypt!==!0)throw Error(`[PipeX] KMS Decryption: legacy format disabled`);let m,h,g,_,b;if(f){if(e.length<45)throw Error(`[PipeX] KMS Decryption: incomplete framed envelope`);if(e.readUInt8(4)!==1)throw Error(`[PipeX] KMS Decryption: unsupported format version`);if(e.readUInt8(5)!==1||e.readUInt16BE(6)!==0)throw Error(`[PipeX] KMS Decryption: invalid framed envelope`);let t=e.readUInt32BE(8),n=e.readUInt32BE(12);if(t<1||t>u)throw Error(`[PipeX] KMS Decryption: invalid key envelope`);if(28+t+n+16!==e.length)throw Error(`[PipeX] KMS Decryption: invalid envelope length`);if(n>s)throw Error(`[PipeX] KMS decryption output exceeds ${s} bytes`);h=e.subarray(16,28),m=e.subarray(28,28+t),_=e.subarray(28+t,e.length-16),g=e.subarray(e.length-16),b=e.subarray(0,28+t)}else{if(e.length<4)throw Error(`[PipeX] KMS Decryption: Packet too short`);let t=e.readUInt32BE(0);if(t<1||t>u||e.length<4+t+12+16)throw Error(`[PipeX] KMS Decryption: invalid key envelope`);m=e.subarray(4,4+t),h=e.subarray(4+t,4+t+12),g=e.subarray(4+t+12,4+t+12+16),_=e.subarray(4+t+12+16)}if(_.length>s)throw Error(`[PipeX] KMS decryption output exceeds ${s} bytes`);let x=await w(r,`decrypt`,n,e=>r.decrypt(m,i,{signal:e}),e=>{Buffer.isBuffer(e)&&e.fill(0)});try{if(!Buffer.isBuffer(x)||x.length!==32)throw Error(`[PipeX] KMS Decryption: invalid data key length`);let e=p(`aes-256-gcm`,x,h,{authTagLength:16});b&&e.setAAD(b),e.setAuthTag(g);let n=e.update(_);try{let t=e.final();return t.length===0?n:Buffer.concat([n,t])}catch{throw n.fill(0),new t}}finally{Buffer.isBuffer(x)&&x.fill(0)}}};export{g as n,_ as r,T as t};
@@ -0,0 +1 @@
1
+ require(`./core-B_z1gN5W.cjs`);const e=require(`./resourceLimits-CI0Qrqdf.cjs`);let t=require(`node:crypto`);const n=[`encrypt`,`decrypt`,`generateDataKey`];function r(t){if(!t||typeof t!=`object`)throw TypeError(`[PipeX] Invalid KMS provider`);if(t.capabilities!==void 0&&(!t.capabilities||typeof t.capabilities!=`object`))throw TypeError(`[PipeX] Invalid KMS provider capabilities`);let r={};for(let i of n){let n=t.capabilities?.[i],a=typeof t[i]==`function`;if(n!==void 0&&typeof n!=`boolean`)throw new e.u(i,`MUST_BE_BOOLEAN`);if(n===!0&&!a)throw new e.u(i,`MISSING_IMPLEMENTATION`);r[i]=n??a}return Object.freeze(r)}function i(e,t){if(!n.includes(t))throw TypeError(`[PipeX] Unknown KMS operation`);return r(e)[t]}function a(t,n){if(!i(t,n))throw new e.x(n)}const o=Buffer.from(`PXKM`);function s(t){let n={cause:t.reason};return t.reason instanceof Error&&t.reason.name===`TimeoutError`?new e._(n):new e.g(n)}async function c(e,t,n){if(!t)return e;if(t.aborted)throw e.then(e=>{try{n?.(e)}catch{}},()=>void 0),s(t);return new Promise((r,i)=>{let a=!1,o=()=>{a=!0,i(s(t))};t.addEventListener(`abort`,o,{once:!0}),e.then(e=>{if(t.removeEventListener(`abort`,o),a)try{n?.(e)}catch{}else r(e)},e=>{t.removeEventListener(`abort`,o),a||i(e)})})}function l(t){let n=t.limits?.operationTimeoutMs??e.t.operationTimeoutMs;if(!Number.isSafeInteger(n)||n<0||n>2147483647)throw Error(`[PipeX] Invalid KMS provider timeout`);if(n===0)return{signal:t.signal,cleanup(){}};let r=new AbortController,i=setTimeout(()=>{r.abort(new DOMException(`KMS provider operation timed out`,`TimeoutError`))},n);return{signal:t.signal?AbortSignal.any([t.signal,r.signal]):r.signal,cleanup(){clearTimeout(i)}}}function u(t,n){return n instanceof e.g||n instanceof e._?n:n instanceof e.p?new e.p(t):n instanceof e.h?new e.h(t):new e.m(t)}async function d(e,t,n,r,i){a(e,t);let o=l(n);try{if(o.signal?.aborted)throw s(o.signal);return await c(r(o.signal),o.signal,i)}catch(e){throw o.signal?.aborted?s(o.signal):u(t,e)}finally{o.cleanup()}}var f=class extends e.i{name=`kms-encryption`;version=`2.1.0`;streaming=!1;get providerCapabilities(){return r(this.options.kms)}get reversible(){return this.providerCapabilities.decrypt}constructor(e){if(super(e),this.options=e,!e||!e.kms||typeof e.keyId!=`string`||e.keyId.length===0)throw Error(`[PipeX] KMS Encryption: invalid provider or keyId`);if(e.allowLegacyDecrypt!==void 0&&typeof e.allowLegacyDecrypt!=`boolean`)throw Error(`[PipeX] KMS Encryption allowLegacyDecrypt must be a boolean`);r(e.kms),a(e.kms,`generateDataKey`)}async process(n,r){let i=e.n(r),a=e.r(r),s=r.limits?.maxKmsEncryptedKeyBytes??e.t.maxKmsEncryptedKeyBytes,c=r.limits?.maxKmsKeyIdBytes??e.t.maxKmsKeyIdBytes;if(Buffer.byteLength(this.options.keyId)>c)throw Error(`[PipeX] KMS key identifier exceeds the configured limit`);if(n.length>i)throw Error(`[PipeX] KMS encryption input exceeds ${i} bytes`);if(n.length>4294967295)throw Error(`[PipeX] KMS encryption input exceeds the format limit`);if(n.length>a-45)throw Error(`[PipeX] KMS encryption output exceeds ${a} bytes`);let{kms:l,keyId:u}=this.options,f=await d(l,`generateDataKey`,r,e=>l.generateDataKey(u,{signal:e}),e=>{Buffer.isBuffer(e?.plaintext)&&e.plaintext.fill(0)}),p=f?.plaintext;try{let e=f?.ciphertext;if(!Buffer.isBuffer(p)||p.length!==32)throw Error(`[PipeX] KMS generated an invalid data key`);if(!Buffer.isBuffer(e)||e.length<1||e.length>s)throw Error(`[PipeX] KMS generated an invalid encrypted key`);let r=28+e.length+16;if(n.length>a-r)throw Error(`[PipeX] KMS encryption output exceeds ${a} bytes`);let i=r+n.length,c=(0,t.randomBytes)(12),l=(0,t.createCipheriv)(`aes-256-gcm`,p,c,{authTagLength:16}),u=Buffer.alloc(28);o.copy(u,0),u.writeUInt8(1,4),u.writeUInt8(1,5),u.writeUInt16BE(0,6),u.writeUInt32BE(e.length,8),u.writeUInt32BE(n.length,12),c.copy(u,16),l.setAAD(Buffer.concat([u,e]));let d=Buffer.concat([l.update(n),l.final()]),m=l.getAuthTag();return Buffer.concat([u,e,d,m],i)}finally{Buffer.isBuffer(p)&&p.fill(0)}}async reverse(n,r){let{kms:i,keyId:s}=this.options;a(i,`decrypt`);let c=e.n(r),l=e.r(r),u=r.limits?.maxKmsEncryptedKeyBytes??e.t.maxKmsEncryptedKeyBytes,f=r.limits?.maxKmsKeyIdBytes??e.t.maxKmsKeyIdBytes;if(Buffer.byteLength(s)>f)throw Error(`[PipeX] KMS key identifier exceeds the configured limit`);if(n.length>c)throw Error(`[PipeX] KMS decryption input exceeds ${c} bytes`);if(n.length===0)throw Error(`[PipeX] KMS Decryption: Packet too short`);let p=n.length>=o.length&&n.subarray(0,o.length).equals(o);if(!p&&n.readUInt8(0)===o.readUInt8(0))throw Error(`[PipeX] KMS Decryption: incomplete framed header`);if(!p&&this.options.allowLegacyDecrypt!==!0)throw Error(`[PipeX] KMS Decryption: legacy format disabled`);let m,h,g,_,v;if(p){if(n.length<45)throw Error(`[PipeX] KMS Decryption: incomplete framed envelope`);if(n.readUInt8(4)!==1)throw Error(`[PipeX] KMS Decryption: unsupported format version`);if(n.readUInt8(5)!==1||n.readUInt16BE(6)!==0)throw Error(`[PipeX] KMS Decryption: invalid framed envelope`);let e=n.readUInt32BE(8),t=n.readUInt32BE(12);if(e<1||e>u)throw Error(`[PipeX] KMS Decryption: invalid key envelope`);if(28+e+t+16!==n.length)throw Error(`[PipeX] KMS Decryption: invalid envelope length`);if(t>l)throw Error(`[PipeX] KMS decryption output exceeds ${l} bytes`);h=n.subarray(16,28),m=n.subarray(28,28+e),_=n.subarray(28+e,n.length-16),g=n.subarray(n.length-16),v=n.subarray(0,28+e)}else{if(n.length<4)throw Error(`[PipeX] KMS Decryption: Packet too short`);let e=n.readUInt32BE(0);if(e<1||e>u||n.length<4+e+12+16)throw Error(`[PipeX] KMS Decryption: invalid key envelope`);m=n.subarray(4,4+e),h=n.subarray(4+e,4+e+12),g=n.subarray(4+e+12,4+e+12+16),_=n.subarray(4+e+12+16)}if(_.length>l)throw Error(`[PipeX] KMS decryption output exceeds ${l} bytes`);let y=await d(i,`decrypt`,r,e=>i.decrypt(m,s,{signal:e}),e=>{Buffer.isBuffer(e)&&e.fill(0)});try{if(!Buffer.isBuffer(y)||y.length!==32)throw Error(`[PipeX] KMS Decryption: invalid data key length`);let n=(0,t.createDecipheriv)(`aes-256-gcm`,y,h,{authTagLength:16});v&&n.setAAD(v),n.setAuthTag(g);let r=n.update(_);try{let e=n.final();return e.length===0?r:Buffer.concat([r,e])}catch{throw r.fill(0),new e.f}}finally{Buffer.isBuffer(y)&&y.fill(0)}}};Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return f}});
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./dataEngine-Bvl6amzP.cjs`);exports.DataEngine=e.t;
@@ -0,0 +1,2 @@
1
+ import { t as DataEngine } from "./dataEngine-D-fIXgE7.cjs";
2
+ export { DataEngine };
@@ -0,0 +1,2 @@
1
+ import { t as DataEngine } from "./dataEngine-DUEmWp7a.mjs";
2
+ export { DataEngine };
@@ -0,0 +1 @@
1
+ import{t as e}from"./dataEngine-4m6GTOLe.mjs";export{e as DataEngine};
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./worker-I_kqxWeK.cjs`);exports.WorkerPoolPlugin=e.t;
@@ -0,0 +1,2 @@
1
+ import { n as WorkerPoolPlugin, t as WorkerPoolOptions } from "./worker-CbuCpSNc.cjs";
2
+ export { type WorkerPoolOptions, WorkerPoolPlugin };
@@ -0,0 +1,2 @@
1
+ import { n as WorkerPoolPlugin, t as WorkerPoolOptions } from "./worker-CgCC-BWG.mjs";
2
+ export { type WorkerPoolOptions, WorkerPoolPlugin };
@@ -0,0 +1 @@
1
+ import{t as e}from"./worker-c0_VZ9c7.mjs";export{e as WorkerPoolPlugin};
@@ -0,0 +1,16 @@
1
+ import { _ as ProcessorContext, b as RetryOptions, v as ProcessorPlugin } from "./types-ia4x-Dvp.cjs";
2
+
3
+ //#region src/core/plugin.d.ts
4
+ declare abstract class BasePlugin implements ProcessorPlugin {
5
+ protected options: object;
6
+ abstract readonly name: string;
7
+ abstract readonly version: string;
8
+ retryOptions?: RetryOptions;
9
+ get reversible(): boolean;
10
+ constructor(options?: object);
11
+ abstract process(data: Buffer, context: ProcessorContext): Promise<Buffer> | Buffer;
12
+ /** Unsupported by default. Subclasses must implement reverse explicitly. */
13
+ reverse(_data: Buffer, _context: ProcessorContext): Promise<Buffer> | Buffer;
14
+ }
15
+ //#endregion
16
+ export { BasePlugin as t };
@@ -0,0 +1,16 @@
1
+ import { _ as ProcessorContext, b as RetryOptions, v as ProcessorPlugin } from "./types-Bytga6zd.mjs";
2
+
3
+ //#region src/core/plugin.d.ts
4
+ declare abstract class BasePlugin implements ProcessorPlugin {
5
+ protected options: object;
6
+ abstract readonly name: string;
7
+ abstract readonly version: string;
8
+ retryOptions?: RetryOptions;
9
+ get reversible(): boolean;
10
+ constructor(options?: object);
11
+ abstract process(data: Buffer, context: ProcessorContext): Promise<Buffer> | Buffer;
12
+ /** Unsupported by default. Subclasses must implement reverse explicitly. */
13
+ reverse(_data: Buffer, _context: ProcessorContext): Promise<Buffer> | Buffer;
14
+ }
15
+ //#endregion
16
+ export { BasePlugin as t };
@@ -0,0 +1 @@
1
+ var e=class extends Error{name=`PipeXError`;transformName;stage;constructor(e,t,n){super(t,n),this.code=e,this.transformName=n?.transformName,this.stage=n?.stage}},t=class extends e{name=`ValidationError`;constructor(e){super(`VALIDATION_FAILED`,`[PipeX] Validation failed`,e)}},n=class extends e{name=`CompressionError`;constructor(e){super(`COMPRESSION_FAILED`,`[PipeX] Compression failed`,e)}},r=class extends e{name=`HashingError`;constructor(e){super(`HASHING_FAILED`,`[PipeX] Hashing failed`,e)}},i=class extends e{name=`UnsupportedAlgorithmError`;constructor(e){super(`UNSUPPORTED_ALGORITHM`,`[PipeX] Unsupported algorithm`,e)}},a=class extends e{name=`PipelineAbortedError`;constructor(e){super(`OPERATION_ABORTED`,`[PipeX] Operation aborted`,e)}},o=class extends e{name=`UnsupportedReverseError`;constructor(e){super(`UNSUPPORTED_REVERSE`,`[PipeX] Plugin ${e} does not support reverse operations`),this.plugin=e}},s=class extends e{name=`UnsupportedStreamingError`;constructor(e){super(`UNSUPPORTED_STREAMING`,`[PipeX] Plugin ${e} does not support stream operations`),this.plugin=e}},c=class extends e{name=`InvalidPluginCapabilityError`;constructor(e,t,n){super(`INVALID_PLUGIN_CAPABILITY`,`[PipeX] Plugin ${e} has an invalid ${t} capability: ${n===`MUST_BE_BOOLEAN`?`must be a boolean when declared`:n===`MISSING_IMPLEMENTATION`?`is declared but its implementation is missing`:`is disabled but its implementation is present`}`),this.plugin=e,this.capability=t,this.issue=n}},l=class extends a{name=`OperationAbortedError`;constructor(e){super(e)}},u=class extends e{name=`OperationTimeoutError`;constructor(e){super(`OPERATION_TIMEOUT`,`[PipeX] Operation timed out`,e)}},d=class extends e{name=`KmsProviderError`;constructor(e,t){super(`KMS_PROVIDER_FAILURE`,`[PipeX] KMS ${e} failed`,t),this.operation=e}},f=class extends e{name=`KmsAuthenticationError`;constructor(){super(`KMS_AUTHENTICATION_FAILED`,`[PipeX] KMS envelope authentication failed`)}},p=class extends e{name=`KmsProviderAuthenticationError`;constructor(e){super(`KMS_PROVIDER_AUTHENTICATION_FAILED`,`[PipeX] KMS ${e} authentication failed`),this.operation=e}},m=class extends e{name=`KmsProviderUnavailableError`;constructor(e){super(`KMS_PROVIDER_UNAVAILABLE`,`[PipeX] KMS ${e} provider unavailable`),this.operation=e}},h=class extends e{name=`UnsupportedKmsOperationError`;constructor(e){super(`UNSUPPORTED_KMS_OPERATION`,`[PipeX] KMS provider does not support ${e}`),this.operation=e}},g=class extends e{name=`InvalidKmsProviderCapabilityError`;constructor(e,t){super(`INVALID_KMS_PROVIDER_CAPABILITY`,`[PipeX] Invalid KMS ${e} capability: ${t===`MUST_BE_BOOLEAN`?`must be a boolean when declared`:`is declared but its implementation is missing`}`),this.operation=e,this.issue=t}},_=class extends e{name=`WorkerPoolClosedError`;constructor(){super(`WORKER_POOL_CLOSED`,`[PipeX] Worker pool is closed`)}},v=class extends e{name=`WorkerQueueFullError`;constructor(e){super(`WORKER_QUEUE_FULL`,`[PipeX] Worker queue is full (maximum ${e} waiting tasks)`),this.maxQueue=e}},y=class extends e{name=`WorkerPoolCloseError`;constructor(e){super(`WORKER_POOL_CLOSE_FAILURE`,`[PipeX] Worker pool failed to close cleanly`,e)}},b=class extends e{name=`WorkerTaskError`;constructor(e,t){super(`WORKER_TASK_FAILURE`,`[PipeX] Worker task ${e} failed`,t),this.taskName=e}},x=class extends e{name=`EncryptionError`;constructor(e=`[PipeX] Encryption operation failed`){super(`ENCRYPTION_ERROR`,e)}},S=class extends e{name=`InvalidKeyError`;constructor(){super(`INVALID_ENCRYPTION_KEY`,`[PipeX] Encryption key must be a 32-byte Buffer`)}},C=class extends e{name=`AuthenticationError`;constructor(){super(`ENCRYPTION_AUTHENTICATION_FAILED`,`[PipeX] Encrypted data authentication failed`)}},w=class e{retryOptions;get reversible(){return this.reverse!==e.prototype.reverse}constructor(e={}){this.options=e}reverse(e,t){throw new o(`${this.name}@${this.version}`)}};const T=Object.freeze({maxInputBytes:64*1024*1024,maxOutputBytes:256*1024*1024,maxFrameBytes:8*1024*1024,maxFrames:1e5,maxConcurrentOperations:32,operationTimeoutMs:5*6e4,maxRetryAttempts:5,maxRetryDelayMs:3e4,maxKmsEncryptedKeyBytes:64*1024,maxKmsKeyIdBytes:512});function E(e){let t=e?.limits??T;return Math.max(t.maxInputBytes,t.maxOutputBytes)}function D(e){return e?.limits?.maxOutputBytes??T.maxOutputBytes}export{s as C,v as D,_ as E,b as O,o as S,y as T,u as _,C as a,i as b,r as c,c as d,f,l as g,m as h,w as i,S as l,d as m,E as n,n as o,p,D as r,x as s,T as t,g as u,e as v,t as w,h as x,a as y};
@@ -0,0 +1 @@
1
+ var e=class extends Error{name=`PipeXError`;transformName;stage;constructor(e,t,n){super(t,n),this.code=e,this.transformName=n?.transformName,this.stage=n?.stage}},t=class extends e{name=`ValidationError`;constructor(e){super(`VALIDATION_FAILED`,`[PipeX] Validation failed`,e)}},n=class extends e{name=`CompressionError`;constructor(e){super(`COMPRESSION_FAILED`,`[PipeX] Compression failed`,e)}},r=class extends e{name=`HashingError`;constructor(e){super(`HASHING_FAILED`,`[PipeX] Hashing failed`,e)}},i=class extends e{name=`UnsupportedAlgorithmError`;constructor(e){super(`UNSUPPORTED_ALGORITHM`,`[PipeX] Unsupported algorithm`,e)}},a=class extends e{name=`PipelineAbortedError`;constructor(e){super(`OPERATION_ABORTED`,`[PipeX] Operation aborted`,e)}},o=class extends e{name=`UnsupportedReverseError`;constructor(e){super(`UNSUPPORTED_REVERSE`,`[PipeX] Plugin ${e} does not support reverse operations`),this.plugin=e}},s=class extends e{name=`UnsupportedStreamingError`;constructor(e){super(`UNSUPPORTED_STREAMING`,`[PipeX] Plugin ${e} does not support stream operations`),this.plugin=e}},c=class extends e{name=`InvalidPluginCapabilityError`;constructor(e,t,n){super(`INVALID_PLUGIN_CAPABILITY`,`[PipeX] Plugin ${e} has an invalid ${t} capability: ${n===`MUST_BE_BOOLEAN`?`must be a boolean when declared`:n===`MISSING_IMPLEMENTATION`?`is declared but its implementation is missing`:`is disabled but its implementation is present`}`),this.plugin=e,this.capability=t,this.issue=n}},l=class extends a{name=`OperationAbortedError`;constructor(e){super(e)}},u=class extends e{name=`OperationTimeoutError`;constructor(e){super(`OPERATION_TIMEOUT`,`[PipeX] Operation timed out`,e)}},d=class extends e{name=`KmsProviderError`;constructor(e,t){super(`KMS_PROVIDER_FAILURE`,`[PipeX] KMS ${e} failed`,t),this.operation=e}},f=class extends e{name=`KmsAuthenticationError`;constructor(){super(`KMS_AUTHENTICATION_FAILED`,`[PipeX] KMS envelope authentication failed`)}},p=class extends e{name=`KmsProviderAuthenticationError`;constructor(e){super(`KMS_PROVIDER_AUTHENTICATION_FAILED`,`[PipeX] KMS ${e} authentication failed`),this.operation=e}},m=class extends e{name=`KmsProviderUnavailableError`;constructor(e){super(`KMS_PROVIDER_UNAVAILABLE`,`[PipeX] KMS ${e} provider unavailable`),this.operation=e}},h=class extends e{name=`UnsupportedKmsOperationError`;constructor(e){super(`UNSUPPORTED_KMS_OPERATION`,`[PipeX] KMS provider does not support ${e}`),this.operation=e}},g=class extends e{name=`InvalidKmsProviderCapabilityError`;constructor(e,t){super(`INVALID_KMS_PROVIDER_CAPABILITY`,`[PipeX] Invalid KMS ${e} capability: ${t===`MUST_BE_BOOLEAN`?`must be a boolean when declared`:`is declared but its implementation is missing`}`),this.operation=e,this.issue=t}},_=class extends e{name=`WorkerPoolClosedError`;constructor(){super(`WORKER_POOL_CLOSED`,`[PipeX] Worker pool is closed`)}},v=class extends e{name=`WorkerQueueFullError`;constructor(e){super(`WORKER_QUEUE_FULL`,`[PipeX] Worker queue is full (maximum ${e} waiting tasks)`),this.maxQueue=e}},y=class extends e{name=`WorkerPoolCloseError`;constructor(e){super(`WORKER_POOL_CLOSE_FAILURE`,`[PipeX] Worker pool failed to close cleanly`,e)}},b=class extends e{name=`WorkerTaskError`;constructor(e,t){super(`WORKER_TASK_FAILURE`,`[PipeX] Worker task ${e} failed`,t),this.taskName=e}},x=class extends e{name=`EncryptionError`;constructor(e=`[PipeX] Encryption operation failed`){super(`ENCRYPTION_ERROR`,e)}},S=class extends e{name=`InvalidKeyError`;constructor(){super(`INVALID_ENCRYPTION_KEY`,`[PipeX] Encryption key must be a 32-byte Buffer`)}},C=class extends e{name=`AuthenticationError`;constructor(){super(`ENCRYPTION_AUTHENTICATION_FAILED`,`[PipeX] Encrypted data authentication failed`)}},w=class e{retryOptions;get reversible(){return this.reverse!==e.prototype.reverse}constructor(e={}){this.options=e}reverse(e,t){throw new o(`${this.name}@${this.version}`)}};const T=Object.freeze({maxInputBytes:64*1024*1024,maxOutputBytes:256*1024*1024,maxFrameBytes:8*1024*1024,maxFrames:1e5,maxConcurrentOperations:32,operationTimeoutMs:5*6e4,maxRetryAttempts:5,maxRetryDelayMs:3e4,maxKmsEncryptedKeyBytes:64*1024,maxKmsKeyIdBytes:512});function E(e){let t=e?.limits??T;return Math.max(t.maxInputBytes,t.maxOutputBytes)}function D(e){return e?.limits?.maxOutputBytes??T.maxOutputBytes}Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return a}});
@@ -0,0 +1,155 @@
1
+ import { Duplex, Writable } from "node:stream";
2
+ import { z } from "zod";
3
+
4
+ //#region src/core/types.d.ts
5
+ interface Logger {
6
+ info(message: string, context?: Record<string, unknown>): void;
7
+ warn(message: string, context?: Record<string, unknown>): void;
8
+ error(message: string, context?: Record<string, unknown>): void;
9
+ debug(message: string, context?: Record<string, unknown>): void;
10
+ }
11
+ interface Span {
12
+ setAttribute(key: string, value: unknown): this;
13
+ addEvent(name: string, attributes?: Record<string, unknown>): this;
14
+ end(): void;
15
+ }
16
+ interface Tracer {
17
+ startSpan(name: string, context?: ProcessorContext): Span;
18
+ }
19
+ interface RetryOptions {
20
+ attempts: number;
21
+ backoff: 'exponential' | 'fixed';
22
+ delayMs: number;
23
+ }
24
+ interface EngineLimits {
25
+ maxInputBytes: number;
26
+ maxOutputBytes: number;
27
+ maxFrameBytes: number;
28
+ maxFrames: number;
29
+ maxConcurrentOperations: number;
30
+ operationTimeoutMs: number;
31
+ maxRetryAttempts: number;
32
+ maxRetryDelayMs: number;
33
+ /** Maximum provider-wrapped data-key bytes accepted in a KMS envelope. */
34
+ maxKmsEncryptedKeyBytes: number;
35
+ /** Maximum UTF-8 bytes accepted for a provider key identifier. */
36
+ maxKmsKeyIdBytes: number;
37
+ }
38
+ interface OperationOptions {
39
+ signal?: AbortSignal;
40
+ timeoutMs?: number;
41
+ }
42
+ /** expectedType must come from trusted application configuration, never the received result. */
43
+ interface BinaryUndoOptions extends OperationOptions {
44
+ expectedType?: string;
45
+ }
46
+ interface StreamPluginContext {
47
+ /** Engine-owned accounting for work that continues after cancellation. */
48
+ readonly track?: (pending: Promise<unknown>) => void;
49
+ readonly requestId: string;
50
+ readonly signal: AbortSignal;
51
+ readonly limits: Readonly<EngineLimits>;
52
+ readonly logger?: Logger;
53
+ readonly tracer?: Tracer;
54
+ }
55
+ interface AuditRecord {
56
+ requestId: string;
57
+ operation: 'pack' | 'unpack' | 'process' | 'reverse';
58
+ pluginChain: string[];
59
+ timestamp: number;
60
+ metadata: Record<string, unknown>;
61
+ }
62
+ interface AuditLogger {
63
+ log(record: AuditRecord): void | Promise<void>;
64
+ }
65
+ type KmsOperation = 'encrypt' | 'decrypt' | 'generateDataKey';
66
+ interface KmsProviderCapabilities {
67
+ readonly encrypt: boolean;
68
+ readonly decrypt: boolean;
69
+ readonly generateDataKey: boolean;
70
+ }
71
+ interface KmsProvider {
72
+ /** Explicit false disables an operation even when a compatibility stub exists. */
73
+ readonly capabilities?: Partial<KmsProviderCapabilities>;
74
+ encrypt?(data: Buffer, keyId: string, options?: KmsRequestOptions): Promise<Buffer>;
75
+ decrypt?(data: Buffer, keyId: string, options?: KmsRequestOptions): Promise<Buffer>;
76
+ generateDataKey?(keyId: string, options?: KmsRequestOptions): Promise<{
77
+ plaintext: Buffer;
78
+ ciphertext: Buffer;
79
+ }>;
80
+ }
81
+ interface KmsRequestOptions {
82
+ signal?: AbortSignal;
83
+ }
84
+ interface SchemaRegistry {
85
+ getSchema(subject: string, version?: number): Promise<z.ZodType<any>>;
86
+ }
87
+ interface EngineConfig {
88
+ plugins?: {
89
+ name: string;
90
+ options?: unknown;
91
+ }[];
92
+ limits?: Partial<EngineLimits>;
93
+ logger?: Logger;
94
+ tracer?: Tracer;
95
+ auditLogger?: AuditLogger;
96
+ /** Optional caller-owned failure sink; `dlq` is retained for compatibility. */
97
+ dlq?: Writable;
98
+ schema?: z.ZodType<any>;
99
+ schemaRegistry?: SchemaRegistry;
100
+ }
101
+ interface ProcessorContext {
102
+ readonly requestId: string;
103
+ readonly timestamp: number;
104
+ readonly signal?: AbortSignal;
105
+ readonly limits?: Readonly<EngineLimits>;
106
+ metadata: Record<string, unknown>;
107
+ logger?: Logger;
108
+ span?: Span;
109
+ }
110
+ interface ProcessorPlugin {
111
+ readonly name: string;
112
+ readonly version: string;
113
+ readonly reversible?: boolean;
114
+ readonly streaming?: boolean;
115
+ process(data: Buffer, ctx: ProcessorContext): Promise<Buffer> | Buffer;
116
+ reverse?(data: Buffer, ctx: ProcessorContext): Promise<Buffer> | Buffer;
117
+ createStream?(mode: 'compress' | 'decompress', context?: StreamPluginContext): Duplex;
118
+ retryOptions?: RetryOptions;
119
+ }
120
+ type PluginOperation = 'process' | 'reverse' | 'stream';
121
+ /** Normalized, runtime-validated operations exposed by a plugin. */
122
+ interface PluginCapabilities {
123
+ readonly process: true;
124
+ readonly reverse: boolean;
125
+ readonly streaming: boolean;
126
+ readonly streamMode: 'native' | 'fallback' | 'none';
127
+ }
128
+ /** Capability view for a plugin registered with a DataEngine. */
129
+ interface RegisteredPluginCapabilities extends PluginCapabilities {
130
+ readonly plugin: string;
131
+ }
132
+ interface EngineResult {
133
+ readonly data: Buffer;
134
+ readonly originalType: string;
135
+ readonly pipeline: string[];
136
+ readonly metrics: {
137
+ durationMs: number;
138
+ steps: Record<string, number>;
139
+ };
140
+ }
141
+ interface PipeXManifest {
142
+ readonly __pipex_v: 1;
143
+ readonly plugins: string[];
144
+ readonly ts: number;
145
+ }
146
+ declare function isManifest(value: unknown): value is PipeXManifest;
147
+ interface EngineEvents {
148
+ start: [requestId: string];
149
+ 'plugin:after': [name: string, durationMs: number];
150
+ progress: [bytes: number, requestId: string];
151
+ error: [err: Error, requestId: string];
152
+ end: [requestId: string, durationMs: number];
153
+ }
154
+ //#endregion
155
+ export { StreamPluginContext as C, Span as S, isManifest as T, ProcessorContext as _, EngineEvents as a, RetryOptions as b, KmsOperation as c, KmsRequestOptions as d, Logger as f, PluginOperation as g, PluginCapabilities as h, EngineConfig as i, KmsProvider as l, PipeXManifest as m, AuditRecord as n, EngineLimits as o, OperationOptions as p, BinaryUndoOptions as r, EngineResult as s, AuditLogger as t, KmsProviderCapabilities as u, ProcessorPlugin as v, Tracer as w, SchemaRegistry as x, RegisteredPluginCapabilities as y };