@uploadista/core 0.1.3 → 0.2.0

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 (89) hide show
  1. package/dist/checksum-B7RDiO7V.cjs +1 -0
  2. package/dist/{checksum-_-9dR9Qp.mjs → checksum-BjP9nb5b.mjs} +1 -1
  3. package/dist/{checksum-_-9dR9Qp.mjs.map → checksum-BjP9nb5b.mjs.map} +1 -1
  4. package/dist/errors/index.cjs +1 -1
  5. package/dist/errors/index.d.mts +1 -2
  6. package/dist/errors/index.mjs +1 -1
  7. package/dist/flow/index.cjs +1 -1
  8. package/dist/flow/index.d.cts +2 -2
  9. package/dist/flow/index.d.mts +5 -6
  10. package/dist/flow/index.mjs +1 -1
  11. package/dist/index.cjs +1 -1
  12. package/dist/index.d.cts +4 -4
  13. package/dist/index.d.mts +11 -6
  14. package/dist/index.mjs +1 -1
  15. package/dist/{index-DWslhr-b.d.cts → resolve-upload-metadata-BUVl1LoS.d.cts} +35 -8
  16. package/dist/resolve-upload-metadata-BUVl1LoS.d.cts.map +1 -0
  17. package/dist/{index-fXTlZ4bM.d.mts → resolve-upload-metadata-MPDmDfOZ.d.mts} +36 -9
  18. package/dist/resolve-upload-metadata-MPDmDfOZ.d.mts.map +1 -0
  19. package/dist/run-args-WD1otVrz.mjs +2 -0
  20. package/dist/run-args-WD1otVrz.mjs.map +1 -0
  21. package/dist/run-args-g74p8pEZ.cjs +1 -0
  22. package/dist/{index-CvOB2TdS.d.cts → stream-limiter-BCFULdAM.d.cts} +1 -1
  23. package/dist/stream-limiter-BCFULdAM.d.cts.map +1 -0
  24. package/dist/{index-DI82_KcP.d.mts → stream-limiter-Bi7OTbRp.d.mts} +2 -2
  25. package/dist/stream-limiter-Bi7OTbRp.d.mts.map +1 -0
  26. package/dist/{stream-limiter-B6AseoKZ.mjs → stream-limiter-CTJPEJqE.mjs} +1 -1
  27. package/dist/{stream-limiter-B6AseoKZ.mjs.map → stream-limiter-CTJPEJqE.mjs.map} +1 -1
  28. package/dist/stream-limiter-DZ22uIqf.cjs +1 -0
  29. package/dist/streams/index.cjs +1 -1
  30. package/dist/streams/index.d.cts +1 -1
  31. package/dist/streams/index.d.mts +2 -2
  32. package/dist/streams/index.mjs +1 -1
  33. package/dist/testing/index.cjs +1 -1
  34. package/dist/testing/index.d.cts +1 -1
  35. package/dist/testing/index.d.mts +6 -5
  36. package/dist/testing/index.d.mts.map +1 -1
  37. package/dist/testing/index.mjs +1 -1
  38. package/dist/testing/index.mjs.map +1 -1
  39. package/dist/{utils-Zq5USthu.mjs → throttle-CnDa3v1k.mjs} +1 -1
  40. package/dist/throttle-CnDa3v1k.mjs.map +1 -0
  41. package/dist/{index-Bg1UKKmY.d.cts → throttle-Da0OA8JT.d.cts} +1 -1
  42. package/dist/throttle-Da0OA8JT.d.cts.map +1 -0
  43. package/dist/throttle-KnkRgZPi.cjs +1 -0
  44. package/dist/{index-rhZqO0Ve.d.mts → throttle-ibiT6E4U.d.mts} +2 -2
  45. package/dist/throttle-ibiT6E4U.d.mts.map +1 -0
  46. package/dist/types/index.cjs +1 -1
  47. package/dist/types/index.d.cts +1 -1
  48. package/dist/types/index.d.mts +4 -5
  49. package/dist/types/index.mjs +1 -1
  50. package/dist/upload/index.cjs +1 -1
  51. package/dist/upload/index.d.cts +1 -1
  52. package/dist/upload/index.d.mts +4 -5
  53. package/dist/upload/index.mjs +1 -1
  54. package/dist/upload-strategy-negotiator-BuxPf1sa.mjs +2 -0
  55. package/dist/upload-strategy-negotiator-BuxPf1sa.mjs.map +1 -0
  56. package/dist/upload-strategy-negotiator-DfiQ0Fy0.cjs +1 -0
  57. package/dist/{uploadista-error-BXq-EvVE.cjs → uploadista-error-B-geDgi8.cjs} +1 -1
  58. package/dist/{uploadista-error-0FLv15ML.d.mts → uploadista-error-BragVhIs.d.mts} +1 -1
  59. package/dist/{uploadista-error-0FLv15ML.d.mts.map → uploadista-error-BragVhIs.d.mts.map} +1 -1
  60. package/dist/utils/index.cjs +1 -1
  61. package/dist/utils/index.d.cts +1 -1
  62. package/dist/utils/index.d.mts +2 -2
  63. package/dist/utils/index.mjs +1 -1
  64. package/dist/{types-D7yTrueF.cjs → websocket-Avz4T8YB.cjs} +1 -1
  65. package/dist/{types-DkF1tvde.mjs → websocket-CdgVhVJs.mjs} +1 -1
  66. package/dist/websocket-CdgVhVJs.mjs.map +1 -0
  67. package/package.json +4 -4
  68. package/src/flow/flow-engine.ts +73 -0
  69. package/dist/checksum-Dsr8Y9VO.cjs +0 -1
  70. package/dist/errors-CRm1FHHT.cjs +0 -0
  71. package/dist/errors-DuxBpAc7.mjs +0 -1
  72. package/dist/flow-DIxNUAi1.cjs +0 -1
  73. package/dist/flow-DeWBwvnY.mjs +0 -2
  74. package/dist/flow-DeWBwvnY.mjs.map +0 -1
  75. package/dist/index-9iG2qHLe.d.mts +0 -1
  76. package/dist/index-Bg1UKKmY.d.cts.map +0 -1
  77. package/dist/index-CvOB2TdS.d.cts.map +0 -1
  78. package/dist/index-DDRpa5CJ.d.cts +0 -1
  79. package/dist/index-DI82_KcP.d.mts.map +0 -1
  80. package/dist/index-DWslhr-b.d.cts.map +0 -1
  81. package/dist/index-fXTlZ4bM.d.mts.map +0 -1
  82. package/dist/index-rhZqO0Ve.d.mts.map +0 -1
  83. package/dist/stream-limiter-DETw0BvJ.cjs +0 -1
  84. package/dist/types-DkF1tvde.mjs.map +0 -1
  85. package/dist/upload--crv1pjP.cjs +0 -1
  86. package/dist/upload-1FHGCe87.mjs +0 -2
  87. package/dist/upload-1FHGCe87.mjs.map +0 -1
  88. package/dist/utils-D0MpvdVc.cjs +0 -1
  89. package/dist/utils-Zq5USthu.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ const e=require(`./websocket-Avz4T8YB.cjs`),t=require(`./uploadista-error-B-geDgi8.cjs`),n=require(`./upload-strategy-negotiator-DfiQ0Fy0.cjs`);let r=require(`effect`),i=require(`zod`),a=require(`micromustache`);const o={enabled:!1,failureThreshold:5,resetTimeout:3e4,halfOpenRequests:3,windowDuration:6e4,fallback:{type:`fail`}},s=`uploadista:circuit-breaker:`;function c(t){let n=e=>`${s}${e}`,i=i=>r.Effect.gen(function*(){let r=n(i),a=yield*t.get(r);if(a===null)return null;try{return e.F.deserialize(a)}catch{return yield*t.delete(r),null}}),a=(r,i)=>{let a=n(r),o=e.F.serialize(i);return t.set(a,o)};return{getState:i,setState:a,incrementFailures:(t,n)=>r.Effect.gen(function*(){let r=Date.now(),o=yield*i(t);return o===null&&(o=e.R({failureThreshold:5,resetTimeout:3e4,halfOpenRequests:3,windowDuration:n})),o=r-o.windowStart>n?{...o,failureCount:1,windowStart:r}:{...o,failureCount:o.failureCount+1},yield*a(t,o),o.failureCount}),resetFailures:e=>r.Effect.gen(function*(){let t=yield*i(e);t!==null&&(yield*a(e,{...t,failureCount:0,windowStart:Date.now()}))}),incrementHalfOpenSuccesses:e=>r.Effect.gen(function*(){let t=yield*i(e);if(t===null)return 1;let n={...t,halfOpenSuccesses:t.halfOpenSuccesses+1};return yield*a(e,n),n.halfOpenSuccesses}),getAllStats:()=>r.Effect.gen(function*(){let e=new Map;if(!t.list)return e;let n=yield*t.list(s),r=Date.now();for(let t of n){let n=t,a=yield*i(n);if(a!==null){let t=r-a.lastStateChange;e.set(n,{nodeType:n,state:a.state,failureCount:a.failureCount,halfOpenSuccesses:a.halfOpenSuccesses,timeSinceLastStateChange:t,timeUntilHalfOpen:a.state===`open`?Math.max(0,a.config.resetTimeout-t):void 0})}}return e}),delete:e=>t.delete(n(e))}}function l(){let t=new Map;return{getState:e=>r.Effect.succeed(t.get(e)??null),setState:(e,n)=>r.Effect.sync(()=>{t.set(e,n)}),incrementFailures:(n,i)=>r.Effect.sync(()=>{let r=Date.now(),a=t.get(n);return a===void 0&&(a=e.R({failureThreshold:5,resetTimeout:3e4,halfOpenRequests:3,windowDuration:i})),a=r-a.windowStart>i?{...a,failureCount:1,windowStart:r}:{...a,failureCount:a.failureCount+1},t.set(n,a),a.failureCount}),resetFailures:e=>r.Effect.sync(()=>{let n=t.get(e);n!==void 0&&t.set(e,{...n,failureCount:0,windowStart:Date.now()})}),incrementHalfOpenSuccesses:e=>r.Effect.sync(()=>{let n=t.get(e);if(n===void 0)return 1;let r={...n,halfOpenSuccesses:n.halfOpenSuccesses+1};return t.set(e,r),r.halfOpenSuccesses}),getAllStats:()=>r.Effect.sync(()=>{let e=new Map,n=Date.now();for(let[r,i]of t){let t=n-i.lastStateChange;e.set(r,{nodeType:r,state:i.state,failureCount:i.failureCount,halfOpenSuccesses:i.halfOpenSuccesses,timeSinceLastStateChange:t,timeUntilHalfOpen:i.state===`open`?Math.max(0,i.config.resetTimeout-t):void 0})}return e}),delete:e=>r.Effect.sync(()=>{t.delete(e)})}}const u=r.Layer.effect(e.L,r.Effect.gen(function*(){return c(yield*e.O)})),d=r.Layer.succeed(e.L,l());var f=class{eventHandler;nodeType;config;store;constructor(e,t,n){this.nodeType=e,this.config={enabled:t.enabled??o.enabled,failureThreshold:t.failureThreshold??o.failureThreshold,resetTimeout:t.resetTimeout??o.resetTimeout,halfOpenRequests:t.halfOpenRequests??o.halfOpenRequests,windowDuration:t.windowDuration??o.windowDuration,fallback:t.fallback??o.fallback},this.store=n}setEventHandler(e){this.eventHandler=e}allowRequest(){let t=this;return r.Effect.gen(function*(){if(!t.config.enabled)return{allowed:!0,state:`closed`,failureCount:0};let n=yield*t.store.getState(t.nodeType),r=Date.now();if(n===null&&(n=e.R({failureThreshold:t.config.failureThreshold,resetTimeout:t.config.resetTimeout,halfOpenRequests:t.config.halfOpenRequests,windowDuration:t.config.windowDuration}),yield*t.store.setState(t.nodeType,n)),n.state===`open`&&r-n.lastStateChange>=t.config.resetTimeout){let e=n.state;n={...n,state:`half-open`,halfOpenSuccesses:0,lastStateChange:r},yield*t.store.setState(t.nodeType,n),yield*t.emitEvent(e,`half-open`,n.failureCount)}return{allowed:n.state!==`open`,state:n.state,failureCount:n.failureCount}})}getState(){let e=this;return r.Effect.gen(function*(){return(yield*e.store.getState(e.nodeType))?.state??`closed`})}getFailureCount(){let e=this;return r.Effect.gen(function*(){return(yield*e.store.getState(e.nodeType))?.failureCount??0})}recordSuccess(){let e=this;return r.Effect.gen(function*(){if(!e.config.enabled)return;let t=yield*e.store.getState(e.nodeType);t!==null&&(t.state===`half-open`?(yield*e.store.incrementHalfOpenSuccesses(e.nodeType))>=e.config.halfOpenRequests&&(yield*e.transitionTo(`closed`,t.failureCount)):t.state===`closed`&&(yield*e.store.resetFailures(e.nodeType)))})}recordFailure(e){let t=this;return r.Effect.gen(function*(){if(!t.config.enabled)return;let e=yield*t.store.getState(t.nodeType);if(e===null||e.state===`closed`){let e=yield*t.store.incrementFailures(t.nodeType,t.config.windowDuration);e>=t.config.failureThreshold&&(yield*t.transitionTo(`open`,e))}else e.state===`half-open`&&(yield*t.transitionTo(`open`,e.failureCount))})}getFallback(){return this.config.fallback}reset(){let t=this;return r.Effect.gen(function*(){let n=(yield*t.store.getState(t.nodeType))?.state??`closed`;yield*t.store.setState(t.nodeType,e.R({failureThreshold:t.config.failureThreshold,resetTimeout:t.config.resetTimeout,halfOpenRequests:t.config.halfOpenRequests,windowDuration:t.config.windowDuration})),n!==`closed`&&(yield*t.emitEvent(n,`closed`,0))})}transitionTo(e,t){let n=this;return r.Effect.gen(function*(){let r=yield*n.store.getState(n.nodeType),i=r?.state??`closed`;if(i===e)return;let a=Date.now(),o={state:e,failureCount:e===`closed`?0:t,lastStateChange:a,halfOpenSuccesses:0,windowStart:e===`closed`?a:r?.windowStart??a,config:{failureThreshold:n.config.failureThreshold,resetTimeout:n.config.resetTimeout,halfOpenRequests:n.config.halfOpenRequests,windowDuration:n.config.windowDuration}};yield*n.store.setState(n.nodeType,o),yield*n.emitEvent(i,e,t)})}emitEvent(e,t,n){let i=this;return r.Effect.gen(function*(){i.eventHandler&&(yield*i.eventHandler({nodeType:i.nodeType,previousState:e,newState:t,timestamp:Date.now(),failureCount:n}))})}},p=class{breakers=new Map;eventHandler;constructor(e){this.store=e}setEventHandler(e){this.eventHandler=e;for(let t of this.breakers.values())t.setEventHandler(e)}getOrCreate(e,t){let n=this.breakers.get(e);return n||(n=new f(e,t,this.store),this.eventHandler&&n.setEventHandler(this.eventHandler),this.breakers.set(e,n)),n}get(e){return this.breakers.get(e)}getAllStats(){return this.store.getAllStats()}resetAll(){let e=this;return r.Effect.gen(function*(){for(let t of e.breakers.values())yield*t.reset()})}clear(){this.breakers.clear()}};function m({source:e,target:t,sourcePort:n,targetPort:r}){return{source:e,target:t,sourcePort:n,targetPort:r}}let h=function(e){return e.JobStart=`job-start`,e.JobEnd=`job-end`,e.FlowStart=`flow-start`,e.FlowEnd=`flow-end`,e.FlowError=`flow-error`,e.FlowPause=`flow-pause`,e.FlowCancel=`flow-cancel`,e.NodeStart=`node-start`,e.NodeEnd=`node-end`,e.NodePause=`node-pause`,e.NodeResume=`node-resume`,e.NodeError=`node-error`,e.NodeStream=`node-stream`,e.NodeResponse=`node-response`,e.DlqItemAdded=`dlq-item-added`,e.DlqRetryStart=`dlq-retry-start`,e.DlqRetrySuccess=`dlq-retry-success`,e.DlqRetryFailed=`dlq-retry-failed`,e.DlqItemExhausted=`dlq-item-exhausted`,e.DlqItemResolved=`dlq-item-resolved`,e}({});var g=class{types;constructor(){this.types=new Map}register(e){if(this.types.has(e.id))throw t.n.fromCode(`VALIDATION_ERROR`,{body:`Input type "${e.id}" is already registered. Types cannot be modified or re-registered.`,details:{typeId:e.id}});this.types.set(e.id,e)}get(e){return this.types.get(e)}list(){return Array.from(this.types.values())}validate(e,n){let r=this.types.get(e);if(!r)return{success:!1,error:t.n.fromCode(`VALIDATION_ERROR`,{body:`Input type "${e}" is not registered`,details:{typeId:e}})};try{return{success:!0,data:r.schema.parse(n)}}catch(n){return{success:!1,error:t.n.fromCode(`VALIDATION_ERROR`,{body:`Data validation failed for input type "${e}"`,cause:n,details:{typeId:e,validationErrors:n}})}}}has(e){return this.types.has(e)}size(){return this.types.size}};const _=new g;function v(e,t){return _.validate(e,t)}var y=class{types;constructor(){this.types=new Map}register(e){if(this.types.has(e.id))throw t.n.fromCode(`VALIDATION_ERROR`,{body:`Output type "${e.id}" is already registered. Types cannot be modified or re-registered.`,details:{typeId:e.id}});this.types.set(e.id,e)}get(e){return this.types.get(e)}list(){return Array.from(this.types.values())}validate(e,n){let r=this.types.get(e);if(!r)return{success:!1,error:t.n.fromCode(`VALIDATION_ERROR`,{body:`Output type "${e}" is not registered`,details:{typeId:e}})};try{return{success:!0,data:r.schema.parse(n)}}catch(n){return{success:!1,error:t.n.fromCode(`VALIDATION_ERROR`,{body:`Data validation failed for output type "${e}"`,cause:n,details:{typeId:e,validationErrors:n}})}}}has(e){return this.types.has(e)}size(){return this.types.size}};const b=new y;function x(e,t){return b.validate(e,t)}let S=function(e){return e.input=`input`,e.process=`process`,e.conditional=`conditional`,e.multiplex=`multiplex`,e.merge=`merge`,e}({});function C({id:e,name:n,description:i,type:a,inputSchema:o,outputSchema:s,run:c,condition:l,multiInput:u=!1,multiOutput:d=!1,pausable:f=!1,retry:p,inputTypeId:m,outputTypeId:h,keepOutput:g=!1,circuitBreaker:v,nodeTypeId:y}){return r.Effect.gen(function*(){return m&&!_.get(m)?yield*t.n.fromCode(`INVALID_INPUT_TYPE`,{body:`Input type "${m}" is not registered in inputTypeRegistry`,details:{inputTypeId:m,nodeId:e}}).toEffect():h&&!b.get(h)?yield*t.n.fromCode(`INVALID_OUTPUT_TYPE`,{body:`Output type "${h}" is not registered in outputTypeRegistry`,details:{outputTypeId:h,nodeId:e}}).toEffect():{id:e,name:n,description:i,type:a,inputTypeId:m,outputTypeId:h,keepOutput:g,inputSchema:o,outputSchema:s,pausable:f,run:({data:i,jobId:a,flowId:l,storageId:u,clientId:d})=>r.Effect.gen(function*(){let f=yield*c({data:yield*r.Effect.try({try:()=>o.parse(i),catch:r=>{let i=r instanceof Error?r.message:String(r);return t.n.fromCode(`FLOW_INPUT_VALIDATION_ERROR`,{body:`Node '${n}' (${e}) input validation failed: ${i}`,cause:r})}}),jobId:a,storageId:u,flowId:l,clientId:d});return f.type===`waiting`?{type:`waiting`,partialData:f.partialData,nodeType:h,nodeId:e}:{type:`complete`,data:yield*r.Effect.try({try:()=>s.parse(f.data),catch:r=>{let i=r instanceof Error?r.message:String(r);return t.n.fromCode(`FLOW_OUTPUT_VALIDATION_ERROR`,{body:`Node '${n}' (${e}) output validation failed: ${i}`,cause:r})}}),nodeType:h,nodeId:e}}),condition:l,multiInput:u,multiOutput:d,retry:p,circuitBreaker:v,nodeTypeId:y}})}const w=e=>({id:e.id,name:e.name,description:e.description,type:e.type,inputTypeId:e.inputTypeId,outputTypeId:e.outputTypeId,nodeTypeId:e.nodeTypeId}),T=e=>t=>t.nodeType===e,E=T(`storage-output-v1`),D=T(`streaming-input-v1`),O=e=>({type:`complete`,data:e}),k=e=>({type:`waiting`,partialData:e}),A=(e,t)=>{if(e===t)return!0;try{return!!(e&&t&&typeof e==`object`&&typeof t==`object`)}catch{return!0}};var ee=class{typeChecker;constructor(e=A){this.typeChecker=e}validateConnection(e,t,n){return this.getCompatibleTypes(e.outputSchema,t.inputSchema)}getCompatibleTypes(e,t){return this.typeChecker(e,t)}validateFlow(e,t){let n=[],r=new Map(e.map(e=>[e.id,e]));for(let e of t){let t=r.get(e.source),i=r.get(e.target);if(!t){n.push(`Source node ${e.source} not found`);continue}if(!i){n.push(`Target node ${e.target} not found`);continue}this.validateConnection(t,i,e)||n.push(`Schema mismatch: ${t.id} output schema incompatible with ${i.id} input schema`)}return{isValid:n.length===0,errors:n}}getExpectedInputSchemas(e,t,n){let r=new Map(t.map(e=>[e.id,e])),i={};for(let t of n)if(t.target===e){let e=r.get(t.source);if(e){let n=t.sourcePort||t.source;i[n]=e.outputSchema}}return i}getActualOutputSchemas(e,t,n){let r=new Map(t.map(e=>[e.id,e])),i={};for(let t of n)if(t.source===e){let e=r.get(t.target);if(e){let n=t.targetPort||t.target;i[n]=e.inputSchema}}return i}validateData(e,t){try{return t.parse(e),{isValid:!0,errors:[]}}catch(e){return e instanceof Error&&`errors`in e?{isValid:!1,errors:e.errors.map(e=>`${e.path.join(`.`)}: ${e.message}`)}:{isValid:!1,errors:[e instanceof Error?e.message:`Validation failed`]}}}};function j(e){if(!e)return{type:``,fileName:``,metadata:void 0,metadataJson:void 0};let t={...e},n=String(t.type||t.mimeType||t[`content-type`]||``);n&&(t.type||=n,t.mimeType||=n);let r=String(t.fileName||t.originalName||t.name||``);return r&&(t.fileName||=r,t.originalName||=r,t.name||=r),{type:n,fileName:r,metadata:t,metadataJson:JSON.stringify(t)}}const M=i.z.object({operation:i.z.literal(`init`),storageId:i.z.string(),metadata:i.z.record(i.z.string(),i.z.any()).optional()}),N=i.z.object({operation:i.z.literal(`finalize`),uploadId:i.z.string()}),P=i.z.object({operation:i.z.literal(`url`),url:i.z.string(),storageId:i.z.string().optional(),metadata:i.z.record(i.z.string(),i.z.any()).optional()}),F=i.z.union([M,N,P]),te=i.z.object({allowedMimeTypes:i.z.array(i.z.string()).optional(),minSize:i.z.number().positive().optional(),maxSize:i.z.number().positive().optional()});function ne(e,n){return r.Effect.gen(function*(){if(n){if(n.allowedMimeTypes&&n.allowedMimeTypes.length>0&&!n.allowedMimeTypes.some(t=>{if(t.endsWith(`/*`)){let n=t.slice(0,-2);return e.type.startsWith(n)}return e.type===t}))throw yield*t.n.fromCode(`VALIDATION_ERROR`,{cause:Error(`File type "${e.type}" is not allowed. Allowed types: ${n.allowedMimeTypes.join(`, `)}`)}).toEffect();if(n.minSize!==void 0&&e.size<n.minSize)throw yield*t.n.fromCode(`VALIDATION_ERROR`,{cause:Error(`File size (${e.size} bytes) is below minimum (${n.minSize} bytes)`)}).toEffect();if(n.maxSize!==void 0&&e.size>n.maxSize)throw yield*t.n.fromCode(`VALIDATION_ERROR`,{cause:Error(`File size (${e.size} bytes) exceeds maximum (${n.maxSize} bytes)`)}).toEffect()}})}function re(i,a,o){let s=o?.keepOutput??!1;return r.Effect.gen(function*(){let o=yield*n.n;return yield*C({id:i,name:`Input`,description:`Handles file input through multiple methods - streaming upload (init/finalize) or direct URL fetch`,type:S.input,nodeTypeId:`input`,inputSchema:F,outputSchema:e.D,keepOutput:s,inputTypeId:z,outputTypeId:I,run:({data:e,flowId:s,jobId:c,clientId:l})=>r.Effect.gen(function*(){switch(e.operation){case`init`:{let t={storageId:e.storageId,size:e.metadata?.size||0,type:e.metadata?.mimeType||`application/octet-stream`,fileName:e.metadata?.originalName,lastModified:e.metadata?.size?Date.now():void 0,metadata:e.metadata?JSON.stringify(e.metadata):void 0,flow:{flowId:s,nodeId:i,jobId:c}};return k(yield*o.createUpload(t,l))}case`finalize`:{let t=yield*o.getUpload(e.uploadId),{type:n}=j(t.metadata);return yield*ne({type:n,size:t.size||0},a),O(t)}case`url`:{let t=yield*n.o(e.url),r=yield*n.a(t),u=e.metadata?.mimeType||t.headers.get(`content-type`)||`application/octet-stream`,d=e.metadata?.size||Number(t.headers.get(`content-length`)||0),f=e.metadata?.originalName||e.url.split(`/`).pop()||`file`;yield*ne({type:u,size:d},a);let p=new ReadableStream({start(e){e.enqueue(new Uint8Array(r)),e.close()}}),m={storageId:e.storageId||`buffer`,size:d,type:u,fileName:f,lastModified:Date.now(),metadata:e.metadata?JSON.stringify(e.metadata):void 0};return O({...yield*o.upload(m,l,p),flow:{flowId:s,nodeId:i,jobId:c}})}default:throw yield*t.n.fromCode(`VALIDATION_ERROR`,{cause:Error(`Invalid operation`)}).toEffect()}})})})}const I=`storage-output-v1`,L=`ocr-output-v1`,R=`image-description-output-v1`,z=`streaming-input-v1`,ie=i.z.object({extractedText:i.z.string(),format:i.z.enum([`markdown`,`plain`,`structured`]),taskType:i.z.enum([`convertToMarkdown`,`freeOcr`,`parseFigure`,`locateObject`]),confidence:i.z.number().min(0).max(1).optional()}),ae=i.z.object({description:i.z.string(),confidence:i.z.number().min(0).max(1).optional(),metadata:i.z.record(i.z.string(),i.z.unknown()).optional()});_.register({id:z,schema:F,version:`1.0.0`,description:`Streaming file input with init/finalize/url operations for flexible file ingestion`}),b.register({id:I,schema:e.D,version:`1.0.0`,description:`Storage output node that saves files to configured storage backend`}),b.register({id:L,schema:ie,version:`1.0.0`,description:`OCR output node that extracts structured text from documents using AI`}),b.register({id:R,schema:ae,version:`1.0.0`,description:`Image description output node that generates AI-powered descriptions of images`});const B={enabled:!0,maxRetries:3,backoff:{type:`exponential`,initialDelayMs:1e3,maxDelayMs:3e5,multiplier:2,jitter:!0},ttlMs:6048e5};function V(e,t){switch(e.type){case`immediate`:return 0;case`fixed`:return e.delayMs;case`exponential`:{let n=e.initialDelayMs*e.multiplier**t,r=Math.min(n,e.maxDelayMs);if(e.jitter){let e=.5+Math.random();return Math.floor(r*e)}return r}default:return 0}}function oe(e,t){return!t.enabled||t.nonRetryableErrors?.includes(e)?!1:t.retryableErrors&&t.retryableErrors.length>0?t.retryableErrors.includes(e):!0}function se(e,t){if(!(t===void 0||t<=0))return new Date(e.getTime()+t)}var H=class e extends r.Context.Tag(`DeadLetterQueueService`)(){static optional=r.Effect.serviceOption(e)};function ce(){return r.Effect.gen(function*(){let t=yield*e.k,n=()=>`dlq_${crypto.randomUUID()}`,i=e=>({...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),expiresAt:e.expiresAt?new Date(e.expiresAt):void 0,nextRetryAt:e.nextRetryAt?new Date(e.nextRetryAt):void 0,retryHistory:e.retryHistory.map(e=>({...e,attemptedAt:new Date(e.attemptedAt)}))}),a=()=>r.Effect.gen(function*(){if(!t.list)return[];let e=yield*t.list(),n=[];for(let a of e){let e=yield*r.Effect.catchAll(t.get(a),()=>r.Effect.succeed(null));e&&n.push(i(e))}return n});return{add:(e,i,a=B)=>r.Effect.gen(function*(){let r=n(),o=new Date,s={code:i.code||`UNKNOWN_ERROR`,message:i.body||i.message||`Unknown error`,nodeId:void 0,stack:i.stack},c=e.tasks.find(e=>e.status===`failed`);c&&(s.nodeId=c.nodeId);let l={};for(let t of e.tasks)t.result!==void 0&&(l[t.nodeId]=t.result);let u=oe(s.code,a),d;if(a.enabled&&u&&a.maxRetries>0){let e=V(a.backoff,0);d=new Date(o.getTime()+e)}let f={id:r,jobId:e.id,flowId:e.flowId,storageId:e.storageId,clientId:e.clientId,error:s,inputs:e.executionState?.inputs||{},nodeResults:l,failedAtNodeId:s.nodeId,retryCount:0,maxRetries:a.maxRetries,nextRetryAt:d,retryHistory:[],createdAt:o,updatedAt:o,expiresAt:se(o,a.ttlMs),status:u&&a.enabled?`pending`:`exhausted`};return yield*t.set(r,f),f}),get:e=>r.Effect.gen(function*(){return i(yield*t.get(e))}),getOption:e=>r.Effect.gen(function*(){let n=yield*r.Effect.either(t.get(e));return n._tag===`Left`?n.left.code===`FILE_NOT_FOUND`?r.Option.none():yield*r.Effect.fail(n.left):r.Option.some(i(n.right))}),delete:e=>t.delete(e),list:(e={})=>r.Effect.gen(function*(){let t=yield*a(),{status:n,flowId:r,clientId:i,limit:o=50,offset:s=0}=e,c=t;n&&(c=c.filter(e=>e.status===n)),r&&(c=c.filter(e=>e.flowId===r)),i&&(c=c.filter(e=>e.clientId===i)),c.sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime());let l=c.length;return{items:c.slice(s,s+o),total:l}}),update:(e,n)=>r.Effect.gen(function*(){let r={...i(yield*t.get(e)),...n,updatedAt:new Date};return yield*t.set(e,r),r}),markRetrying:e=>r.Effect.gen(function*(){let n={...i(yield*t.get(e)),status:`retrying`,updatedAt:new Date};return yield*t.set(e,n),n}),recordRetryFailure:(e,n,a)=>r.Effect.gen(function*(){let r=i(yield*t.get(e)),o=new Date,s=r.retryCount+1,c=[...r.retryHistory,{attemptedAt:o,error:n,durationMs:a}],l=`pending`,u;if(s>=r.maxRetries)l=`exhausted`,u=void 0;else{let e=V(B.backoff,s);u=new Date(o.getTime()+e)}let d={...r,retryCount:s,retryHistory:c,status:l,nextRetryAt:u,updatedAt:o};return yield*t.set(e,d),d}),markResolved:e=>r.Effect.gen(function*(){let n={...i(yield*t.get(e)),status:`resolved`,nextRetryAt:void 0,updatedAt:new Date};return yield*t.set(e,n),n}),getScheduledRetries:(e=100)=>r.Effect.gen(function*(){let t=yield*a(),n=new Date;return t.filter(e=>e.status===`pending`&&e.nextRetryAt&&e.nextRetryAt<=n).sort((e,t)=>(e.nextRetryAt?.getTime()||0)-(t.nextRetryAt?.getTime()||0)).slice(0,e)}),cleanup:(e={})=>r.Effect.gen(function*(){let n=yield*a(),{olderThan:i,status:o}=e,s=new Date,c=0;for(let e of n){let n=!1;e.expiresAt&&e.expiresAt<=s&&(n=!0),i&&e.createdAt<=i&&(o?n=e.status===o:(e.status===`exhausted`||e.status===`resolved`)&&(n=!0)),n&&(yield*r.Effect.catchAll(t.delete(e.id),()=>r.Effect.succeed(void 0)),c++)}return{deleted:c}}),getStats:()=>r.Effect.gen(function*(){let e=yield*a(),t={pending:0,retrying:0,exhausted:0,resolved:0},n={},r,i=0;for(let a of e)t[a.status]++,n[a.flowId]=(n[a.flowId]||0)+1,(!r||a.createdAt<r)&&(r=a.createdAt),i+=a.retryCount;let o=e.length>0?i/e.length:0;return{totalItems:e.length,byStatus:t,byFlow:n,oldestItem:r,averageRetryCount:o}})}})}const le=r.Layer.effect(H,ce());var U=class{maxConcurrency;constructor(e={}){this.maxConcurrency=e.maxConcurrency??4}groupNodesByExecutionLevel(e,t){let n={},r={};e.forEach(e=>{n[e.id]=[],r[e.id]=0}),t.forEach(e=>{n[e.source]?.push(e.target),r[e.target]=(r[e.target]||0)+1});let i=[],a=new Set,o=0;for(;a.size<e.length;){let e=Object.keys(r).filter(e=>r[e]===0&&!a.has(e));if(e.length===0)throw Error(`Cycle detected in flow graph - cannot execute in parallel`);i.push({level:o++,nodes:e}),e.forEach(e=>{a.add(e),delete r[e],n[e]?.forEach(e=>{r[e]!==void 0&&r[e]--})})}return i}executeNodesInParallel(e){return r.Effect.all(e.map(e=>e()),{concurrency:this.maxConcurrency})}canExecuteInParallel(e,t,n){return e.every(e=>(n[e]||[]).every(e=>t.has(e)))}getStats(){return{maxConcurrency:this.maxConcurrency}}};function W(e){return t=>{if(t.nodeType!==e)return!1;let n=b.get(e);return n?n.schema.safeParse(t.data).success:!1}}function G(t){return!t||typeof t!=`object`?!1:e.D.safeParse(t).success}const ue=W(`storage-output-v1`),de=W(L),fe=W(R);function K(e,t){return e.filter(t)}function pe(e,n){return r.Effect.gen(function*(){let r=K(e,n);return r.length===0?yield*t.n.fromCode(`OUTPUT_NOT_FOUND`,{body:`No output of the specified type was found in the flow results`}).toEffect():r.length>1?yield*t.n.fromCode(`MULTIPLE_OUTPUTS_FOUND`,{body:`Found ${r.length} outputs of the specified type, expected exactly one`,details:{foundCount:r.length,nodeIds:r.map(e=>e.nodeId)}}).toEffect():r[0]})}function me(e,t){return K(e,t)[0]}function he(e,t){return e.find(e=>e.nodeId===t)}function ge(e,t){return e.some(t)}function _e(e){return e.operation===`init`}function ve(e){return e.operation===`finalize`}function ye(e){return e.operation===`url`}function be(e){return e.operation===`init`||e.operation===`url`}const xe=e=>({id:e.id,name:e.name,nodes:e.nodes.map(w),edges:e.edges});function q(n){return r.Effect.gen(function*(){let a=yield*r.Effect.all(n.nodes.map(e=>r.Effect.isEffect(e)?e:r.Effect.succeed(e))),{flowId:o,name:s,onEvent:c,checkJobStatus:l,edges:u,inputSchema:d,outputSchema:f,typeChecker:m,circuitBreaker:g}=n,_=a,v=new ee(m),y=e=>{let t=e.circuitBreaker,n=e.nodeTypeId?g?.nodeTypeOverrides?.[e.nodeTypeId]:void 0,r=g?.defaults;if(!(!t&&!n&&!r))return{...r,...n,...t}},b=()=>{let e={},t={},n={};return _.forEach(r=>{e[r.id]=[],n[r.id]=[],t[r.id]=0}),u.forEach(r=>{e[r.source]?.push(r.target),n[r.target]?.push(r.source),t[r.target]=(t[r.target]||0)+1}),{graph:e,reverseGraph:n,inDegree:t}},x=new Map;u.forEach(e=>{let t=x.get(e.target)||[];t.push({source:e.source,sourcePort:e.sourcePort,targetPort:e.targetPort}),x.set(e.target,t)});let S=new Map,C=()=>{let{graph:e,inDegree:t}=b(),n=[],r=[];for(Object.keys(t).forEach(e=>{t[e]===0&&n.push(e)});n.length>0;){let i=n.shift();if(!i)throw Error(`No current node found`);r.push(i),e[i]?.forEach(e=>{t[e]=(t[e]||0)-1,t[e]===0&&n.push(e)})}return r},w=(e,t)=>{if(!e.condition)return r.Effect.succeed(!0);let{field:n,operator:i,value:a}=e.condition,o=t,s=o?.metadata?.[n]||o?.[n],c=(()=>{switch(i){case`equals`:return s===a;case`notEquals`:return s!==a;case`greaterThan`:return Number(s)>Number(a);case`lessThan`:return Number(s)<Number(a);case`contains`:return String(s).includes(String(a));case`startsWith`:return String(s).startsWith(String(a));default:return!0}})();return r.Effect.succeed(c)},T=(e,t)=>{let n=x.get(e)||[],r={};return n.forEach(e=>{let n=e.source,i=t.get(n);if(i!==void 0){if(_.find(e=>e.id===n)?.type===`conditional`&&e.sourcePort){let t=S.get(n)?`true`:`false`;if(e.sourcePort!==t)return}r[n]=i}}),r},E=(e,t,n)=>{let r=x.get(e)||[];if(_.find(t=>t.id===e)?.type===`input`||r.length===0)return`execute`;let i=!1,a=!1,o=!1,s=!1;for(let e of r){let r=e.source;if(n.has(r)){a=!0;continue}if(t.get(r)===void 0){s=!0;continue}if(_.find(e=>e.id===r)?.type===`conditional`&&e.sourcePort){let t=S.get(r);if(t===void 0){s=!0;continue}let n=t?`true`:`false`;e.sourcePort===n?o=!0:i=!0}else o=!0}return o?`execute`:(i||a)&&!s?`skip`:s?`wait`:`execute`},D=e=>{let t=_.filter(e=>e.type===`input`),n={};return t.forEach(t=>{e&&typeof e==`object`&&t.id in e&&(n[t.id]=d.parse(e[t.id]))}),n},O=e=>!u.some(t=>t.source===e),k=e=>{let t=_.find(t=>t.id===e);return O(e)||t?.keepOutput===!0},A=e=>{let t=_.filter(e=>k(e.id)),n={};return t.forEach(t=>{let r=e.get(t.id);r!==void 0&&(n[t.id]=r)}),n},j=(e,t)=>{let n=_.filter(e=>k(e.id)),r=[];return n.forEach(n=>{let i=e.get(n.id);if(i!==void 0){let e=t.get(n.id);r.push({nodeId:n.id,nodeType:e,data:i,timestamp:new Date().toISOString()})}}),r},M=(t,n,i)=>r.Effect.gen(function*(){if(t.storage.id===n)return t;let a=yield*e.S,o=yield*a.getDataStore(t.storage.id,i),s=yield*a.getDataStore(n,i),c=yield*o.read(t.id),l=r.Stream.make(c),u={...t,storage:{id:n,type:t.storage.type}},d=yield*s.create(u);return yield*s.write({file_id:d.id,stream:l,offset:0},{}),d}),N=(e,i,a,s,u,d,f,p)=>r.Effect.gen(function*(){let m=u.get(e);if(!m)return yield*t.n.fromCode(`FLOW_NODE_NOT_FOUND`).toEffect();if(l){let e=yield*l(d);if(e===`paused`)return yield*t.n.fromCode(`FLOW_PAUSED`,{cause:`Flow ${o} was paused by user at job ${d}`}).toEffect();if(e===`cancelled`)return yield*t.n.fromCode(`FLOW_CANCELLED`,{cause:`Flow ${o} was cancelled by user at job ${d}`}).toEffect()}c&&(yield*c({jobId:d,flowId:o,nodeId:e,eventType:h.NodeStart,nodeName:m.name,nodeType:m.type}));let g=m.retry?.maxRetries??0,_=m.retry?.retryDelay??1e3,v=m.retry?.exponentialBackoff??!0,b=y(m),x=b?.enabled&&m.nodeTypeId&&p?p.getOrCreate(m.nodeTypeId,b):null;if(x){let{allowed:n,state:i,failureCount:s}=yield*x.allowRequest();if(!n){let n=x.getFallback();return yield*r.Effect.logWarning(`Circuit breaker OPEN for node type "${m.nodeTypeId}" - applying fallback`),n.type===`skip`?(c&&(yield*c({jobId:d,flowId:o,nodeId:e,eventType:h.NodeEnd,nodeName:m.name})),{nodeId:e,result:a[e],success:!0,waiting:!1}):n.type===`default`?(c&&(yield*c({jobId:d,flowId:o,nodeId:e,eventType:h.NodeEnd,nodeName:m.name,result:n.value})),{nodeId:e,result:n.value,success:!0,waiting:!1}):yield*t.n.fromCode(`CIRCUIT_BREAKER_OPEN`,{body:`Circuit breaker is open for node type "${m.name}"`,details:{nodeType:m.name,nodeId:e,state:i,failureCount:s}}).toEffect()}}let C=0,E=null;for(;C<=g;)try{let l,u={};if(m.type===`input`){if(l=a[e],l===void 0)return yield*r.Effect.logError(`Input node ${e} has no input data`),yield*t.n.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Input node ${e} has no input data`)}).toEffect()}else{if(u=T(e,s),Object.keys(u).length===0)return yield*r.Effect.logError(`Node ${e} has no input data`),yield*t.n.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Node ${e} has no input data`)}).toEffect();if(m.multiInput)l=u;else{let n=Object.keys(u)[0];if(!n)return yield*t.n.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Node ${e} has no input data`)}).toEffect();l=u[n]}}if(m.type===`conditional`){let t=yield*w(m,l);S.set(e,t)}let p=yield*m.run({data:l,inputs:u,jobId:d,flowId:o,storageId:i,clientId:f});if(p.type===`waiting`){let t=p.partialData;return c&&(yield*c({jobId:d,flowId:o,nodeId:e,eventType:h.NodePause,nodeName:m.name,partialData:t})),{nodeId:e,result:t,success:!0,waiting:!0,nodeType:p.nodeType}}let g=p.data;if(k(e)&&(G(g)&&g.storage.id!==i&&(yield*r.Effect.logDebug(`Auto-persisting output node ${e} output from ${g.storage.id} to ${i}`),g=yield*M(g,i,f)),n.hooks?.onNodeOutput)){yield*r.Effect.logDebug(`Calling onNodeOutput hook for sink node ${e}`);let t=n.hooks.onNodeOutput({output:g,nodeId:e,flowId:o,jobId:d,storageId:i,clientId:f});g=yield*r.Effect.isEffect(t)?t:r.Effect.promise(()=>t)}return x&&(yield*x.recordSuccess()),c&&(yield*c({jobId:d,flowId:o,nodeId:e,eventType:h.NodeEnd,nodeName:m.name,result:g})),{nodeId:e,result:g,success:!0,waiting:!1,nodeType:p.nodeType}}catch(n){if(E=n instanceof t.n?n:t.n.fromCode(`FLOW_NODE_ERROR`,{cause:n}),x&&(yield*x.recordFailure(E.body)),C<g){C++;let t=v?_*2**(C-1):_;yield*r.Effect.logWarning(`Node ${e} (${m.name}) failed, retrying (${C}/${g}) after ${t}ms`),yield*r.Effect.sleep(t);continue}return c&&(yield*c({jobId:d,flowId:o,nodeId:e,eventType:h.NodeError,nodeName:m.name,error:E.body,retryCount:C})),yield*E.toEffect()}return E?yield*E.toEffect():yield*t.n.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Unexpected error in retry loop`)}).toEffect()}).pipe((()=>{let t=u.get(e),n=t?.nodeTypeId??t?.type??`unknown`;return r.Effect.withSpan(`node-${n}`,{attributes:{"node.id":e,"node.type":t?.type??`unknown`,"node.type_id":t?.nodeTypeId??`unknown`,"node.name":t?.name??`unknown`,"flow.id":o,"flow.job_id":d}})})()),P=({inputs:a,storageId:s,jobId:l,resumeFrom:d,clientId:m})=>r.Effect.gen(function*(){let g=yield*r.Effect.serviceOption(e.L),v=g._tag===`Some`?new p(g.value):null;!d&&c&&(yield*c({jobId:l,eventType:h.FlowStart,flowId:o}));let y=D(a||{}),b,x,S;d?(b=d.executionOrder,x=d.nodeResults,S=d.currentIndex):(b=C(),x=new Map,S=0);let w=new Map;if(b.length!==_.length)return yield*t.n.fromCode(`FLOW_CYCLE_ERROR`).toEffect();let T=new Map(_.map(e=>[e.id,e])),O=new Set;if(n.parallelExecution?.enabled??!1){yield*r.Effect.logDebug(`Flow ${o}: Executing in parallel mode (maxConcurrency: ${n.parallelExecution?.maxConcurrency??4})`);let e=new U({maxConcurrency:n.parallelExecution?.maxConcurrency??4}),t=e.groupNodesByExecutionLevel(_,u);yield*r.Effect.logDebug(`Flow ${o}: Grouped nodes into ${t.length} execution levels`);let i={};_.forEach(e=>{i[e.id]=[]}),u.forEach(e=>{i[e.target]?.push(e.source)});for(let n of t){yield*r.Effect.logDebug(`Flow ${o}: Executing level ${n.level} with nodes: ${n.nodes.join(`, `)}`);let t=[],i=[];for(let e of n.nodes)E(e,x,O)===`skip`?(i.push(e),O.add(e)):t.push(e);if(i.length>0&&(yield*r.Effect.logDebug(`Flow ${o}: Skipping nodes due to conditional routing: ${i.join(`, `)}`)),t.length===0){yield*r.Effect.logDebug(`Flow ${o}: All nodes in level ${n.level} skipped due to conditional routing`);continue}let a=t.map(e=>()=>r.Effect.gen(function*(){if(d&&e===d.executionOrder[S]&&c){let t=T.get(e);t&&(yield*c({jobId:l,flowId:o,nodeId:e,eventType:h.NodeResume,nodeName:t.name,nodeType:t.type}))}return{nodeId:e,nodeResult:yield*N(e,s,y,x,T,l,m,v)}})),u=yield*e.executeNodesInParallel(a);for(let{nodeId:e,nodeResult:t}of u){if(t.waiting)return t.result!==void 0&&(x.set(e,t.result),t.nodeType&&w.set(e,t.nodeType)),{type:`paused`,nodeId:e,executionState:{executionOrder:b,currentIndex:b.indexOf(e),inputs:y}};t.success&&(x.set(e,t.result),t.nodeType&&w.set(e,t.nodeType))}}}else{yield*r.Effect.logDebug(`Flow ${o}: Executing in sequential mode`);for(let e=S;e<b.length;e++){let n=b[e];if(!n)return yield*t.n.fromCode(`FLOW_NODE_NOT_FOUND`).toEffect();if(E(n,x,O)===`skip`){yield*r.Effect.logDebug(`Flow ${o}: Skipping node ${n} due to conditional routing`),O.add(n);continue}if(d&&e===S&&c){let e=T.get(n);e&&(yield*c({jobId:l,flowId:o,nodeId:n,eventType:h.NodeResume,nodeName:e.name,nodeType:e.type}))}let i=yield*N(n,s,y,x,T,l,m,v);if(i.waiting)return i.result!==void 0&&(x.set(i.nodeId,i.result),i.nodeType&&w.set(i.nodeId,i.nodeType)),{type:`paused`,nodeId:i.nodeId,executionState:{executionOrder:b,currentIndex:e,inputs:y}};i.success&&(x.set(i.nodeId,i.result),i.nodeType&&w.set(i.nodeId,i.nodeType))}}let ee=A(x),M=j(x,w),P=i.z.record(i.z.string(),f).safeParse(ee);if(!P.success){let e=`Flow output validation failed: ${P.error.message}. Expected outputs: ${JSON.stringify(Object.keys(A(x)))}. Output nodes (sinks + keepOutput): ${_.filter(e=>k(e.id)).map(e=>e.id).join(`, `)}`;return c&&(yield*c({jobId:l,eventType:h.FlowError,flowId:o,error:e})),yield*t.n.fromCode(`FLOW_OUTPUT_VALIDATION_ERROR`,{body:e,cause:P.error}).toEffect()}let F=P.data;return c&&(yield*c({jobId:l,eventType:h.FlowEnd,flowId:o,outputs:M,result:F})),{type:`completed`,result:F,outputs:M}});return{id:o,name:s,nodes:_,edges:u,inputSchema:d,outputSchema:f,onEvent:c,checkJobStatus:l,hooks:n.hooks,run:({inputs:e,storageId:t,jobId:n,clientId:r})=>P({inputs:e,storageId:t,jobId:n,clientId:r}),resume:({jobId:e,storageId:t,nodeResults:n,executionState:r,clientId:i})=>P({inputs:r.inputs,storageId:t,jobId:e,resumeFrom:{executionOrder:r.executionOrder,nodeResults:new Map(Object.entries(n)),currentIndex:r.currentIndex},clientId:i}),validateTypes:()=>{let e=_;return v.validateFlow(e,u)},validateInputs:e=>v.validateData(e,d),validateOutputs:e=>v.validateData(e,f)}})}var J=class e extends r.Context.Tag(`FlowWaitUntil`)(){static optional=r.Effect.serviceOption(e)},Se=class e extends r.Context.Tag(`FlowLifecycleHook`)(){static optional=r.Effect.serviceOption(e)},Ce=class extends r.Context.Tag(`FlowProvider`)(){},we=class extends r.Context.Tag(`FlowEngine`)(){};const Y=e=>typeof e==`object`&&!!e&&`id`in e,Te=e=>typeof e==`object`&&e&&`nodeId`in e&&`data`in e&&`timestamp`in e?e.data:e;function Ee(e,n,i){let a=t=>{let a=e=>r.Effect.gen(function*(){let n=yield*i.get(t);n&&(yield*i.set(t,{...n,...e,updatedAt:new Date}))});return o=>r.Effect.gen(function*(){switch(e.onEvent&&(yield*r.Effect.catchAll(e.onEvent(o),e=>(r.Effect.logError(`Original onEvent failed`,e),r.Effect.succeed({eventId:null})))),yield*n.emit(t,o),r.Effect.logInfo(`Updating job ${t} with event ${o.eventType}`),o.eventType){case h.FlowStart:yield*a({status:`running`});break;case h.FlowEnd:yield*r.Effect.gen(function*(){let e=yield*i.get(t);e&&o.outputs&&(yield*i.set(t,{...e,result:o.outputs,updatedAt:new Date}))});break;case h.FlowError:yield*a({status:`failed`,error:o.error});break;case h.NodeStart:yield*r.Effect.gen(function*(){let e=yield*i.get(t);if(e){let n=e.tasks.find(e=>e.nodeId===o.nodeId)?e.tasks.map(e=>e.nodeId===o.nodeId?{...e,status:`running`,updatedAt:new Date}:e):[...e.tasks,{nodeId:o.nodeId,status:`running`,createdAt:new Date,updatedAt:new Date}];yield*i.set(t,{...e,tasks:n,updatedAt:new Date})}});break;case h.NodePause:yield*r.Effect.gen(function*(){let e=yield*i.get(t);if(e){let n=e.tasks.find(e=>e.nodeId===o.nodeId)?e.tasks.map(e=>e.nodeId===o.nodeId?{...e,status:`paused`,result:o.partialData,updatedAt:new Date}:e):[...e.tasks,{nodeId:o.nodeId,status:`paused`,result:o.partialData,createdAt:new Date,updatedAt:new Date}],r=o.partialData?.id,a=r?[...e.activeUploads||[],r]:e.activeUploads;yield*i.set(t,{...e,tasks:n,activeUploads:a,updatedAt:new Date})}});break;case h.NodeResume:yield*r.Effect.gen(function*(){let e=yield*i.get(t);if(e){let n=e.tasks.map(e=>e.nodeId===o.nodeId?{...e,status:`running`,updatedAt:new Date}:e);yield*i.set(t,{...e,tasks:n,updatedAt:new Date})}});break;case h.NodeEnd:yield*r.Effect.gen(function*(){let n=yield*i.get(t);if(n){let a=n.tasks.map(e=>e.nodeId===o.nodeId?{...e,status:`completed`,result:o.result,updatedAt:new Date}:e),s=!e.edges.some(e=>e.source===o.nodeId),c=e.nodes.find(e=>e.id===o.nodeId)?.keepOutput===!0,l=o.result,u=Te(l),d=n.intermediateFiles||[],f=s||c;f&&Y(u)&&u.id?(d=d.filter(e=>e!==u.id),c&&!s&&r.Effect.logInfo(`Preserving output from node ${o.nodeId} due to keepOutput flag`)):!f&&Y(u)&&u.id&&(d.includes(u.id)||d.push(u.id));let p=n.activeUploads||[];Y(u)&&u.id&&(p=p.filter(e=>e!==u.id)),yield*i.set(t,{...n,tasks:a,intermediateFiles:d,activeUploads:p,updatedAt:new Date})}});break;case h.NodeError:yield*r.Effect.gen(function*(){let e=yield*i.get(t);if(e){let n=e.tasks.map(e=>e.nodeId===o.nodeId?{...e,status:`failed`,error:o.error,retryCount:o.retryCount,updatedAt:new Date}:e);yield*i.set(t,{...e,tasks:n,error:o.error,updatedAt:new Date})}});break}return{eventId:t}})},o=e=>e=>r.Effect.gen(function*(){let n=yield*i.get(e);return n?n.status===`paused`?`paused`:n.status===`cancelled`?`cancelled`:`running`:yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found`}))});return{...e,run:t=>r.Effect.gen(function*(){let n=t.jobId||crypto.randomUUID(),r=a(n),i=o(n);return yield*(yield*q({flowId:e.id,name:e.name,nodes:e.nodes,edges:e.edges,inputSchema:e.inputSchema,outputSchema:e.outputSchema,onEvent:r,checkJobStatus:i})).run({...t,jobId:n,clientId:t.clientId})}),resume:t=>r.Effect.gen(function*(){let n=t.jobId,r=a(n),i=o(n);return yield*(yield*q({flowId:e.id,name:e.name,nodes:e.nodes,edges:e.edges,inputSchema:e.inputSchema,outputSchema:e.outputSchema,onEvent:r,checkJobStatus:i})).resume(t)})}}function De(){return r.Effect.gen(function*(){let i=yield*Ce,a=yield*e.d,o=yield*e.A,s=yield*n.n,c=yield*H.optional,l=yield*Se.optional,u=(e,n)=>r.Effect.gen(function*(){let i=yield*o.get(e);return i?yield*o.set(e,{...i,...n}):yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found`}))}),d=(e,t)=>r.Effect.gen(function*(){let n=yield*o.get(e);!n||!n.intermediateFiles||n.intermediateFiles.length===0||(yield*r.Effect.logInfo(`Cleaning up ${n.intermediateFiles.length} intermediate files for job ${e}`),yield*r.Effect.all(n.intermediateFiles.map(e=>r.Effect.gen(function*(){yield*s.delete(e,t),yield*r.Effect.logDebug(`Deleted intermediate file ${e}`)}).pipe(r.Effect.catchAll(t=>r.Effect.gen(function*(){return yield*r.Effect.logWarning(`Failed to delete intermediate file ${e}: ${t}`),r.Effect.succeed(void 0)})))),{concurrency:5}),yield*u(e,{intermediateFiles:[]}))}),f=(e,t)=>r.Effect.gen(function*(){if(r.Option.isNone(c)){yield*r.Effect.logDebug(`[FlowServer] DLQ not configured, skipping for job: ${e}`);return}let n=c.value,i=yield*r.Effect.catchAll(o.get(e),()=>r.Effect.succeed(null));if(!i){yield*r.Effect.logWarning(`[FlowServer] Job ${e} not found when adding to DLQ`);return}yield*r.Effect.catchAll(n.add(i,t),t=>r.Effect.gen(function*(){return yield*r.Effect.logError(`[FlowServer] Failed to add job ${e} to DLQ`,t),r.Effect.succeed(void 0)})),yield*r.Effect.logInfo(`[FlowServer] Added job ${e} to Dead Letter Queue`)}),p=e=>r.Option.isSome(l)?l.value.onComplete(e).pipe(r.Effect.catchAll(e=>r.Effect.logWarning(`FlowLifecycleHook.onComplete failed: ${e}`))):r.Effect.void,m=r.Effect.gen(function*(){let e=yield*r.Effect.currentSpan.pipe(r.Effect.option);return r.Option.match(e,{onNone:()=>void 0,onSome:e=>({traceId:e.traceId,spanId:e.spanId,traceFlags:e.sampled?1:0})})}),g=({jobId:e,flow:n,storageId:i,clientId:c,inputs:l})=>r.Effect.gen(function*(){return console.log(`[FlowServer] executeFlowInBackground started for job: ${e}`),yield*u(e,{status:`running`,traceContext:yield*m}),yield*r.Effect.gen(function*(){console.log(`[FlowServer] Creating flowWithEvents for job: ${e}`);let t=Ee(n,a,o);console.log(`[FlowServer] Running flow for job: ${e}`);let r=yield*t.run({inputs:l,storageId:i,jobId:e,clientId:c});return console.log(`[FlowServer] Flow completed for job: ${e}, result type: ${r.type}`),r.type===`paused`?yield*u(e,{status:`paused`,pausedAt:r.nodeId,executionState:r.executionState,updatedAt:new Date}):(yield*u(e,{status:`completed`,updatedAt:new Date,endedAt:new Date}),yield*d(e,c),yield*p({jobId:e,flowId:n.id,clientId:c,status:`completed`})),r}).pipe(r.Effect.withSpan(`flow-execution`,{attributes:{"flow.id":n.id,"flow.name":n.name,"flow.job_id":e,"flow.storage_id":i,"flow.node_count":n.nodes.length}}))}).pipe(r.Effect.withSpan(`flow`,{attributes:{"flow.id":n.id,"flow.name":n.name,"flow.job_id":e,"flow.storage_id":i,"flow.node_count":n.nodes.length}}),r.Effect.catchAll(i=>r.Effect.gen(function*(){yield*r.Effect.logError(`Flow execution failed`,i);let l=i instanceof t.n?i.body:String(i);yield*r.Effect.logInfo(`Updating job ${e} to failed status with error: ${l}`),yield*u(e,{status:`failed`,error:l,updatedAt:new Date}).pipe(r.Effect.catchAll(t=>r.Effect.gen(function*(){return yield*r.Effect.logError(`Failed to update job ${e}`,t),r.Effect.succeed(void 0)})));let m=yield*o.get(e);throw m&&(yield*a.emit(e,{jobId:e,eventType:h.FlowError,flowId:m.flowId,error:l}).pipe(r.Effect.catchAll(t=>r.Effect.gen(function*(){return yield*r.Effect.logError(`Failed to emit FlowError event for job ${e}`,t),r.Effect.succeed(void 0)})))),n.onEvent&&(yield*n.onEvent({jobId:e,eventType:h.FlowError,flowId:n.id,error:l}).pipe(r.Effect.catchAll(t=>r.Effect.gen(function*(){return yield*r.Effect.logError(`Failed to call flow.onEvent for FlowError event for job ${e}`,t),r.Effect.succeed({eventId:null})})))),yield*d(e,c).pipe(r.Effect.catchAll(t=>r.Effect.gen(function*(){return yield*r.Effect.logWarning(`Failed to cleanup intermediate files for job ${e}`,t),r.Effect.succeed(void 0)}))),yield*r.Effect.gen(function*(){let t=yield*o.get(e);t&&t.activeUploads&&t.activeUploads.length>0&&(yield*r.Effect.logInfo(`Cleaning up ${t.activeUploads.length} active uploads for failed job ${e}`),yield*r.Effect.all(t.activeUploads.map(t=>r.Effect.gen(function*(){yield*s.delete(t,c),yield*r.Effect.logDebug(`Aborted active upload ${t} for failed job ${e}`)}).pipe(r.Effect.catchAll(e=>r.Effect.gen(function*(){return yield*r.Effect.logWarning(`Failed to abort active upload ${t}: ${e}`),r.Effect.succeed(void 0)})))),{concurrency:5}),yield*u(e,{activeUploads:[]}))}).pipe(r.Effect.catchAll(t=>r.Effect.gen(function*(){return yield*r.Effect.logWarning(`Failed to cleanup active uploads for job ${e}`,t),r.Effect.succeed(void 0)}))),yield*f(e,i instanceof t.n?i:new t.n({code:`UNKNOWN_ERROR`,status:500,body:String(i),cause:i})),yield*p({jobId:e,flowId:n.id,clientId:c,status:`failed`}),i})));return{getFlow:(e,t)=>r.Effect.gen(function*(){return yield*i.getFlow(e,t)}),getFlowData:(e,t)=>r.Effect.gen(function*(){return xe(yield*i.getFlow(e,t))}),runFlow:({flowId:e,storageId:n,clientId:a,inputs:s})=>r.Effect.gen(function*(){let c=yield*J.optional,l=yield*r.Effect.try({try:()=>pt.parse({inputs:s}),catch:e=>t.n.fromCode(`FLOW_INPUT_VALIDATION_ERROR`,{cause:e})}),u=crypto.randomUUID(),d=new Date,f={id:u,flowId:e,storageId:n,clientId:a,status:`started`,createdAt:d,updatedAt:d,tasks:[]};yield*o.set(u,f);let p=yield*i.getFlow(e,a);console.log(`[FlowServer] About to fork flow execution for job: ${u}`);let m=g({jobId:u,flow:p,storageId:n,clientId:a,inputs:l.inputs}).pipe(r.Effect.tapErrorCause(e=>r.Effect.logError(`Flow execution failed`,e)));if(r.Option.isSome(c)){console.log(`[FlowServer] Using waitUntil for job: ${u}`);let e=yield*r.Effect.runtime(),t=r.Runtime.runPromise(e)(m);c.value(t)}else console.log(`[FlowServer] Using Effect.forkDaemon for job: ${u}`),yield*r.Effect.forkDaemon(m);return console.log(`[FlowServer] Flow execution started for job: ${u}`),f}),getJobStatus:e=>r.Effect.gen(function*(){return(yield*o.get(e))||(yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found`})))}),resumeFlow:({jobId:e,nodeId:n,newData:c,clientId:l})=>r.Effect.gen(function*(){let m=yield*J.optional,g=yield*o.get(e);if(!g)return console.error(`Job not found`),yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found`}));if(g.status!==`paused`)return console.error(`Job is not paused`),yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${e} is not paused (status: ${g.status})`}));if(g.pausedAt!==n)return console.error(`Job is not paused at the expected node`),yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${e} is paused at node ${g.pausedAt}, not ${n}`}));if(!g.executionState)return console.error(`Job has no execution state`),yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${e} has no execution state`}));let _={...g.tasks.reduce((e,t)=>(t.result!==void 0&&(e[t.nodeId]=t.result),e),{}),[n]:c},v={...g.executionState.inputs,[n]:c};yield*u(e,{status:`running`});let y=yield*i.getFlow(g.flowId,g.clientId),b=g.traceContext?r.Tracer.externalSpan({traceId:g.traceContext.traceId,spanId:g.traceContext.spanId,sampled:g.traceContext.traceFlags===1}):void 0,x=r.Effect.gen(function*(){let n=Ee(y,a,o);if(!g.executionState)return yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${e} has no execution state`}));let i=yield*n.resume({jobId:e,storageId:g.storageId,nodeResults:_,executionState:{...g.executionState,inputs:v},clientId:g.clientId});return i.type===`paused`?yield*u(e,{status:`paused`,pausedAt:i.nodeId,executionState:i.executionState,updatedAt:new Date}):(yield*u(e,{status:`completed`,pausedAt:void 0,executionState:void 0,updatedAt:new Date,endedAt:new Date}),yield*d(e,l),yield*p({jobId:e,flowId:y.id,clientId:g.clientId,status:`completed`})),i}).pipe(r.Effect.withSpan(`flow-execution-resume`,{attributes:{"flow.id":y.id,"flow.name":y.name,"flow.job_id":e,"flow.storage_id":g.storageId,"flow.resumed_from_node":n},parent:b})).pipe(r.Effect.catchAll(n=>r.Effect.gen(function*(){yield*r.Effect.logError(`Flow resume failed`,n);let i=n instanceof t.n?n.body:String(n);yield*r.Effect.logInfo(`Updating job ${e} to failed status with error: ${i}`),yield*u(e,{status:`failed`,error:i,updatedAt:new Date}).pipe(r.Effect.catchAll(t=>r.Effect.gen(function*(){return yield*r.Effect.logError(`Failed to update job ${e}`,t),r.Effect.succeed(void 0)})));let c=yield*o.get(e);throw c&&(yield*a.emit(e,{jobId:e,eventType:h.FlowError,flowId:c.flowId,error:i}).pipe(r.Effect.catchAll(t=>r.Effect.gen(function*(){return yield*r.Effect.logError(`Failed to emit FlowError event for job ${e}`,t),r.Effect.succeed(void 0)})))),yield*d(e,l).pipe(r.Effect.catchAll(t=>r.Effect.gen(function*(){return yield*r.Effect.logWarning(`Failed to cleanup intermediate files for job ${e}`,t),r.Effect.succeed(void 0)}))),yield*r.Effect.gen(function*(){let t=yield*o.get(e);t&&t.activeUploads&&t.activeUploads.length>0&&(yield*r.Effect.logInfo(`Cleaning up ${t.activeUploads.length} active uploads for failed job ${e}`),yield*r.Effect.all(t.activeUploads.map(t=>r.Effect.gen(function*(){yield*s.delete(t,l),yield*r.Effect.logDebug(`Aborted active upload ${t} for failed job ${e}`)}).pipe(r.Effect.catchAll(e=>r.Effect.gen(function*(){return yield*r.Effect.logWarning(`Failed to abort active upload ${t}: ${e}`),r.Effect.succeed(void 0)})))),{concurrency:5}),yield*u(e,{activeUploads:[]}))}).pipe(r.Effect.catchAll(t=>r.Effect.gen(function*(){return yield*r.Effect.logWarning(`Failed to cleanup active uploads for job ${e}`,t),r.Effect.succeed(void 0)}))),yield*f(e,n instanceof t.n?n:new t.n({code:`UNKNOWN_ERROR`,status:500,body:String(n),cause:n})),yield*p({jobId:e,flowId:y.id,clientId:g.clientId,status:`failed`}),n}))).pipe(r.Effect.tapErrorCause(e=>r.Effect.logError(`Flow resume failed`,e)));if(r.Option.isSome(m)){console.log(`[FlowServer] Using waitUntil for resume job: ${e}`);let t=yield*r.Effect.runtime(),n=r.Runtime.runPromise(t)(x);m.value(n)}else console.log(`[FlowServer] Using Effect.forkDaemon for resume job: ${e}`),yield*r.Effect.forkDaemon(x);return(yield*o.get(e))||(yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found after update`})))}),pauseFlow:(e,n)=>r.Effect.gen(function*(){let i=yield*o.get(e);if(!i)return yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found`}));if(n!==null&&i.clientId!==n)return yield*r.Effect.fail(t.n.fromCode(`FLOW_NOT_AUTHORIZED`,{cause:`Client ${n} is not authorized to pause job ${e}`}));if(i.status!==`running`)return yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${e} cannot be paused (current status: ${i.status})`}));let s=i.tasks.find(e=>e.status===`running`)?.nodeId;return yield*u(e,{status:`paused`,pausedAt:s,updatedAt:new Date}),yield*a.emit(e,{jobId:e,flowId:i.flowId,eventType:h.FlowPause,pausedAt:s}),(yield*o.get(e))||(yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found after pause`})))}),cancelFlow:(e,n)=>r.Effect.gen(function*(){let i=yield*o.get(e);return i?n!==null&&i.clientId!==n?yield*r.Effect.fail(t.n.fromCode(`FLOW_NOT_AUTHORIZED`,{cause:`Client ${n} is not authorized to cancel job ${e}`})):i.status!==`running`&&i.status!==`paused`&&i.status!==`started`?yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${e} cannot be cancelled (current status: ${i.status})`})):(yield*u(e,{status:`cancelled`,updatedAt:new Date,endedAt:new Date}),yield*a.emit(e,{jobId:e,flowId:i.flowId,eventType:h.FlowCancel}),i.activeUploads&&i.activeUploads.length>0&&(yield*r.Effect.logInfo(`Cleaning up ${i.activeUploads.length} active uploads for job ${e}`),yield*r.Effect.all(i.activeUploads.map(t=>r.Effect.gen(function*(){yield*s.delete(t,n),yield*r.Effect.logDebug(`Aborted active upload ${t} for job ${e}`)}).pipe(r.Effect.catchAll(e=>r.Effect.gen(function*(){return yield*r.Effect.logWarning(`Failed to abort active upload ${t}: ${e}`),r.Effect.succeed(void 0)})))),{concurrency:5}),yield*u(e,{activeUploads:[]})),yield*d(e,n),(yield*o.get(e))||(yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found after cancellation`})))):yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found`}))}),subscribeToFlowEvents:(e,t)=>r.Effect.gen(function*(){yield*a.subscribe(e,t)}),unsubscribeFromFlowEvents:e=>r.Effect.gen(function*(){yield*a.unsubscribe(e)})}})}const Oe=r.Layer.effect(we,De());function ke(e){let t=e.lastIndexOf(`.`);return t===-1||t===0?e:e.substring(0,t)}function Ae(e){let t=e.lastIndexOf(`.`);return t===-1||t===0?``:e.substring(t+1)}function X(e,t,n){let r=e.metadata??{},i=r.fileName??r.originalName??r.name??`unnamed`;return{baseName:ke(i),extension:Ae(i),fileName:i,nodeType:t.nodeType,nodeId:t.nodeId,flowId:t.flowId,jobId:t.jobId,timestamp:new Date().toISOString(),...n}}function je(e,t){try{let n={};for(let[e,r]of Object.entries(t))r!==void 0&&(n[e]=String(r));return(0,a.render)(e,n)}catch{return e}}function Z(e,t,n){let r=t.fileName;if(!n)return r;try{if(n.mode===`auto`){if(n.autoSuffix){let e=n.autoSuffix(t);if(e){let{baseName:n,extension:r}=t;return r?`${n}-${e}.${r}`:`${n}-${e}`}}return r}if(n.mode===`custom`){if(n.rename)return n.rename(e,t)||r;if(n.pattern)return je(n.pattern,t)||r}return r}catch{return r}}function Me(e){if(!e||e.trim()===``)return{isValid:!1,error:`Pattern cannot be empty`};let t=(e.match(/\{\{/g)||[]).length,n=(e.match(/\}\}/g)||[]).length;if(t!==n)return{isValid:!1,error:`Unbalanced braces: ${t} opening, ${n} closing`};let r=e.match(/\{\{[^}]*[^a-zA-Z0-9_}][^}]*\}\}/g);return r?{isValid:!1,error:`Invalid variable syntax: ${r[0]}`}:{isValid:!0}}const Ne=[{name:`baseName`,description:`Filename without extension`,example:`photo`},{name:`extension`,description:`File extension without dot`,example:`jpg`},{name:`fileName`,description:`Full original filename`,example:`photo.jpg`},{name:`nodeType`,description:`Type of processing node`,example:`resize`},{name:`nodeId`,description:`Specific node instance ID`,example:`resize-1`},{name:`flowId`,description:`Flow identifier`,example:`flow-abc`},{name:`jobId`,description:`Execution job ID`,example:`job-123`},{name:`timestamp`,description:`ISO 8601 processing time`,example:`2024-01-15T10:30:00Z`},{name:`width`,description:`Output width (image/video)`,example:`800`},{name:`height`,description:`Output height (image/video)`,example:`600`},{name:`format`,description:`Output format`,example:`webp`},{name:`quality`,description:`Quality setting`,example:`80`},{name:`pageNumber`,description:`Page number (documents)`,example:`1`}];function Q(e){return!(`stream`in e)}function Pe({id:t,name:i,description:a,outputTypeId:o,keepOutput:s,naming:c,nodeType:l=`transform`,nodeTypeId:u,namingVars:d,circuitBreaker:f,mode:p=`auto`,streamingConfig:m,transform:h,streamingTransform:g}){if(p===`streaming`&&!g)throw Error(`Transform node "${t}": mode is "streaming" but no streamingTransform function provided`);if(p===`buffered`&&!h)throw Error(`Transform node "${t}": mode is "buffered" but no transform function provided`);if(p===`auto`&&!h&&!g)throw Error(`Transform node "${t}": mode is "auto" but neither transform nor streamingTransform provided`);let _={...e.b,...m};return r.Effect.gen(function*(){let m=yield*n.n;return yield*C({id:t,name:i,description:a,type:S.process,outputTypeId:o,keepOutput:s,nodeTypeId:u,circuitBreaker:f,inputSchema:e.D,outputSchema:e.D,run:({data:e,storageId:n,flowId:i,jobId:a,clientId:o})=>r.Effect.gen(function*(){let s={flowId:i,nodeId:t,jobId:a},u=yield*r.Effect.gen(function*(){if(p===`buffered`)return!1;if(p===`streaming`)return!0;let t=e.size??0,i=_.fileSizeThreshold;return t>0&&t<i?(yield*r.Effect.logDebug(`File ${e.id} (${t} bytes) below threshold (${i}), using buffered mode`),!1):g?(yield*m.getCapabilities(n,o)).supportsStreamingRead?(yield*r.Effect.logDebug(`File ${e.id} qualifies for streaming mode`),!0):(yield*r.Effect.logDebug(`DataStore doesn't support streaming read, using buffered mode`),!1):(yield*r.Effect.logDebug(`No streamingTransform function, using buffered mode`),!1)}),{type:f,fileName:v,metadata:y,metadataJson:b}=j(e.metadata);if(u&&g){yield*r.Effect.logDebug(`Using streaming transform for ${e.id}`);let u=yield*g(yield*m.readStream(e.id,o,_),e),p=Q(u)?u:u.stream,h=Q(u)?void 0:u.type,x=Q(u)?void 0:u.estimatedSize,S=Q(u)?void 0:u.fileName;!S&&c&&(S=Z(e,X(e,{flowId:i,jobId:a,nodeId:t,nodeType:l},d),c));let C=yield*m.getCapabilities(n,o),w;if(C.supportsStreamingWrite)yield*r.Effect.logDebug(`Using streaming write for ${e.id} - no intermediate buffering`),w=yield*m.uploadStream({storageId:n,uploadLengthDeferred:!0,sizeHint:x,type:h??f,fileName:S??v,lastModified:0,metadata:b,flow:s},o,p);else{yield*r.Effect.logDebug(`Falling back to buffered upload for ${e.id} (streaming write not supported)`);let t=[];yield*r.Stream.runForEach(p,e=>r.Effect.sync(()=>{t.push(e)}));let i=t.reduce((e,t)=>e+t.byteLength,0),a=new Uint8Array(i),c=0;for(let e of t)a.set(e,c),c+=e.byteLength;let l=new ReadableStream({start(e){e.enqueue(a),e.close()}});w=yield*m.upload({storageId:n,size:a.byteLength,type:h??f,fileName:S??v,lastModified:0,metadata:b,flow:s},o,l)}let T=y?{...y,...h&&{mimeType:h,type:h,"content-type":h},...S&&{fileName:S,originalName:S,name:S,extension:S.split(`.`).pop()||y.extension}}:w.metadata;return O(T?{...w,metadata:T}:w)}if(!h)throw Error(`Transform node "${t}": buffered mode selected but no transform function provided`);let x=yield*h(yield*m.read(e.id,o),e),S=x instanceof Uint8Array?x:x.bytes,C=x instanceof Uint8Array?void 0:x.type,w=x instanceof Uint8Array?void 0:x.fileName,T=x instanceof Uint8Array?void 0:x.metadata;!w&&c&&(w=Z(e,X(e,{flowId:i,jobId:a,nodeId:t,nodeType:l},d),c));let E=new ReadableStream({start(e){e.enqueue(S),e.close()}}),D=yield*m.upload({storageId:n,size:S.byteLength,type:C??f,fileName:w??v,lastModified:0,metadata:b,flow:s},o,E),k=y?{...y,...T,...C&&{mimeType:C,type:C,"content-type":C},...w&&{fileName:w,originalName:w,name:w,extension:w.split(`.`).pop()||y.extension}}:D.metadata;return O(k?{...D,metadata:k}:D)})})})}var Fe=class extends r.Context.Tag(`CredentialProvider`)(){},Ie=class extends r.Context.Tag(`DocumentAiPlugin`)(){},Le=class extends r.Context.Tag(`DocumentPlugin`)(){},Re=class extends r.Context.Tag(`ImageAiPlugin`)(){},ze=class extends r.Context.Tag(`ImagePlugin`)(){};const Be=i.z.object({serviceType:i.z.enum([`replicate`]).optional()}),Ve=i.z.object({duration:i.z.number().nonnegative(),width:i.z.number().positive(),height:i.z.number().positive(),codec:i.z.string(),format:i.z.string(),bitrate:i.z.number().nonnegative(),frameRate:i.z.number().positive(),aspectRatio:i.z.string(),hasAudio:i.z.boolean(),audioCodec:i.z.string().optional(),audioBitrate:i.z.number().nonnegative().optional(),size:i.z.number().nonnegative()}),He=i.z.object({timestamp:i.z.number().nonnegative(),format:i.z.enum([`png`,`jpeg`]).optional(),quality:i.z.number().min(1).max(100).optional()}),Ue=i.z.object({quality:i.z.number().min(0).max(100),format:i.z.enum([`jpeg`,`webp`,`png`,`avif`])}),We=i.z.object({serviceType:i.z.enum([`replicate`]).optional()}),Ge=i.z.object({width:i.z.number().positive().optional(),height:i.z.number().positive().optional(),fit:i.z.enum([`contain`,`cover`,`fill`])}).refine(e=>e.width||e.height,`Either width or height must be specified for resize`),Ke=i.z.object({width:i.z.number().positive().optional(),height:i.z.number().positive().optional(),aspectRatio:i.z.enum([`keep`,`ignore`]).optional(),scaling:i.z.enum([`bicubic`,`bilinear`,`lanczos`]).optional()}).refine(e=>e.width||e.height,`Either width or height must be specified for video resize`),qe=i.z.object({format:i.z.enum([`mp4`,`webm`,`mov`,`avi`]),codec:i.z.enum([`h264`,`h265`,`vp9`,`av1`]).optional(),videoBitrate:i.z.string().optional(),audioBitrate:i.z.string().optional(),audioCodec:i.z.enum([`aac`,`mp3`,`opus`,`vorbis`]).optional()}),Je=i.z.object({type:i.z.literal(`resize`),width:i.z.number().positive().optional(),height:i.z.number().positive().optional(),fit:i.z.enum([`contain`,`cover`,`fill`])}),Ye=i.z.object({type:i.z.literal(`blur`),sigma:i.z.number().min(.3).max(1e3)}),Xe=i.z.object({type:i.z.literal(`rotate`),angle:i.z.number(),background:i.z.string().optional()}),Ze=i.z.object({type:i.z.literal(`flip`),direction:i.z.enum([`horizontal`,`vertical`])}),Qe=i.z.object({type:i.z.literal(`grayscale`)}),$e=i.z.object({type:i.z.literal(`sepia`)}),et=i.z.object({type:i.z.literal(`brightness`),value:i.z.number().min(-100).max(100)}),tt=i.z.object({type:i.z.literal(`contrast`),value:i.z.number().min(-100).max(100)}),$=i.z.object({type:i.z.literal(`sharpen`),sigma:i.z.number().positive().optional()}),nt=i.z.object({type:i.z.literal(`watermark`),imagePath:i.z.string().min(1).url(),position:i.z.enum([`top-left`,`top-right`,`bottom-left`,`bottom-right`,`center`]),opacity:i.z.number().min(0).max(1),offsetX:i.z.number().optional(),offsetY:i.z.number().optional()}),rt=i.z.object({type:i.z.literal(`logo`),imagePath:i.z.string().min(1).url(),position:i.z.enum([`top-left`,`top-right`,`bottom-left`,`bottom-right`,`center`]),scale:i.z.number().min(.1).max(2),offsetX:i.z.number().optional(),offsetY:i.z.number().optional()}),it=i.z.object({type:i.z.literal(`text`),text:i.z.string().min(1),position:i.z.enum([`top-left`,`top-right`,`bottom-left`,`bottom-right`,`center`]),fontSize:i.z.number().positive(),color:i.z.string().min(1),fontFamily:i.z.string().optional(),offsetX:i.z.number().optional(),offsetY:i.z.number().optional()}),at=i.z.discriminatedUnion(`type`,[Je,Ye,Xe,Ze,Qe,$e,et,tt,$,nt,rt,it]),ot=i.z.object({transformations:i.z.array(at).min(1)}),st=i.z.object({startTime:i.z.number().nonnegative(),endTime:i.z.number().positive().optional(),duration:i.z.number().positive().optional()}).refine(e=>!e.endTime||!e.duration,`Cannot specify both endTime and duration`).refine(e=>!e.endTime||e.endTime>e.startTime,`endTime must be greater than startTime`);var ct=class extends r.Context.Tag(`VideoPlugin`)(){},lt=class extends r.Context.Tag(`VirusScanPlugin`)(){},ut=class extends r.Context.Tag(`ZipPlugin`)(){};const dt=(e,t)=>{if(e.length===0)return t;let[n,...r]=e;return r.reduce((e,t)=>i.z.union([e,t]),n)};function ft(e){return r.Effect.gen(function*(){let n=Object.entries(e.nodes),a=e=>r.Effect.isEffect(e)?e:r.Effect.succeed(e),o=yield*r.Effect.forEach(n,([e,n])=>r.Effect.flatMap(a(n),n=>n.id===e?r.Effect.succeed([e,n]):r.Effect.fail(t.n.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Node key ${e} does not match node id ${n.id}`)})))),s=Object.fromEntries(o),c=o.map(([,e])=>e),l=o.filter(([,e])=>e.type===S.input).map(([,e])=>e.inputSchema),u=e.edges.map(e=>({source:s[e.source]?.id??e.source,target:s[e.target]?.id??e.target,sourcePort:e.sourcePort,targetPort:e.targetPort})),d=new Set(o.map(([e])=>s[e]?.id).filter(e=>e&&!u.some(t=>t.source===e))),f=o.filter(([,e])=>d.has(e.id)||e.keepOutput===!0).map(([,e])=>e.outputSchema),p=e.inputSchema??dt(l,i.z.unknown()),m=e.outputSchema??dt(f,i.z.unknown());return yield*q({flowId:e.flowId,name:e.name,nodes:c,edges:u,inputSchema:p,outputSchema:m,typeChecker:e.typeChecker,onEvent:e.onEvent,parallelExecution:e.parallelExecution,hooks:e.hooks,circuitBreaker:e.circuitBreaker})})}const pt=i.z.object({inputs:i.z.record(i.z.string(),i.z.any())});Object.defineProperty(exports,`$`,{enumerable:!0,get:function(){return he}}),Object.defineProperty(exports,`A`,{enumerable:!0,get:function(){return Re}}),Object.defineProperty(exports,`At`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,`B`,{enumerable:!0,get:function(){return je}}),Object.defineProperty(exports,`Bt`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return Ge}}),Object.defineProperty(exports,`Ct`,{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return Ve}}),Object.defineProperty(exports,`Dt`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return He}}),Object.defineProperty(exports,`Et`,{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,`F`,{enumerable:!0,get:function(){return Ne}}),Object.defineProperty(exports,`Ft`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`G`,{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,`Gt`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`H`,{enumerable:!0,get:function(){return we}}),Object.defineProperty(exports,`Ht`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`I`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`It`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,`J`,{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,`Jt`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`K`,{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,`Kt`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`L`,{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,`Lt`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,`Mt`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`N`,{enumerable:!0,get:function(){return Fe}}),Object.defineProperty(exports,`Nt`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return Be}}),Object.defineProperty(exports,`Ot`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`P`,{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(exports,`Pt`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`Q`,{enumerable:!0,get:function(){return me}}),Object.defineProperty(exports,`R`,{enumerable:!0,get:function(){return ke}}),Object.defineProperty(exports,`Rt`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return Ke}}),Object.defineProperty(exports,`St`,{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return Ue}}),Object.defineProperty(exports,`Tt`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`U`,{enumerable:!0,get:function(){return Se}}),Object.defineProperty(exports,`Ut`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`V`,{enumerable:!0,get:function(){return Me}}),Object.defineProperty(exports,`Vt`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,`W`,{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,`Wt`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`X`,{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,`Xt`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`Y`,{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,`Yt`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,`Z`,{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return it}}),Object.defineProperty(exports,`_t`,{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return ct}}),Object.defineProperty(exports,`at`,{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return nt}}),Object.defineProperty(exports,`bt`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return et}}),Object.defineProperty(exports,`ct`,{enumerable:!0,get:function(){return be}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return Qe}}),Object.defineProperty(exports,`dt`,{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,`et`,{enumerable:!0,get:function(){return pe}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return rt}}),Object.defineProperty(exports,`ft`,{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,`gt`,{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return $e}}),Object.defineProperty(exports,`ht`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return lt}}),Object.defineProperty(exports,`it`,{enumerable:!0,get:function(){return _e}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return Le}}),Object.defineProperty(exports,`jt`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return ze}}),Object.defineProperty(exports,`kt`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return tt}}),Object.defineProperty(exports,`lt`,{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return Xe}}),Object.defineProperty(exports,`mt`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return ft}}),Object.defineProperty(exports,`nt`,{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return st}}),Object.defineProperty(exports,`ot`,{enumerable:!0,get:function(){return ue}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return Je}}),Object.defineProperty(exports,`pt`,{enumerable:!0,get:function(){return le}}),Object.defineProperty(exports,`q`,{enumerable:!0,get:function(){return Oe}}),Object.defineProperty(exports,`qt`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return ut}}),Object.defineProperty(exports,`rt`,{enumerable:!0,get:function(){return fe}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return Ye}}),Object.defineProperty(exports,`st`,{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return pt}}),Object.defineProperty(exports,`tt`,{enumerable:!0,get:function(){return ge}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return Ze}}),Object.defineProperty(exports,`ut`,{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return ot}}),Object.defineProperty(exports,`vt`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return We}}),Object.defineProperty(exports,`wt`,{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return qe}}),Object.defineProperty(exports,`xt`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return at}}),Object.defineProperty(exports,`yt`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`z`,{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(exports,`zt`,{enumerable:!0,get:function(){return g}});
@@ -33,4 +33,4 @@ declare const StreamLimiterEffect: {
33
33
  };
34
34
  //#endregion
35
35
  export { streamLimiter as n, StreamLimiterEffect as t };
36
- //# sourceMappingURL=index-CvOB2TdS.d.cts.map
36
+ //# sourceMappingURL=stream-limiter-BCFULdAM.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-limiter-BCFULdAM.d.cts","names":[],"sources":["../src/streams/stream-limiter.ts"],"mappings":";;;;KAGK,oBAAA;EACH,OAAA;EACA,MAAA,IAAU,SAAA;AAAA;AAAA,iBAGI,aAAA,CAAA;EACd,OAAA;EACA;AAAA,GACC,oBAAA,GAAuB,eAAA;;;;cAqBb,mBAAA;EA3BgB;;AAG7B;;;;;;;KAgC0B,oBAAA,SAClB,MAAA,EAAQ,MAAA,CAAO,MAAA,CAAO,CAAA,EAAG,eAAA,MAAgB,MAAA,CAAA,MAAA,CAAA,CAAA,EAAA,eAAA;EA9B9C;;;;;mCA6DgC,oBAAA,KAAuB,eAAA;AAAA"}
@@ -1,4 +1,4 @@
1
- import { n as UploadistaError } from "./uploadista-error-0FLv15ML.mjs";
1
+ import { n as UploadistaError } from "./uploadista-error-BragVhIs.mjs";
2
2
  import { Stream } from "effect";
3
3
 
4
4
  //#region src/streams/stream-limiter.d.ts
@@ -33,4 +33,4 @@ declare const StreamLimiterEffect: {
33
33
  };
34
34
  //#endregion
35
35
  export { streamLimiter as n, StreamLimiterEffect as t };
36
- //# sourceMappingURL=index-DI82_KcP.d.mts.map
36
+ //# sourceMappingURL=stream-limiter-Bi7OTbRp.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-limiter-Bi7OTbRp.d.mts","names":[],"sources":["../src/streams/stream-limiter.ts"],"mappings":";;;;KAGK,oBAAA;EACH,OAAA;EACA,MAAA,IAAU,SAAA;AAAA;AAAA,iBAGI,aAAA,CAAA;EACd,OAAA;EACA;AAAA,GACC,oBAAA,GAAuB,eAAA;;;;cAqBb,mBAAA;EA3BgB;;AAG7B;;;;;;;KAgC0B,oBAAA,SAClB,MAAA,EAAQ,MAAA,CAAO,MAAA,CAAO,CAAA,EAAG,eAAA,MAAgB,MAAA,CAAA,MAAA,CAAA,CAAA,EAAA,eAAA;EA9B9C;;;;;mCA6DgC,oBAAA,KAAuB,eAAA;AAAA"}
@@ -1,2 +1,2 @@
1
1
  import{n as e}from"./uploadista-error-Fsfvr2Bb.mjs";import{Effect as t,Ref as n,Stream as r}from"effect";function i({maxSize:t,onData:n}){let r=0;return new TransformStream({transform(i,a){r+=i.length,n?.(i.byteLength),r>t?a.error(e.fromCode(`ERR_MAX_SIZE_EXCEEDED`)):a.enqueue(i)}})}const a={limit:({maxSize:i,onData:a})=>o=>t.gen(function*(){let s=yield*n.make(0);return o.pipe(r.mapEffect(r=>t.gen(function*(){let t=r instanceof Uint8Array?r.byteLength:0;return yield*n.update(s,e=>e+t),a?.(t),(yield*n.get(s))>i&&(yield*e.fromCode(`ERR_MAX_SIZE_EXCEEDED`).toEffect()),r})))}).pipe(r.unwrap),createTransformStream:e=>i(e)};export{i as n,a as t};
2
- //# sourceMappingURL=stream-limiter-B6AseoKZ.mjs.map
2
+ //# sourceMappingURL=stream-limiter-CTJPEJqE.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"stream-limiter-B6AseoKZ.mjs","names":[],"sources":["../src/streams/stream-limiter.ts"],"sourcesContent":["import { Effect, Ref, Stream } from \"effect\";\nimport { UploadistaError } from \"../errors/uploadista-error\";\n\ntype StreamLimiterOptions = {\n maxSize: number;\n onData?: (chunkSize: number) => void;\n};\n\nexport function streamLimiter({\n maxSize,\n onData,\n}: StreamLimiterOptions): TransformStream {\n let currentSize = 0;\n\n return new TransformStream({\n transform(chunk, controller) {\n currentSize += chunk.length;\n\n onData?.(chunk.byteLength);\n\n if (currentSize > maxSize) {\n controller.error(UploadistaError.fromCode(\"ERR_MAX_SIZE_EXCEEDED\"));\n } else {\n controller.enqueue(chunk);\n }\n },\n });\n}\n\n/**\n * Effect-based stream limiter that restricts stream size\n */\nexport const StreamLimiterEffect = {\n /**\n * Creates an Effect-based stream limiter\n * @param maxSize - Maximum allowed stream size in bytes\n * @param onData - Optional callback for data progress tracking\n * @returns Effect stream transformation that enforces size limits\n */\n limit:\n ({ maxSize, onData }: StreamLimiterOptions) =>\n <A>(stream: Stream.Stream<A, UploadistaError>) => {\n return Effect.gen(function* () {\n const currentSize = yield* Ref.make(0);\n\n return stream.pipe(\n Stream.mapEffect((chunk) =>\n Effect.gen(function* () {\n const chunkSize =\n chunk instanceof Uint8Array ? chunk.byteLength : 0;\n yield* Ref.update(currentSize, (size) => size + chunkSize);\n\n onData?.(chunkSize);\n const size = yield* Ref.get(currentSize);\n if (size > maxSize) {\n yield* UploadistaError.fromCode(\n \"ERR_MAX_SIZE_EXCEEDED\",\n ).toEffect();\n }\n\n return chunk;\n }),\n ),\n );\n }).pipe(Stream.unwrap);\n },\n\n /**\n * Creates a legacy TransformStream-based limiter\n * @param options - Stream limiter options\n * @returns TransformStream that enforces size limits\n */\n createTransformStream: (options: StreamLimiterOptions): TransformStream =>\n streamLimiter(options),\n};\n"],"mappings":"yGAQA,SAAgB,EAAc,CAC5B,UACA,UACwC,CACxC,IAAI,EAAc,EAElB,OAAO,IAAI,gBAAgB,CACzB,UAAU,EAAO,EAAY,CAC3B,GAAe,EAAM,OAErB,IAAS,EAAM,WAAW,CAEtB,EAAc,EAChB,EAAW,MAAM,EAAgB,SAAS,wBAAwB,CAAC,CAEnE,EAAW,QAAQ,EAAM,EAG9B,CAAC,CAMJ,MAAa,EAAsB,CAOjC,OACG,CAAE,UAAS,YACR,GACK,EAAO,IAAI,WAAa,CAC7B,IAAM,EAAc,MAAO,EAAI,KAAK,EAAE,CAEtC,OAAO,EAAO,KACZ,EAAO,UAAW,GAChB,EAAO,IAAI,WAAa,CACtB,IAAM,EACJ,aAAiB,WAAa,EAAM,WAAa,EAWnD,OAVA,MAAO,EAAI,OAAO,EAAc,GAAS,EAAO,EAAU,CAE1D,IAAS,EAAU,EACN,MAAO,EAAI,IAAI,EAAY,EAC7B,IACT,MAAO,EAAgB,SACrB,wBACD,CAAC,UAAU,EAGP,GACP,CACH,CACF,EACD,CAAC,KAAK,EAAO,OAAO,CAQ1B,sBAAwB,GACtB,EAAc,EAAQ,CACzB"}
1
+ {"version":3,"file":"stream-limiter-CTJPEJqE.mjs","names":[],"sources":["../src/streams/stream-limiter.ts"],"sourcesContent":["import { Effect, Ref, Stream } from \"effect\";\nimport { UploadistaError } from \"../errors/uploadista-error\";\n\ntype StreamLimiterOptions = {\n maxSize: number;\n onData?: (chunkSize: number) => void;\n};\n\nexport function streamLimiter({\n maxSize,\n onData,\n}: StreamLimiterOptions): TransformStream {\n let currentSize = 0;\n\n return new TransformStream({\n transform(chunk, controller) {\n currentSize += chunk.length;\n\n onData?.(chunk.byteLength);\n\n if (currentSize > maxSize) {\n controller.error(UploadistaError.fromCode(\"ERR_MAX_SIZE_EXCEEDED\"));\n } else {\n controller.enqueue(chunk);\n }\n },\n });\n}\n\n/**\n * Effect-based stream limiter that restricts stream size\n */\nexport const StreamLimiterEffect = {\n /**\n * Creates an Effect-based stream limiter\n * @param maxSize - Maximum allowed stream size in bytes\n * @param onData - Optional callback for data progress tracking\n * @returns Effect stream transformation that enforces size limits\n */\n limit:\n ({ maxSize, onData }: StreamLimiterOptions) =>\n <A>(stream: Stream.Stream<A, UploadistaError>) => {\n return Effect.gen(function* () {\n const currentSize = yield* Ref.make(0);\n\n return stream.pipe(\n Stream.mapEffect((chunk) =>\n Effect.gen(function* () {\n const chunkSize =\n chunk instanceof Uint8Array ? chunk.byteLength : 0;\n yield* Ref.update(currentSize, (size) => size + chunkSize);\n\n onData?.(chunkSize);\n const size = yield* Ref.get(currentSize);\n if (size > maxSize) {\n yield* UploadistaError.fromCode(\n \"ERR_MAX_SIZE_EXCEEDED\",\n ).toEffect();\n }\n\n return chunk;\n }),\n ),\n );\n }).pipe(Stream.unwrap);\n },\n\n /**\n * Creates a legacy TransformStream-based limiter\n * @param options - Stream limiter options\n * @returns TransformStream that enforces size limits\n */\n createTransformStream: (options: StreamLimiterOptions): TransformStream =>\n streamLimiter(options),\n};\n"],"mappings":"yGAQA,SAAgB,EAAc,CAC5B,UACA,UACwC,CACxC,IAAI,EAAc,EAElB,OAAO,IAAI,gBAAgB,CACzB,UAAU,EAAO,EAAY,CAC3B,GAAe,EAAM,OAErB,IAAS,EAAM,WAAW,CAEtB,EAAc,EAChB,EAAW,MAAM,EAAgB,SAAS,wBAAwB,CAAC,CAEnE,EAAW,QAAQ,EAAM,EAG9B,CAAC,CAMJ,MAAa,EAAsB,CAOjC,OACG,CAAE,UAAS,YACR,GACK,EAAO,IAAI,WAAa,CAC7B,IAAM,EAAc,MAAO,EAAI,KAAK,EAAE,CAEtC,OAAO,EAAO,KACZ,EAAO,UAAW,GAChB,EAAO,IAAI,WAAa,CACtB,IAAM,EACJ,aAAiB,WAAa,EAAM,WAAa,EAWnD,OAVA,MAAO,EAAI,OAAO,EAAc,GAAS,EAAO,EAAU,CAE1D,IAAS,EAAU,EACN,MAAO,EAAI,IAAI,EAAY,EAC7B,IACT,MAAO,EAAgB,SACrB,wBACD,CAAC,UAAU,EAGP,GACP,CACH,CACF,EACD,CAAC,KAAK,EAAO,OAAO,CAQ1B,sBAAwB,GACtB,EAAc,EAAQ,CACzB"}
@@ -0,0 +1 @@
1
+ require(`./websocket-Avz4T8YB.cjs`);const e=require(`./uploadista-error-B-geDgi8.cjs`);let t=require(`effect`);function n({maxSize:t,onData:n}){let r=0;return new TransformStream({transform(i,a){r+=i.length,n?.(i.byteLength),r>t?a.error(e.n.fromCode(`ERR_MAX_SIZE_EXCEEDED`)):a.enqueue(i)}})}const r={limit:({maxSize:n,onData:r})=>i=>t.Effect.gen(function*(){let a=yield*t.Ref.make(0);return i.pipe(t.Stream.mapEffect(i=>t.Effect.gen(function*(){let o=i instanceof Uint8Array?i.byteLength:0;return yield*t.Ref.update(a,e=>e+o),r?.(o),(yield*t.Ref.get(a))>n&&(yield*e.n.fromCode(`ERR_MAX_SIZE_EXCEEDED`).toEffect()),i})))}).pipe(t.Stream.unwrap),createTransformStream:e=>n(e)};Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return r}});
@@ -1 +1 @@
1
- require(`../uploadista-error-BXq-EvVE.cjs`);const e=require(`../stream-limiter-DETw0BvJ.cjs`);exports.StreamLimiterEffect=e.t,exports.streamLimiter=e.n;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../uploadista-error-B-geDgi8.cjs`);const e=require(`../stream-limiter-DZ22uIqf.cjs`);exports.StreamLimiterEffect=e.t,exports.streamLimiter=e.n;
@@ -1,2 +1,2 @@
1
- import { n as streamLimiter, t as StreamLimiterEffect } from "../index-CvOB2TdS.cjs";
1
+ import { n as streamLimiter, t as StreamLimiterEffect } from "../stream-limiter-BCFULdAM.cjs";
2
2
  export { StreamLimiterEffect, streamLimiter };
@@ -1,3 +1,3 @@
1
- import "../uploadista-error-0FLv15ML.mjs";
2
- import { n as streamLimiter, t as StreamLimiterEffect } from "../index-DI82_KcP.mjs";
1
+ import "../uploadista-error-BragVhIs.mjs";
2
+ import { n as streamLimiter, t as StreamLimiterEffect } from "../stream-limiter-Bi7OTbRp.mjs";
3
3
  export { StreamLimiterEffect, streamLimiter };
@@ -1 +1 @@
1
- import"../uploadista-error-Fsfvr2Bb.mjs";import{n as e,t}from"../stream-limiter-B6AseoKZ.mjs";export{t as StreamLimiterEffect,e as streamLimiter};
1
+ import"../uploadista-error-Fsfvr2Bb.mjs";import{n as e,t}from"../stream-limiter-CTJPEJqE.mjs";export{t as StreamLimiterEffect,e as streamLimiter};
@@ -1,4 +1,4 @@
1
- const e=require(`../types-D7yTrueF.cjs`);require(`../uploadista-error-BXq-EvVE.cjs`),require(`../errors-CRm1FHHT.cjs`);const t=require(`../flow-DIxNUAi1.cjs`),n=require(`../upload--crv1pjP.cjs`);require(`../checksum-Dsr8Y9VO.cjs`),require(`../stream-limiter-DETw0BvJ.cjs`);let r=require(`effect`);const i=r.Layer.succeed(t.M,t.M.of({performOCR:(e,t,n)=>r.Effect.sync(()=>({extractedText:t.taskType===`convertToMarkdown`?`# Document Title
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../websocket-Avz4T8YB.cjs`);require(`../uploadista-error-B-geDgi8.cjs`);const t=require(`../run-args-g74p8pEZ.cjs`),n=require(`../upload-strategy-negotiator-DfiQ0Fy0.cjs`);require(`../checksum-B7RDiO7V.cjs`),require(`../stream-limiter-DZ22uIqf.cjs`),require(`../upload/index.cjs`),require(`../flow/index.cjs`);let r=require(`effect`);const i=r.Layer.succeed(t.M,t.M.of({performOCR:(e,t,n)=>r.Effect.sync(()=>({extractedText:t.taskType===`convertToMarkdown`?`# Document Title
2
2
 
3
3
  This is a paragraph with **bold** text.
4
4
 
@@ -1,4 +1,4 @@
1
- import { $ as VideoPlugin, G as ZipPlugin, Qt as ImageAiPlugin, X as VirusScanPlugin, Zn as UploadEngine, ln as DocumentAiPlugin, mt as ImagePlugin, nn as DocumentPlugin } from "../index-DWslhr-b.cjs";
1
+ import { $ as VideoPlugin, G as ZipPlugin, Qn as UploadEngine, Qt as ImageAiPlugin, X as VirusScanPlugin, ln as DocumentAiPlugin, mt as ImagePlugin, nn as DocumentPlugin } from "../resolve-upload-metadata-BUVl1LoS.cjs";
2
2
  import { Layer } from "effect";
3
3
 
4
4
  //#region src/testing/mock-document-ai-plugin.d.ts
@@ -1,8 +1,9 @@
1
- import "../uploadista-error-0FLv15ML.mjs";
2
- import "../index-9iG2qHLe.mjs";
3
- import { $ as VideoPlugin, G as ZipPlugin, Qt as ImageAiPlugin, X as VirusScanPlugin, Zn as UploadEngine, ln as DocumentAiPlugin, mt as ImagePlugin, nn as DocumentPlugin } from "../index-fXTlZ4bM.mjs";
4
- import "../index-rhZqO0Ve.mjs";
5
- import "../index-DI82_KcP.mjs";
1
+ import "../uploadista-error-BragVhIs.mjs";
2
+ import { $ as VideoPlugin, G as ZipPlugin, Qn as UploadEngine, Qt as ImageAiPlugin, X as VirusScanPlugin, ln as DocumentAiPlugin, mt as ImagePlugin, nn as DocumentPlugin } from "../resolve-upload-metadata-MPDmDfOZ.mjs";
3
+ import "../throttle-ibiT6E4U.mjs";
4
+ import "../upload/index.mjs";
5
+ import "../stream-limiter-Bi7OTbRp.mjs";
6
+ import "../flow/index.mjs";
6
7
  import { Layer } from "effect";
7
8
 
8
9
  //#region src/testing/mock-document-ai-plugin.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/testing/mock-document-ai-plugin.ts","../../src/testing/mock-document-plugin.ts","../../src/testing/mock-image-ai-plugin.ts","../../src/testing/mock-image-plugin.ts","../../src/testing/mock-upload-engine.ts","../../src/testing/mock-video-plugin.ts","../../src/testing/mock-virus-scan-plugin.ts","../../src/testing/mock-zip-plugin.ts"],"mappings":";;;;;;;;;;;;;;AAwBA;;;;;;;;;;;;ACJA;;cDIa,oBAAA,EAAoB,KAAA,CAAA,KAAA,CAAA,gBAAA;;;;;;;;;AAAjC;;;;;;;;;;cCJa,kBAAA,EAAkB,KAAA,CAAA,KAAA,CAAA,cAAA;;;;;;;;;ADI/B;;;;;;;;;;;cEJa,iBAAA,EAAiB,KAAA,CAAA,KAAA,CAAA,aAAA;;;;;;;;;AFI9B;;;;;;;;;;;cGJa,eAAA,EAAe,KAAA,CAAA,KAAA,CAAA,WAAA;;;;;;;;;AHI5B;;;;;;;;;;;cIUa,gBAAA,EAAgB,KAAA,CAAA,KAAA,CAAA,YAAA;;;;;;;;;AJV7B;;;;;;;;;;;cKHa,eAAA,EAAe,KAAA,CAAA,KAAA,CAAA,WAAA;;;;;;;;;ALG5B;;;;;;;;;;;;ACJA;cKSa,mBAAA,EAAmB,KAAA,CAAA,KAAA,CAAA,eAAA;;;;;;;;;ANLhC;;;;;;;;;;;cOJa,aAAA,EAAa,KAAA,CAAA,KAAA,CAAA,SAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/testing/mock-document-ai-plugin.ts","../../src/testing/mock-document-plugin.ts","../../src/testing/mock-image-ai-plugin.ts","../../src/testing/mock-image-plugin.ts","../../src/testing/mock-upload-engine.ts","../../src/testing/mock-video-plugin.ts","../../src/testing/mock-virus-scan-plugin.ts","../../src/testing/mock-zip-plugin.ts"],"mappings":";;;;;;;;;;;;;;;;AAwBA;;;;;;;;;;;;ACJA;cDIa,oBAAA,EAAoB,KAAA,CAAA,KAAA,CAAA,gBAAA;;;;;;;;;;AAAjC;;;;;;;;;cCJa,kBAAA,EAAkB,KAAA,CAAA,KAAA,CAAA,cAAA;;;;;;;;;;ADI/B;;;;;;;;;;cEJa,iBAAA,EAAiB,KAAA,CAAA,KAAA,CAAA,aAAA;;;;;;;;;;AFI9B;;;;;;;;;;cGJa,eAAA,EAAe,KAAA,CAAA,KAAA,CAAA,WAAA;;;;;;;;;;AHI5B;;;;;;;;;;cIUa,gBAAA,EAAgB,KAAA,CAAA,KAAA,CAAA,YAAA;;;;;;;;;;AJV7B;;;;;;;;;;cKHa,eAAA,EAAe,KAAA,CAAA,KAAA,CAAA,WAAA;;;;;;;;;;ALG5B;;;;;;;;;;;;cMKa,mBAAA,EAAmB,KAAA,CAAA,KAAA,CAAA,eAAA;;;;;;;;;;ANLhC;;;;;;;;;;cOJa,aAAA,EAAa,KAAA,CAAA,KAAA,CAAA,SAAA"}
@@ -1,4 +1,4 @@
1
- import"../uploadista-error-Fsfvr2Bb.mjs";import"../errors-DuxBpAc7.mjs";import{A as e,M as t,a as n,i as r,j as i,k as a,r as o}from"../flow-DeWBwvnY.mjs";import{b as s}from"../types-DkF1tvde.mjs";import{n as c}from"../upload-1FHGCe87.mjs";import"../checksum-_-9dR9Qp.mjs";import"../stream-limiter-B6AseoKZ.mjs";import{Effect as l,Layer as u,Stream as d}from"effect";const f=u.succeed(t,t.of({performOCR:(e,t,n)=>l.sync(()=>({extractedText:t.taskType===`convertToMarkdown`?`# Document Title
1
+ import"../uploadista-error-Fsfvr2Bb.mjs";import{A as e,M as t,a as n,i as r,j as i,k as a,r as o}from"../run-args-WD1otVrz.mjs";import{b as s}from"../websocket-CdgVhVJs.mjs";import{n as c}from"../upload-strategy-negotiator-BuxPf1sa.mjs";import"../checksum-BjP9nb5b.mjs";import"../stream-limiter-CTJPEJqE.mjs";import"../upload/index.mjs";import"../flow/index.mjs";import{Effect as l,Layer as u,Stream as d}from"effect";const f=u.succeed(t,t.of({performOCR:(e,t,n)=>l.sync(()=>({extractedText:t.taskType===`convertToMarkdown`?`# Document Title
2
2
 
3
3
  This is a paragraph with **bold** text.
4
4
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["EICAR_SIGNATURE"],"sources":["../../src/testing/mock-document-ai-plugin.ts","../../src/testing/mock-document-plugin.ts","../../src/testing/mock-image-ai-plugin.ts","../../src/testing/mock-image-plugin.ts","../../src/testing/mock-upload-engine.ts","../../src/testing/mock-video-plugin.ts","../../src/testing/mock-virus-scan-plugin.ts","../../src/testing/mock-zip-plugin.ts"],"sourcesContent":["import { Effect, Layer } from \"effect\";\nimport type { OcrResult } from \"../flow\";\nimport { DocumentAiPlugin } from \"../flow\";\n\n/**\n * Mock DocumentAiPlugin implementation for testing.\n *\n * Provides simple mock implementations of AI document operations.\n *\n * @example\n * ```typescript\n * import { TestDocumentAiPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* DocumentAiPlugin;\n * const result = yield* plugin.performOCR(\n * \"https://example.com/doc.pdf\",\n * { taskType: \"convertToMarkdown\", resolution: \"gundam\" },\n * { clientId: \"test-client\" }\n * );\n * return result;\n * }).pipe(Effect.provide(TestDocumentAiPlugin));\n * ```\n */\nexport const TestDocumentAiPlugin = Layer.succeed(\n DocumentAiPlugin,\n DocumentAiPlugin.of({\n performOCR: (inputUrl: string, params, context) =>\n Effect.sync(() => {\n const result: OcrResult = {\n extractedText:\n params.taskType === \"convertToMarkdown\"\n ? \"# Document Title\\n\\nThis is a paragraph with **bold** text.\\n\\n## Section 2\\n\\n- List item 1\\n- List item 2\"\n : \"Plain text extracted from document without formatting.\",\n format:\n params.taskType === \"convertToMarkdown\" ? \"markdown\" : \"plain\",\n confidence: 0.95,\n };\n return result;\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport type { DocumentMetadata, SplitPdfResult } from \"../flow\";\nimport { DocumentPlugin } from \"../flow\";\n\n/**\n * Mock DocumentPlugin implementation for testing.\n *\n * Provides simple mock implementations of PDF operations that return mock data.\n *\n * @example\n * ```typescript\n * import { TestDocumentPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* DocumentPlugin;\n * const text = yield* plugin.extractText(pdfBytes);\n * return text;\n * }).pipe(Effect.provide(TestDocumentPlugin));\n * ```\n */\nexport const TestDocumentPlugin = Layer.succeed(\n DocumentPlugin,\n DocumentPlugin.of({\n extractText: (input: Uint8Array) =>\n Effect.sync(() => {\n // Mock text extraction\n return \"This is extracted text from a PDF document.\\nPage 1 content.\";\n }),\n splitPdf: (input: Uint8Array, options) =>\n Effect.sync(() => {\n if (options.mode === \"range\") {\n // Mock range split\n const mockPdf = new Uint8Array(500).fill(80);\n return {\n mode: \"range\" as const,\n pdf: mockPdf,\n } satisfies SplitPdfResult;\n }\n // Mock individual split\n const mockPdfs = [\n new Uint8Array(200).fill(81),\n new Uint8Array(200).fill(82),\n new Uint8Array(200).fill(83),\n ];\n return {\n mode: \"individual\" as const,\n pdfs: mockPdfs,\n } satisfies SplitPdfResult;\n }),\n mergePdfs: (options) =>\n Effect.sync(() => {\n // Mock merge: combine sizes\n const totalSize = options.pdfs.reduce(\n (sum, pdf) => sum + pdf.byteLength,\n 0,\n );\n return new Uint8Array(totalSize).fill(90);\n }),\n getMetadata: (input: Uint8Array) =>\n Effect.sync(() => {\n const metadata: DocumentMetadata = {\n pageCount: 5,\n format: \"pdf\",\n author: \"Test Author\",\n title: \"Test Document\",\n subject: \"Test Subject\",\n creator: \"Test Creator\",\n creationDate: \"2024-01-01T00:00:00Z\",\n modifiedDate: \"2024-01-02T00:00:00Z\",\n fileSize: input.byteLength,\n };\n return metadata;\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ImageAiPlugin } from \"../flow\";\n\n/**\n * Mock ImageAiPlugin implementation for testing.\n *\n * Provides simple mock implementations of AI-powered image operations\n * like background removal and image description.\n *\n * @example\n * ```typescript\n * import { TestImageAiPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* ImageAiPlugin;\n * const result = yield* plugin.removeBackground(imageUrl, context);\n * return result;\n * }).pipe(Effect.provide(TestImageAiPlugin));\n * ```\n */\nexport const TestImageAiPlugin = Layer.succeed(\n ImageAiPlugin,\n ImageAiPlugin.of({\n removeBackground: (inputUrl: string, _context) =>\n Effect.sync(() => ({\n outputUrl: inputUrl.replace(\".jpg\", \"-no-bg.png\"),\n })),\n describeImage: (inputUrl: string, _context) =>\n Effect.sync(() => ({\n description: `A test image from ${inputUrl}`,\n })),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ImagePlugin } from \"../flow\";\n\n/**\n * Mock ImagePlugin implementation for testing.\n *\n * Provides simple mock implementations of image optimization, resizing,\n * and transformation operations that return mock Uint8Array data.\n *\n * @example\n * ```typescript\n * import { TestImagePlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* ImagePlugin;\n * const optimized = yield* plugin.optimize(imageBytes, { quality: 80, format: \"webp\" });\n * return optimized;\n * }).pipe(Effect.provide(TestImagePlugin));\n * ```\n */\nexport const TestImagePlugin = Layer.succeed(\n ImagePlugin,\n ImagePlugin.of({\n optimize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock optimize: return smaller array for lower quality\n const sizeMultiplier = options.quality / 100;\n const newSize = Math.floor(input.byteLength * sizeMultiplier);\n return new Uint8Array(newSize).fill(128);\n }),\n resize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock resize: return array with size based on dimensions\n const width = options.width || 800;\n const height = options.height || 600;\n const mockSize = Math.floor((width * height) / 10);\n return new Uint8Array(mockSize).fill(100);\n }),\n transform: (input: Uint8Array, transformation) =>\n Effect.sync(() => {\n // Mock transform: modify array based on transformation type\n if (transformation.type === \"rotate\" && transformation.angle === 90) {\n // For 90° rotation, swap dimensions (mock behavior)\n return new Uint8Array(input.byteLength + 10).fill(150);\n }\n if (transformation.type === \"blur\") {\n return new Uint8Array(input.byteLength).fill(180);\n }\n if (transformation.type === \"grayscale\") {\n return new Uint8Array(input.byteLength).fill(128);\n }\n // Default: return modified copy\n return new Uint8Array(input.byteLength).fill(200);\n }),\n }),\n);\n","import { Effect, Layer, Stream } from \"effect\";\nimport type { UploadistaError } from \"../errors\";\nimport type { InputFile, UploadFile, WebSocketConnection } from \"../types\";\nimport {\n type DataStoreCapabilities,\n DEFAULT_STREAMING_CONFIG,\n type StreamingConfig,\n} from \"../types/data-store\";\nimport { UploadEngine } from \"../upload\";\n\n/**\n * EICAR test file signature (standard antivirus test file)\n * This is a safe, non-malicious string used to test antivirus software\n */\nconst EICAR_SIGNATURE =\n \"X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*\";\n\n/**\n * Mock UploadEngine implementation for testing.\n *\n * Provides a complete in-memory implementation of all UploadEngine methods\n * suitable for unit and integration tests.\n *\n * @example\n * ```typescript\n * import { TestUploadEngine } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const server = yield* UploadEngine;\n * const upload = yield* server.createUpload(inputFile, \"client-123\");\n * return upload;\n * }).pipe(Effect.provide(TestUploadEngine));\n * ```\n */\nexport const TestUploadEngine = Layer.succeed(\n UploadEngine,\n UploadEngine.of({\n read: (fileId: string, _clientId: string | null) =>\n Effect.sync(() => {\n // Return infected content for files that should trigger virus detection\n // This allows tests to verify virus scanning behavior\n if (\n fileId.toLowerCase().includes(\"infected\") ||\n fileId.toLowerCase().includes(\"virus\") ||\n fileId.toLowerCase().includes(\"malware\") ||\n fileId.toLowerCase().includes(\"eicar\")\n ) {\n return new TextEncoder().encode(EICAR_SIGNATURE);\n }\n // Generate clean mock file data for other files\n const text = `Content of file ${fileId}`;\n return new TextEncoder().encode(text);\n }),\n readStream: (\n fileId: string,\n _clientId: string | null,\n config?: StreamingConfig,\n ) =>\n Effect.sync(() => {\n const effectiveConfig = { ...DEFAULT_STREAMING_CONFIG, ...config };\n // Generate mock file data based on fileId\n const text = `Content of file ${fileId}`;\n const fullData = new TextEncoder().encode(text);\n\n // Split data into chunks based on chunkSize\n const chunkSize = effectiveConfig.chunkSize;\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < fullData.length; i += chunkSize) {\n chunks.push(fullData.slice(i, i + chunkSize));\n }\n\n // Return as a stream of chunks\n return Stream.fromIterable(chunks);\n }),\n uploadStream: (\n file: Omit<InputFile, \"size\"> & { size?: number; sizeHint?: number },\n _clientId: string | null,\n stream: Stream.Stream<Uint8Array, UploadistaError>,\n ) =>\n Effect.gen(function* () {\n // Collect stream to calculate total size\n const chunks: Uint8Array[] = [];\n yield* Stream.runForEach(stream, (chunk) =>\n Effect.sync(() => {\n chunks.push(chunk);\n }),\n );\n\n const totalSize = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n\n // Parse existing metadata\n const existingMetadata =\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata || {};\n\n // Extract extension from fileName\n const extension = file.fileName\n ? file.fileName.split(\".\").pop()\n : existingMetadata.extension;\n\n // Create new UploadFile with final size\n const uploadId = `stream-uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n return {\n id: uploadId,\n offset: totalSize,\n size: totalSize,\n storage: {\n id: file.storageId,\n type: \"memory\",\n },\n metadata: {\n ...existingMetadata,\n mimeType: file.type,\n type: file.type,\n \"content-type\": file.type,\n fileName: file.fileName,\n originalName: file.fileName,\n name: file.fileName,\n extension,\n },\n url: `http://test-storage/${uploadId}`,\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n upload: (file, _clientId, stream) =>\n Effect.gen(function* () {\n // Read stream to completion\n const reader = stream.getReader();\n let totalSize = 0;\n const chunks: Uint8Array[] = [];\n\n while (true) {\n const { done, value } = yield* Effect.promise(() => reader.read());\n if (done) break;\n if (value) {\n chunks.push(value);\n totalSize += value.byteLength;\n }\n }\n\n // Parse existing metadata\n const existingMetadata =\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata || {};\n\n // Extract extension from fileName\n const extension = file.fileName\n ? file.fileName.split(\".\").pop()\n : existingMetadata.extension;\n\n // Create new UploadFile with merged metadata\n return {\n id: `uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: totalSize,\n size: totalSize,\n storage: {\n id: file.storageId,\n type: \"memory\",\n },\n metadata: {\n ...existingMetadata,\n // Update with InputFile type and fileName\n mimeType: file.type,\n type: file.type,\n \"content-type\": file.type,\n fileName: file.fileName,\n originalName: file.fileName,\n name: file.fileName,\n extension,\n },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n delete: (_fileId: string, _clientId: string | null) => Effect.void,\n createUpload: (file: InputFile, _clientId: string | null) =>\n Effect.succeed({\n id: `uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: 0,\n size: 0,\n storage: { id: file.storageId, type: \"memory\" },\n metadata:\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata,\n } satisfies UploadFile),\n uploadChunk: (\n uploadId: string,\n _clientId: string | null,\n chunk: ReadableStream,\n ) =>\n Effect.gen(function* () {\n // Read stream to completion\n const reader = chunk.getReader();\n let totalSize = 0;\n const chunks: Uint8Array[] = [];\n\n while (true) {\n const { done, value } = yield* Effect.promise(() => reader.read());\n if (done) break;\n if (value) {\n chunks.push(value);\n totalSize += value.byteLength;\n }\n }\n return {\n id: uploadId,\n offset: totalSize,\n size: totalSize,\n storage: { id: \"test-storage\", type: \"memory\" },\n metadata: { mimeType: \"application/octet-stream\", extension: \"bin\" },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n getCapabilities: (_storageId: string, _clientId: string | null) =>\n Effect.succeed({\n supportsParallelUploads: true,\n supportsConcatenation: true,\n supportsDeferredLength: true,\n supportsResumableUploads: true,\n supportsTransactionalUploads: false,\n supportsStreamingRead: true,\n supportsStreamingWrite: true,\n maxConcurrentUploads: 10,\n minChunkSize: 5 * 1024 * 1024, // 5MB\n maxChunkSize: 100 * 1024 * 1024, // 100MB\n maxParts: 10000,\n optimalChunkSize: 10 * 1024 * 1024, // 10MB\n requiresOrderedChunks: false,\n requiresMimeTypeValidation: false,\n } satisfies DataStoreCapabilities),\n uploadFromUrl: (\n inputFile: InputFile,\n _clientId: string | null,\n url: string,\n ) =>\n Effect.succeed({\n id: `uploaded-from-url-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: 0,\n size: 0,\n storage: { id: inputFile.storageId, type: \"memory\" },\n metadata:\n typeof inputFile.metadata === \"string\"\n ? JSON.parse(inputFile.metadata)\n : inputFile.metadata,\n url,\n creationDate: new Date().toISOString(),\n } satisfies UploadFile),\n getUpload: (uploadId: string) =>\n Effect.succeed({\n id: uploadId,\n offset: 0,\n size: 1024,\n storage: {\n id: \"test-storage\",\n type: \"memory\",\n },\n metadata: {\n mimeType: \"text/plain\",\n originalName: `file-${uploadId}.txt`,\n extension: \"txt\",\n },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile),\n subscribeToUploadEvents: (\n _uploadId: string,\n _connection: WebSocketConnection,\n ) => Effect.void,\n unsubscribeFromUploadEvents: (_uploadId: string) => Effect.void,\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { VideoPlugin } from \"../flow\";\nimport type { DescribeVideoMetadata } from \"../flow/plugins/types/describe-video-node\";\n\n/**\n * Mock VideoPlugin implementation for testing.\n *\n * Provides simple mock implementations of video processing operations\n * that return mock Uint8Array data without requiring FFmpeg or node-av.\n *\n * @example\n * ```typescript\n * import { TestVideoPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* VideoPlugin;\n * const transcoded = yield* plugin.transcode(videoBytes, { format: \"webm\", codec: \"vp9\" });\n * return transcoded;\n * }).pipe(Effect.provide(TestVideoPlugin));\n * ```\n */\nexport const TestVideoPlugin = Layer.succeed(\n VideoPlugin,\n VideoPlugin.of({\n describe: (input: Uint8Array) =>\n Effect.sync(() => {\n // Mock describe: return fake metadata based on input size\n const metadata: DescribeVideoMetadata = {\n duration: 120, // 2 minutes\n width: 1920,\n height: 1080,\n codec: \"h264\",\n format: \"mp4\",\n bitrate: 5000000, // 5 Mbps\n frameRate: 30,\n aspectRatio: \"16:9\",\n hasAudio: true,\n audioCodec: \"aac\",\n audioBitrate: 128000, // 128 kbps\n size: input.byteLength,\n };\n return metadata;\n }),\n transcode: (_input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock transcode: return modified array\n // Simulate different file sizes for different codecs\n let sizeMultiplier = 1.0;\n if (options.codec === \"vp9\") {\n sizeMultiplier = 0.8; // VP9 is more efficient\n } else if (options.codec === \"h265\") {\n sizeMultiplier = 0.7; // H265 is even more efficient\n }\n\n const newSize = Math.floor(_input.byteLength * sizeMultiplier);\n return new Uint8Array(newSize).fill(42);\n }),\n resize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock resize: return array with size based on dimensions\n const width = options.width || 1280;\n const height = options.height || 720;\n // Simulate file size roughly proportional to resolution\n const mockSize = Math.floor((width * height) / 50);\n return new Uint8Array(mockSize).fill(84);\n }),\n trim: (_input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock trim: return smaller array based on duration\n let duration: number;\n if (options.duration !== undefined) {\n duration = options.duration;\n } else if (options.endTime !== undefined) {\n duration = options.endTime - options.startTime;\n } else {\n // Assume 120s total duration\n duration = 120 - options.startTime;\n }\n\n // Simulate proportional file size based on duration\n const ratio = duration / 120; // Assuming 120s original\n const newSize = Math.floor(_input.byteLength * ratio);\n return new Uint8Array(newSize).fill(63);\n }),\n extractFrame: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock extractFrame: return image bytes (smaller than video)\n const format = options.format || \"jpeg\";\n // JPEG typically smaller than PNG\n const mockSize = format === \"png\" ? 50000 : 30000;\n return new Uint8Array(mockSize).fill(255);\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { VirusScanPlugin } from \"../flow\";\n\n/**\n * EICAR test file signature (standard antivirus test file)\n * This is a safe, non-malicious string used to test antivirus software\n */\nconst EICAR_SIGNATURE =\n \"X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*\";\n\n/**\n * Mock VirusScanPlugin implementation for testing.\n *\n * Provides a simple mock implementation that:\n * - Detects the EICAR test signature as infected\n * - Treats all other files as clean\n * - Returns mock version information\n *\n * @example\n * ```typescript\n * import { TestVirusScanPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* VirusScanPlugin;\n * const result = yield* plugin.scan(fileBytes);\n * console.log(result.isClean ? \"Clean\" : \"Infected\");\n * }).pipe(Effect.provide(TestVirusScanPlugin));\n * ```\n */\nexport const TestVirusScanPlugin = Layer.succeed(\n VirusScanPlugin,\n VirusScanPlugin.of({\n scan: (input: Uint8Array) =>\n Effect.sync(() => {\n // Convert bytes to string to check for EICAR signature\n const textDecoder = new TextDecoder();\n const content = textDecoder.decode(input);\n\n // Check if file contains EICAR test signature\n if (content.includes(EICAR_SIGNATURE)) {\n return {\n isClean: false,\n detectedViruses: [\"EICAR-Test-File\"],\n };\n }\n\n // All other files are considered clean\n return {\n isClean: true,\n detectedViruses: [],\n };\n }),\n getVersion: () =>\n Effect.sync(() => {\n return \"TestVirusScanPlugin 1.0.0\";\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ZipPlugin } from \"../flow\";\n\n/**\n * Mock ZipPlugin implementation for testing.\n *\n * Provides a simple in-memory implementation that creates mock zip data\n * by serializing file metadata as JSON.\n *\n * @example\n * ```typescript\n * import { TestZipPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const zipPlugin = yield* ZipPlugin;\n * const zipData = yield* zipPlugin.zip(inputs, options);\n * return zipData;\n * }).pipe(Effect.provide(TestZipPlugin));\n * ```\n */\nexport const TestZipPlugin = Layer.succeed(\n ZipPlugin,\n ZipPlugin.of({\n zip: (inputs, options) =>\n Effect.gen(function* () {\n // Create mock zip data\n const files = inputs.map((input) => ({\n id: input.id,\n size: input.data.byteLength,\n }));\n\n const zipContent = JSON.stringify({\n zipName: options.zipName,\n includeMetadata: options.includeMetadata,\n files,\n });\n\n return new TextEncoder().encode(zipContent);\n }),\n }),\n);\n"],"mappings":"+WAwBA,MAAa,EAAuB,EAAM,QACxC,EACA,EAAiB,GAAG,CAClB,YAAa,EAAkB,EAAQ,IACrC,EAAO,UACqB,CACxB,cACE,EAAO,WAAa,oBAChB;;;;;;;eACA,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-document-ai-plugin.ts","../../src/testing/mock-document-plugin.ts","../../src/testing/mock-image-ai-plugin.ts","../../src/testing/mock-image-plugin.ts","../../src/testing/mock-upload-engine.ts","../../src/testing/mock-video-plugin.ts","../../src/testing/mock-virus-scan-plugin.ts","../../src/testing/mock-zip-plugin.ts"],"sourcesContent":["import { Effect, Layer } from \"effect\";\nimport type { OcrResult } from \"../flow\";\nimport { DocumentAiPlugin } from \"../flow\";\n\n/**\n * Mock DocumentAiPlugin implementation for testing.\n *\n * Provides simple mock implementations of AI document operations.\n *\n * @example\n * ```typescript\n * import { TestDocumentAiPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* DocumentAiPlugin;\n * const result = yield* plugin.performOCR(\n * \"https://example.com/doc.pdf\",\n * { taskType: \"convertToMarkdown\", resolution: \"gundam\" },\n * { clientId: \"test-client\" }\n * );\n * return result;\n * }).pipe(Effect.provide(TestDocumentAiPlugin));\n * ```\n */\nexport const TestDocumentAiPlugin = Layer.succeed(\n DocumentAiPlugin,\n DocumentAiPlugin.of({\n performOCR: (inputUrl: string, params, context) =>\n Effect.sync(() => {\n const result: OcrResult = {\n extractedText:\n params.taskType === \"convertToMarkdown\"\n ? \"# Document Title\\n\\nThis is a paragraph with **bold** text.\\n\\n## Section 2\\n\\n- List item 1\\n- List item 2\"\n : \"Plain text extracted from document without formatting.\",\n format:\n params.taskType === \"convertToMarkdown\" ? \"markdown\" : \"plain\",\n confidence: 0.95,\n };\n return result;\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport type { DocumentMetadata, SplitPdfResult } from \"../flow\";\nimport { DocumentPlugin } from \"../flow\";\n\n/**\n * Mock DocumentPlugin implementation for testing.\n *\n * Provides simple mock implementations of PDF operations that return mock data.\n *\n * @example\n * ```typescript\n * import { TestDocumentPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* DocumentPlugin;\n * const text = yield* plugin.extractText(pdfBytes);\n * return text;\n * }).pipe(Effect.provide(TestDocumentPlugin));\n * ```\n */\nexport const TestDocumentPlugin = Layer.succeed(\n DocumentPlugin,\n DocumentPlugin.of({\n extractText: (input: Uint8Array) =>\n Effect.sync(() => {\n // Mock text extraction\n return \"This is extracted text from a PDF document.\\nPage 1 content.\";\n }),\n splitPdf: (input: Uint8Array, options) =>\n Effect.sync(() => {\n if (options.mode === \"range\") {\n // Mock range split\n const mockPdf = new Uint8Array(500).fill(80);\n return {\n mode: \"range\" as const,\n pdf: mockPdf,\n } satisfies SplitPdfResult;\n }\n // Mock individual split\n const mockPdfs = [\n new Uint8Array(200).fill(81),\n new Uint8Array(200).fill(82),\n new Uint8Array(200).fill(83),\n ];\n return {\n mode: \"individual\" as const,\n pdfs: mockPdfs,\n } satisfies SplitPdfResult;\n }),\n mergePdfs: (options) =>\n Effect.sync(() => {\n // Mock merge: combine sizes\n const totalSize = options.pdfs.reduce(\n (sum, pdf) => sum + pdf.byteLength,\n 0,\n );\n return new Uint8Array(totalSize).fill(90);\n }),\n getMetadata: (input: Uint8Array) =>\n Effect.sync(() => {\n const metadata: DocumentMetadata = {\n pageCount: 5,\n format: \"pdf\",\n author: \"Test Author\",\n title: \"Test Document\",\n subject: \"Test Subject\",\n creator: \"Test Creator\",\n creationDate: \"2024-01-01T00:00:00Z\",\n modifiedDate: \"2024-01-02T00:00:00Z\",\n fileSize: input.byteLength,\n };\n return metadata;\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ImageAiPlugin } from \"../flow\";\n\n/**\n * Mock ImageAiPlugin implementation for testing.\n *\n * Provides simple mock implementations of AI-powered image operations\n * like background removal and image description.\n *\n * @example\n * ```typescript\n * import { TestImageAiPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* ImageAiPlugin;\n * const result = yield* plugin.removeBackground(imageUrl, context);\n * return result;\n * }).pipe(Effect.provide(TestImageAiPlugin));\n * ```\n */\nexport const TestImageAiPlugin = Layer.succeed(\n ImageAiPlugin,\n ImageAiPlugin.of({\n removeBackground: (inputUrl: string, _context) =>\n Effect.sync(() => ({\n outputUrl: inputUrl.replace(\".jpg\", \"-no-bg.png\"),\n })),\n describeImage: (inputUrl: string, _context) =>\n Effect.sync(() => ({\n description: `A test image from ${inputUrl}`,\n })),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ImagePlugin } from \"../flow\";\n\n/**\n * Mock ImagePlugin implementation for testing.\n *\n * Provides simple mock implementations of image optimization, resizing,\n * and transformation operations that return mock Uint8Array data.\n *\n * @example\n * ```typescript\n * import { TestImagePlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* ImagePlugin;\n * const optimized = yield* plugin.optimize(imageBytes, { quality: 80, format: \"webp\" });\n * return optimized;\n * }).pipe(Effect.provide(TestImagePlugin));\n * ```\n */\nexport const TestImagePlugin = Layer.succeed(\n ImagePlugin,\n ImagePlugin.of({\n optimize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock optimize: return smaller array for lower quality\n const sizeMultiplier = options.quality / 100;\n const newSize = Math.floor(input.byteLength * sizeMultiplier);\n return new Uint8Array(newSize).fill(128);\n }),\n resize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock resize: return array with size based on dimensions\n const width = options.width || 800;\n const height = options.height || 600;\n const mockSize = Math.floor((width * height) / 10);\n return new Uint8Array(mockSize).fill(100);\n }),\n transform: (input: Uint8Array, transformation) =>\n Effect.sync(() => {\n // Mock transform: modify array based on transformation type\n if (transformation.type === \"rotate\" && transformation.angle === 90) {\n // For 90° rotation, swap dimensions (mock behavior)\n return new Uint8Array(input.byteLength + 10).fill(150);\n }\n if (transformation.type === \"blur\") {\n return new Uint8Array(input.byteLength).fill(180);\n }\n if (transformation.type === \"grayscale\") {\n return new Uint8Array(input.byteLength).fill(128);\n }\n // Default: return modified copy\n return new Uint8Array(input.byteLength).fill(200);\n }),\n }),\n);\n","import { Effect, Layer, Stream } from \"effect\";\nimport type { UploadistaError } from \"../errors\";\nimport type { InputFile, UploadFile, WebSocketConnection } from \"../types\";\nimport {\n type DataStoreCapabilities,\n DEFAULT_STREAMING_CONFIG,\n type StreamingConfig,\n} from \"../types/data-store\";\nimport { UploadEngine } from \"../upload\";\n\n/**\n * EICAR test file signature (standard antivirus test file)\n * This is a safe, non-malicious string used to test antivirus software\n */\nconst EICAR_SIGNATURE =\n \"X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*\";\n\n/**\n * Mock UploadEngine implementation for testing.\n *\n * Provides a complete in-memory implementation of all UploadEngine methods\n * suitable for unit and integration tests.\n *\n * @example\n * ```typescript\n * import { TestUploadEngine } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const server = yield* UploadEngine;\n * const upload = yield* server.createUpload(inputFile, \"client-123\");\n * return upload;\n * }).pipe(Effect.provide(TestUploadEngine));\n * ```\n */\nexport const TestUploadEngine = Layer.succeed(\n UploadEngine,\n UploadEngine.of({\n read: (fileId: string, _clientId: string | null) =>\n Effect.sync(() => {\n // Return infected content for files that should trigger virus detection\n // This allows tests to verify virus scanning behavior\n if (\n fileId.toLowerCase().includes(\"infected\") ||\n fileId.toLowerCase().includes(\"virus\") ||\n fileId.toLowerCase().includes(\"malware\") ||\n fileId.toLowerCase().includes(\"eicar\")\n ) {\n return new TextEncoder().encode(EICAR_SIGNATURE);\n }\n // Generate clean mock file data for other files\n const text = `Content of file ${fileId}`;\n return new TextEncoder().encode(text);\n }),\n readStream: (\n fileId: string,\n _clientId: string | null,\n config?: StreamingConfig,\n ) =>\n Effect.sync(() => {\n const effectiveConfig = { ...DEFAULT_STREAMING_CONFIG, ...config };\n // Generate mock file data based on fileId\n const text = `Content of file ${fileId}`;\n const fullData = new TextEncoder().encode(text);\n\n // Split data into chunks based on chunkSize\n const chunkSize = effectiveConfig.chunkSize;\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < fullData.length; i += chunkSize) {\n chunks.push(fullData.slice(i, i + chunkSize));\n }\n\n // Return as a stream of chunks\n return Stream.fromIterable(chunks);\n }),\n uploadStream: (\n file: Omit<InputFile, \"size\"> & { size?: number; sizeHint?: number },\n _clientId: string | null,\n stream: Stream.Stream<Uint8Array, UploadistaError>,\n ) =>\n Effect.gen(function* () {\n // Collect stream to calculate total size\n const chunks: Uint8Array[] = [];\n yield* Stream.runForEach(stream, (chunk) =>\n Effect.sync(() => {\n chunks.push(chunk);\n }),\n );\n\n const totalSize = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n\n // Parse existing metadata\n const existingMetadata =\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata || {};\n\n // Extract extension from fileName\n const extension = file.fileName\n ? file.fileName.split(\".\").pop()\n : existingMetadata.extension;\n\n // Create new UploadFile with final size\n const uploadId = `stream-uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n return {\n id: uploadId,\n offset: totalSize,\n size: totalSize,\n storage: {\n id: file.storageId,\n type: \"memory\",\n },\n metadata: {\n ...existingMetadata,\n mimeType: file.type,\n type: file.type,\n \"content-type\": file.type,\n fileName: file.fileName,\n originalName: file.fileName,\n name: file.fileName,\n extension,\n },\n url: `http://test-storage/${uploadId}`,\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n upload: (file, _clientId, stream) =>\n Effect.gen(function* () {\n // Read stream to completion\n const reader = stream.getReader();\n let totalSize = 0;\n const chunks: Uint8Array[] = [];\n\n while (true) {\n const { done, value } = yield* Effect.promise(() => reader.read());\n if (done) break;\n if (value) {\n chunks.push(value);\n totalSize += value.byteLength;\n }\n }\n\n // Parse existing metadata\n const existingMetadata =\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata || {};\n\n // Extract extension from fileName\n const extension = file.fileName\n ? file.fileName.split(\".\").pop()\n : existingMetadata.extension;\n\n // Create new UploadFile with merged metadata\n return {\n id: `uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: totalSize,\n size: totalSize,\n storage: {\n id: file.storageId,\n type: \"memory\",\n },\n metadata: {\n ...existingMetadata,\n // Update with InputFile type and fileName\n mimeType: file.type,\n type: file.type,\n \"content-type\": file.type,\n fileName: file.fileName,\n originalName: file.fileName,\n name: file.fileName,\n extension,\n },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n delete: (_fileId: string, _clientId: string | null) => Effect.void,\n createUpload: (file: InputFile, _clientId: string | null) =>\n Effect.succeed({\n id: `uploaded-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: 0,\n size: 0,\n storage: { id: file.storageId, type: \"memory\" },\n metadata:\n typeof file.metadata === \"string\"\n ? JSON.parse(file.metadata)\n : file.metadata,\n } satisfies UploadFile),\n uploadChunk: (\n uploadId: string,\n _clientId: string | null,\n chunk: ReadableStream,\n ) =>\n Effect.gen(function* () {\n // Read stream to completion\n const reader = chunk.getReader();\n let totalSize = 0;\n const chunks: Uint8Array[] = [];\n\n while (true) {\n const { done, value } = yield* Effect.promise(() => reader.read());\n if (done) break;\n if (value) {\n chunks.push(value);\n totalSize += value.byteLength;\n }\n }\n return {\n id: uploadId,\n offset: totalSize,\n size: totalSize,\n storage: { id: \"test-storage\", type: \"memory\" },\n metadata: { mimeType: \"application/octet-stream\", extension: \"bin\" },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile;\n }),\n getCapabilities: (_storageId: string, _clientId: string | null) =>\n Effect.succeed({\n supportsParallelUploads: true,\n supportsConcatenation: true,\n supportsDeferredLength: true,\n supportsResumableUploads: true,\n supportsTransactionalUploads: false,\n supportsStreamingRead: true,\n supportsStreamingWrite: true,\n maxConcurrentUploads: 10,\n minChunkSize: 5 * 1024 * 1024, // 5MB\n maxChunkSize: 100 * 1024 * 1024, // 100MB\n maxParts: 10000,\n optimalChunkSize: 10 * 1024 * 1024, // 10MB\n requiresOrderedChunks: false,\n requiresMimeTypeValidation: false,\n } satisfies DataStoreCapabilities),\n uploadFromUrl: (\n inputFile: InputFile,\n _clientId: string | null,\n url: string,\n ) =>\n Effect.succeed({\n id: `uploaded-from-url-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n offset: 0,\n size: 0,\n storage: { id: inputFile.storageId, type: \"memory\" },\n metadata:\n typeof inputFile.metadata === \"string\"\n ? JSON.parse(inputFile.metadata)\n : inputFile.metadata,\n url,\n creationDate: new Date().toISOString(),\n } satisfies UploadFile),\n getUpload: (uploadId: string) =>\n Effect.succeed({\n id: uploadId,\n offset: 0,\n size: 1024,\n storage: {\n id: \"test-storage\",\n type: \"memory\",\n },\n metadata: {\n mimeType: \"text/plain\",\n originalName: `file-${uploadId}.txt`,\n extension: \"txt\",\n },\n creationDate: new Date().toISOString(),\n } satisfies UploadFile),\n subscribeToUploadEvents: (\n _uploadId: string,\n _connection: WebSocketConnection,\n ) => Effect.void,\n unsubscribeFromUploadEvents: (_uploadId: string) => Effect.void,\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { VideoPlugin } from \"../flow\";\nimport type { DescribeVideoMetadata } from \"../flow/plugins/types/describe-video-node\";\n\n/**\n * Mock VideoPlugin implementation for testing.\n *\n * Provides simple mock implementations of video processing operations\n * that return mock Uint8Array data without requiring FFmpeg or node-av.\n *\n * @example\n * ```typescript\n * import { TestVideoPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* VideoPlugin;\n * const transcoded = yield* plugin.transcode(videoBytes, { format: \"webm\", codec: \"vp9\" });\n * return transcoded;\n * }).pipe(Effect.provide(TestVideoPlugin));\n * ```\n */\nexport const TestVideoPlugin = Layer.succeed(\n VideoPlugin,\n VideoPlugin.of({\n describe: (input: Uint8Array) =>\n Effect.sync(() => {\n // Mock describe: return fake metadata based on input size\n const metadata: DescribeVideoMetadata = {\n duration: 120, // 2 minutes\n width: 1920,\n height: 1080,\n codec: \"h264\",\n format: \"mp4\",\n bitrate: 5000000, // 5 Mbps\n frameRate: 30,\n aspectRatio: \"16:9\",\n hasAudio: true,\n audioCodec: \"aac\",\n audioBitrate: 128000, // 128 kbps\n size: input.byteLength,\n };\n return metadata;\n }),\n transcode: (_input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock transcode: return modified array\n // Simulate different file sizes for different codecs\n let sizeMultiplier = 1.0;\n if (options.codec === \"vp9\") {\n sizeMultiplier = 0.8; // VP9 is more efficient\n } else if (options.codec === \"h265\") {\n sizeMultiplier = 0.7; // H265 is even more efficient\n }\n\n const newSize = Math.floor(_input.byteLength * sizeMultiplier);\n return new Uint8Array(newSize).fill(42);\n }),\n resize: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock resize: return array with size based on dimensions\n const width = options.width || 1280;\n const height = options.height || 720;\n // Simulate file size roughly proportional to resolution\n const mockSize = Math.floor((width * height) / 50);\n return new Uint8Array(mockSize).fill(84);\n }),\n trim: (_input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock trim: return smaller array based on duration\n let duration: number;\n if (options.duration !== undefined) {\n duration = options.duration;\n } else if (options.endTime !== undefined) {\n duration = options.endTime - options.startTime;\n } else {\n // Assume 120s total duration\n duration = 120 - options.startTime;\n }\n\n // Simulate proportional file size based on duration\n const ratio = duration / 120; // Assuming 120s original\n const newSize = Math.floor(_input.byteLength * ratio);\n return new Uint8Array(newSize).fill(63);\n }),\n extractFrame: (input: Uint8Array, options) =>\n Effect.sync(() => {\n // Mock extractFrame: return image bytes (smaller than video)\n const format = options.format || \"jpeg\";\n // JPEG typically smaller than PNG\n const mockSize = format === \"png\" ? 50000 : 30000;\n return new Uint8Array(mockSize).fill(255);\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { VirusScanPlugin } from \"../flow\";\n\n/**\n * EICAR test file signature (standard antivirus test file)\n * This is a safe, non-malicious string used to test antivirus software\n */\nconst EICAR_SIGNATURE =\n \"X5O!P%@AP[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*\";\n\n/**\n * Mock VirusScanPlugin implementation for testing.\n *\n * Provides a simple mock implementation that:\n * - Detects the EICAR test signature as infected\n * - Treats all other files as clean\n * - Returns mock version information\n *\n * @example\n * ```typescript\n * import { TestVirusScanPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const plugin = yield* VirusScanPlugin;\n * const result = yield* plugin.scan(fileBytes);\n * console.log(result.isClean ? \"Clean\" : \"Infected\");\n * }).pipe(Effect.provide(TestVirusScanPlugin));\n * ```\n */\nexport const TestVirusScanPlugin = Layer.succeed(\n VirusScanPlugin,\n VirusScanPlugin.of({\n scan: (input: Uint8Array) =>\n Effect.sync(() => {\n // Convert bytes to string to check for EICAR signature\n const textDecoder = new TextDecoder();\n const content = textDecoder.decode(input);\n\n // Check if file contains EICAR test signature\n if (content.includes(EICAR_SIGNATURE)) {\n return {\n isClean: false,\n detectedViruses: [\"EICAR-Test-File\"],\n };\n }\n\n // All other files are considered clean\n return {\n isClean: true,\n detectedViruses: [],\n };\n }),\n getVersion: () =>\n Effect.sync(() => {\n return \"TestVirusScanPlugin 1.0.0\";\n }),\n }),\n);\n","import { Effect, Layer } from \"effect\";\nimport { ZipPlugin } from \"../flow\";\n\n/**\n * Mock ZipPlugin implementation for testing.\n *\n * Provides a simple in-memory implementation that creates mock zip data\n * by serializing file metadata as JSON.\n *\n * @example\n * ```typescript\n * import { TestZipPlugin } from \"@uploadista/core/testing\";\n *\n * const program = Effect.gen(function* () {\n * const zipPlugin = yield* ZipPlugin;\n * const zipData = yield* zipPlugin.zip(inputs, options);\n * return zipData;\n * }).pipe(Effect.provide(TestZipPlugin));\n * ```\n */\nexport const TestZipPlugin = Layer.succeed(\n ZipPlugin,\n ZipPlugin.of({\n zip: (inputs, options) =>\n Effect.gen(function* () {\n // Create mock zip data\n const files = inputs.map((input) => ({\n id: input.id,\n size: input.data.byteLength,\n }));\n\n const zipContent = JSON.stringify({\n zipName: options.zipName,\n includeMetadata: options.includeMetadata,\n files,\n });\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CAChC,QAAS,EAAQ,QACjB,gBAAiB,EAAQ,gBACzB,QACD,CAAC,CAEF,OAAO,IAAI,aAAa,CAAC,OAAO,EAAW,EAC3C,CACL,CAAC,CACH"}
@@ -1,2 +1,2 @@
1
1
  import{n as e}from"./uploadista-error-Fsfvr2Bb.mjs";import{Effect as t}from"effect";var n=class e{static hashStr(t,n=!1){return e.onePassHasher.start().appendStr(t).end(n)}static hashAsciiStr(t,n=!1){return e.onePassHasher.start().appendAsciiStr(t).end(n)}static stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]);static buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);static hexChars=`0123456789abcdef`;static hexOut=[];static onePassHasher=new e;static _hex(t){let n=e.hexChars,r=e.hexOut,i,a,o,s;for(s=0;s<4;s+=1)for(a=s*8,i=t[s]??0,o=0;o<8;o+=2)r[a+1+o]=n.charAt(i&15),i>>>=4,r[a+0+o]=n.charAt(i&15),i>>>=4;return r.join(``)}static _md5cycle(e,t){let n=e[0]??0,r=e[1]??0,i=e[2]??0,a=e[3]??0;n+=(r&i|~r&a)+(t[0]??0)-680876936|0,n=(n<<7|n>>>25)+r|0,a+=(n&r|~n&i)+(t[1]??0)-389564586|0,a=(a<<12|a>>>20)+n|0,i+=(a&n|~a&r)+(t[2]??0)+606105819|0,i=(i<<17|i>>>15)+a|0,r+=(i&a|~i&n)+(t[3]??0)-1044525330|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&a)+(t[4]??0)-176418897|0,n=(n<<7|n>>>25)+r|0,a+=(n&r|~n&i)+(t[5]??0)+1200080426|0,a=(a<<12|a>>>20)+n|0,i+=(a&n|~a&r)+(t[6]??0)-1473231341|0,i=(i<<17|i>>>15)+a|0,r+=(i&a|~i&n)+(t[7]??0)-45705983|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&a)+(t[8]??0)+1770035416|0,n=(n<<7|n>>>25)+r|0,a+=(n&r|~n&i)+(t[9]??0)-1958414417|0,a=(a<<12|a>>>20)+n|0,i+=(a&n|~a&r)+(t[10]??0)-42063|0,i=(i<<17|i>>>15)+a|0,r+=(i&a|~i&n)+(t[11]??0)-1990404162|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&a)+(t[12]??0)+1804603682|0,n=(n<<7|n>>>25)+r|0,a+=(n&r|~n&i)+(t[13]??0)-40341101|0,a=(a<<12|a>>>20)+n|0,i+=(a&n|~a&r)+(t[14]??0)-1502002290|0,i=(i<<17|i>>>15)+a|0,r+=(i&a|~i&n)+(t[15]??0)+1236535329|0,r=(r<<22|r>>>10)+i|0,n+=(r&a|i&~a)+(t[1]??0)-165796510|0,n=(n<<5|n>>>27)+r|0,a+=(n&i|r&~i)+(t[6]??0)-1069501632|0,a=(a<<9|a>>>23)+n|0,i+=(a&r|n&~r)+(t[11]??0)+643717713|0,i=(i<<14|i>>>18)+a|0,r+=(i&n|a&~n)+(t[0]??0)-373897302|0,r=(r<<20|r>>>12)+i|0,n+=(r&a|i&~a)+(t[5]??0)-701558691|0,n=(n<<5|n>>>27)+r|0,a+=(n&i|r&~i)+(t[10]??0)+38016083|0,a=(a<<9|a>>>23)+n|0,i+=(a&r|n&~r)+(t[15]??0)-660478335|0,i=(i<<14|i>>>18)+a|0,r+=(i&n|a&~n)+(t[4]??0)-405537848|0,r=(r<<20|r>>>12)+i|0,n+=(r&a|i&~a)+(t[9]??0)+568446438|0,n=(n<<5|n>>>27)+r|0,a+=(n&i|r&~i)+(t[14]??0)-1019803690|0,a=(a<<9|a>>>23)+n|0,i+=(a&r|n&~r)+(t[3]??0)-187363961|0,i=(i<<14|i>>>18)+a|0,r+=(i&n|a&~n)+(t[8]??0)+1163531501|0,r=(r<<20|r>>>12)+i|0,n+=(r&a|i&~a)+(t[13]??0)-1444681467|0,n=(n<<5|n>>>27)+r|0,a+=(n&i|r&~i)+(t[2]??0)-51403784|0,a=(a<<9|a>>>23)+n|0,i+=(a&r|n&~r)+(t[7]??0)+1735328473|0,i=(i<<14|i>>>18)+a|0,r+=(i&n|a&~n)+(t[12]??0)-1926607734|0,r=(r<<20|r>>>12)+i|0,n+=(r^i^a)+(t[5]??0)-378558|0,n=(n<<4|n>>>28)+r|0,a+=(n^r^i)+(t[8]??0)-2022574463|0,a=(a<<11|a>>>21)+n|0,i+=(a^n^r)+(t[11]??0)+1839030562|0,i=(i<<16|i>>>16)+a|0,r+=(i^a^n)+(t[14]??0)-35309556|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^a)+(t[1]??0)-1530992060|0,n=(n<<4|n>>>28)+r|0,a+=(n^r^i)+(t[4]??0)+1272893353|0,a=(a<<11|a>>>21)+n|0,i+=(a^n^r)+(t[7]??0)-155497632|0,i=(i<<16|i>>>16)+a|0,r+=(i^a^n)+(t[10]??0)-1094730640|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^a)+(t[13]??0)+681279174|0,n=(n<<4|n>>>28)+r|0,a+=(n^r^i)+(t[0]??0)-358537222|0,a=(a<<11|a>>>21)+n|0,i+=(a^n^r)+(t[3]??0)-722521979|0,i=(i<<16|i>>>16)+a|0,r+=(i^a^n)+(t[6]??0)+76029189|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^a)+(t[9]??0)-640364487|0,n=(n<<4|n>>>28)+r|0,a+=(n^r^i)+(t[12]??0)-421815835|0,a=(a<<11|a>>>21)+n|0,i+=(a^n^r)+(t[15]??0)+530742520|0,i=(i<<16|i>>>16)+a|0,r+=(i^a^n)+(t[2]??0)-995338651|0,r=(r<<23|r>>>9)+i|0,n+=(i^(r|~a))+(t[0]??0)-198630844|0,n=(n<<6|n>>>26)+r|0,a+=(r^(n|~i))+(t[7]??0)+1126891415|0,a=(a<<10|a>>>22)+n|0,i+=(n^(a|~r))+(t[14]??0)-1416354905|0,i=(i<<15|i>>>17)+a|0,r+=(a^(i|~n))+(t[5]??0)-57434055|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~a))+(t[12]??0)+1700485571|0,n=(n<<6|n>>>26)+r|0,a+=(r^(n|~i))+(t[3]??0)-1894986606|0,a=(a<<10|a>>>22)+n|0,i+=(n^(a|~r))+(t[10]??0)-1051523|0,i=(i<<15|i>>>17)+a|0,r+=(a^(i|~n))+(t[1]??0)-2054922799|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~a))+(t[8]??0)+1873313359|0,n=(n<<6|n>>>26)+r|0,a+=(r^(n|~i))+(t[15]??0)-30611744|0,a=(a<<10|a>>>22)+n|0,i+=(n^(a|~r))+(t[6]??0)-1560198380|0,i=(i<<15|i>>>17)+a|0,r+=(a^(i|~n))+(t[13]??0)+1309151649|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~a))+(t[4]??0)-145523070|0,n=(n<<6|n>>>26)+r|0,a+=(r^(n|~i))+(t[11]??0)-1120210379|0,a=(a<<10|a>>>22)+n|0,i+=(n^(a|~r))+(t[2]??0)+718787259|0,i=(i<<15|i>>>17)+a|0,r+=(a^(i|~n))+(t[9]??0)-343485551|0,r=(r<<21|r>>>11)+i|0,e[0]=n+(e[0]??0)|0,e[1]=r+(e[1]??0)|0,e[2]=i+(e[2]??0)|0,e[3]=a+(e[3]??0)|0}_dataLength=0;_bufferLength=0;_state=new Int32Array(4);_buffer=new ArrayBuffer(68);_buffer8;_buffer32;constructor(){this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(e.stateIdentity),this}appendStr(t){let n=this._buffer8,r=this._buffer32,i=this._bufferLength,a,o;for(o=0;o<t.length;o+=1){if(a=t.charCodeAt(o),a<128)n[i++]=a;else if(a<2048)n[i++]=(a>>>6)+192,n[i++]=a&63|128;else if(a<55296||a>56319)n[i++]=(a>>>12)+224,n[i++]=a>>>6&63|128,n[i++]=a&63|128;else{if(a=(a-55296)*1024+(t.charCodeAt(++o)-56320)+65536,a>1114111)throw Error(`Unicode standard supports code points up to U+10FFFF`);n[i++]=(a>>>18)+240,n[i++]=a>>>12&63|128,n[i++]=a>>>6&63|128,n[i++]=a&63|128}i>=64&&(this._dataLength+=64,e._md5cycle(this._state,r),i-=64,r[0]=r[16]??0)}return this._bufferLength=i,this}appendAsciiStr(t){let n=this._buffer8,r=this._buffer32,i=this._bufferLength,a,o=0;for(;;){for(a=Math.min(t.length-o,64-i);a--;)n[i++]=t.charCodeAt(o++);if(i<64)break;this._dataLength+=64,e._md5cycle(this._state,r),i=0}return this._bufferLength=i,this}appendByteArray(t){let n=this._buffer8,r=this._buffer32,i=this._bufferLength,a,o=0;for(;;){for(a=Math.min(t.length-o,64-i);a--;)n[i++]=t[o++]??0;if(i<64)break;this._dataLength+=64,e._md5cycle(this._state,r),i=0}return this._bufferLength=i,this}getState(){let e=this._state;return{buffer:String.fromCharCode.apply(null,Array.from(this._buffer8)),buflen:this._bufferLength,length:this._dataLength,state:[e[0]??0,e[1]??0,e[2]??0,e[3]??0]}}setState(e){let t=e.buffer,n=e.state,r=this._state,i;for(this._dataLength=e.length,this._bufferLength=e.buflen,r[0]=n[0]??0,r[1]=n[1]??0,r[2]=n[2]??0,r[3]=n[3]??0,i=0;i<t.length;i+=1)this._buffer8[i]=t.charCodeAt(i)}end(t=!1){let n=this._bufferLength,r=this._buffer8,i=this._buffer32,a=(n>>2)+1;this._dataLength+=n;let o=this._dataLength*8;if(r[n]=128,r[n+1]=r[n+2]=r[n+3]=0,i.set(e.buffer32Identity.subarray(a),a),n>55&&(e._md5cycle(this._state,i),i.set(e.buffer32Identity)),o<=4294967295)i[14]=o;else{let e=o.toString(16).match(/(.*?)(.{0,8})$/);if(e===null)return;let t=Number.parseInt(e[2]??``,16),n=Number.parseInt(e[1]??``,16)||0;i[14]=t,i[15]=n}return e._md5cycle(this._state,i),t?this._state:e._hex(this._state)}};if(n.hashStr(`hello`)!==`5d41402abc4b2a76b9719d911017c592`)throw Error(`Md5 self test failed.`);function r(e){let t=!1,n;return function(...r){if(t){if(n)return n;throw Error(`Function called more than once`)}return t=!0,n=e.apply(this,r),n}}const i={make:n=>{let r,i=!1;return t.gen(function*(){if(i){if(r!==void 0)return r;yield*new e({code:`UNKNOWN_ERROR`,status:500,body:`Effect called more than once with undefined result`}).toEffect()}return i=!0,r=yield*n,r})},legacy:r},a={leading:!1,trailing:!0};function o(e,t,n={}){let r={...a,...n},i;return function(...n){r.leading&&!i?(console.log(`leading`),e.apply(this,n),i=setTimeout(()=>{i=void 0},t)):(clearTimeout(i),i=setTimeout(()=>{r.trailing?(e.apply(this,n),r.leading&&setTimeout(()=>{i=void 0},t)):i=void 0},t))}}function s(e,t,{leading:n=!0,trailing:r=!0}={}){return o(e,t,{leading:n,trailing:r})}const c={legacy:s};export{n as a,r as i,s as n,i as r,c as t};
2
- //# sourceMappingURL=utils-Zq5USthu.mjs.map
2
+ //# sourceMappingURL=throttle-CnDa3v1k.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throttle-CnDa3v1k.mjs","names":[],"sources":["../src/utils/md5.ts","../src/utils/once.ts","../src/utils/debounce.ts","../src/utils/throttle.ts"],"sourcesContent":["/*\n\nTypeScript Md5\n==============\n\nBased on work by\n* Joseph Myers: http://www.myersdaily.org/joseph/javascript/md5-text.html\n* André Cruz: https://github.com/satazor/SparkMD5\n* Raymond Hill: https://github.com/gorhill/yamd5.js\n\nEffectively a TypeScrypt re-write of Raymond Hill JS Library\n\nThe MIT License (MIT)\n\nCopyright (C) 2014 Raymond Hill\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n DO WHAT YOU WANT TO PUBLIC LICENSE\n Version 2, December 2004\n\n Copyright (C) 2015 André Cruz <amdfcruz@gmail.com>\n\n Everyone is permitted to copy and distribute verbatim or modified\n copies of this license document, and changing it is allowed as long\n as the name is changed.\n\n DO WHAT YOU WANT TO PUBLIC LICENSE\n TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n 0. You just DO WHAT YOU WANT TO.\n\n*/\n\ntype HasherState = {\n buffer: string;\n buflen: number;\n length: number;\n state: number[];\n};\n\nexport class Md5 {\n /**\n * Hash a UTF-8 string on the spot\n * @param str String to hash\n * @param raw Whether to return the value as an `Int32Array`\n */\n public static hashStr(str: string, raw?: false): string;\n public static hashStr(str: string, raw: true): Int32Array;\n public static hashStr(str: string, raw = false) {\n return Md5.onePassHasher.start().appendStr(str).end(raw);\n }\n\n /**\n * Hash a ASCII string on the spot\n * @param str String to hash\n * @param raw Whether to return the value as an `Int32Array`\n */\n public static hashAsciiStr(str: string, raw?: false): string;\n public static hashAsciiStr(str: string, raw: true): Int32Array;\n public static hashAsciiStr(str: string, raw = false) {\n return Md5.onePassHasher.start().appendAsciiStr(str).end(raw);\n }\n\n // Private Static Variables\n private static stateIdentity = new Int32Array([\n 1732584193, -271733879, -1732584194, 271733878,\n ]);\n\n private static buffer32Identity = new Int32Array([\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n ]);\n\n private static hexChars = \"0123456789abcdef\";\n private static hexOut: string[] = [];\n\n // Permanent instance is to use for one-call hashing\n private static onePassHasher = new Md5();\n\n private static _hex(x: Int32Array): string {\n const hc = Md5.hexChars;\n const ho = Md5.hexOut;\n let n: number;\n let offset: number;\n let j: number;\n let i: number;\n\n for (i = 0; i < 4; i += 1) {\n offset = i * 8;\n n = x[i] ?? 0;\n for (j = 0; j < 8; j += 2) {\n ho[offset + 1 + j] = hc.charAt(n & 0x0f);\n n >>>= 4;\n ho[offset + 0 + j] = hc.charAt(n & 0x0f);\n n >>>= 4;\n }\n }\n return ho.join(\"\");\n }\n\n private static _md5cycle(\n x: Int32Array | Uint32Array,\n k: Int32Array | Uint32Array,\n ) {\n let a: number = x[0] ?? 0;\n let b: number = x[1] ?? 0;\n let c: number = x[2] ?? 0;\n let d: number = x[3] ?? 0;\n // ff()\n a += (((b & c) | (~b & d)) + (k[0] ?? 0) - 680876936) | 0;\n a = (((a << 7) | (a >>> 25)) + b) | 0;\n d += (((a & b) | (~a & c)) + (k[1] ?? 0) - 389564586) | 0;\n d = (((d << 12) | (d >>> 20)) + a) | 0;\n c += (((d & a) | (~d & b)) + (k[2] ?? 0) + 606105819) | 0;\n c = (((c << 17) | (c >>> 15)) + d) | 0;\n b += (((c & d) | (~c & a)) + (k[3] ?? 0) - 1044525330) | 0;\n b = (((b << 22) | (b >>> 10)) + c) | 0;\n a += (((b & c) | (~b & d)) + (k[4] ?? 0) - 176418897) | 0;\n a = (((a << 7) | (a >>> 25)) + b) | 0;\n d += (((a & b) | (~a & c)) + (k[5] ?? 0) + 1200080426) | 0;\n d = (((d << 12) | (d >>> 20)) + a) | 0;\n c += (((d & a) | (~d & b)) + (k[6] ?? 0) - 1473231341) | 0;\n c = (((c << 17) | (c >>> 15)) + d) | 0;\n b += (((c & d) | (~c & a)) + (k[7] ?? 0) - 45705983) | 0;\n b = (((b << 22) | (b >>> 10)) + c) | 0;\n a += (((b & c) | (~b & d)) + (k[8] ?? 0) + 1770035416) | 0;\n a = (((a << 7) | (a >>> 25)) + b) | 0;\n d += (((a & b) | (~a & c)) + (k[9] ?? 0) - 1958414417) | 0;\n d = (((d << 12) | (d >>> 20)) + a) | 0;\n c += (((d & a) | (~d & b)) + (k[10] ?? 0) - 42063) | 0;\n c = (((c << 17) | (c >>> 15)) + d) | 0;\n b += (((c & d) | (~c & a)) + (k[11] ?? 0) - 1990404162) | 0;\n b = (((b << 22) | (b >>> 10)) + c) | 0;\n a += (((b & c) | (~b & d)) + (k[12] ?? 0) + 1804603682) | 0;\n a = (((a << 7) | (a >>> 25)) + b) | 0;\n d += (((a & b) | (~a & c)) + (k[13] ?? 0) - 40341101) | 0;\n d = (((d << 12) | (d >>> 20)) + a) | 0;\n c += (((d & a) | (~d & b)) + (k[14] ?? 0) - 1502002290) | 0;\n c = (((c << 17) | (c >>> 15)) + d) | 0;\n b += (((c & d) | (~c & a)) + (k[15] ?? 0) + 1236535329) | 0;\n b = (((b << 22) | (b >>> 10)) + c) | 0;\n // gg()\n a += (((b & d) | (c & ~d)) + (k[1] ?? 0) - 165796510) | 0;\n a = (((a << 5) | (a >>> 27)) + b) | 0;\n d += (((a & c) | (b & ~c)) + (k[6] ?? 0) - 1069501632) | 0;\n d = (((d << 9) | (d >>> 23)) + a) | 0;\n c += (((d & b) | (a & ~b)) + (k[11] ?? 0) + 643717713) | 0;\n c = (((c << 14) | (c >>> 18)) + d) | 0;\n b += (((c & a) | (d & ~a)) + (k[0] ?? 0) - 373897302) | 0;\n b = (((b << 20) | (b >>> 12)) + c) | 0;\n a += (((b & d) | (c & ~d)) + (k[5] ?? 0) - 701558691) | 0;\n a = (((a << 5) | (a >>> 27)) + b) | 0;\n d += (((a & c) | (b & ~c)) + (k[10] ?? 0) + 38016083) | 0;\n d = (((d << 9) | (d >>> 23)) + a) | 0;\n c += (((d & b) | (a & ~b)) + (k[15] ?? 0) - 660478335) | 0;\n c = (((c << 14) | (c >>> 18)) + d) | 0;\n b += (((c & a) | (d & ~a)) + (k[4] ?? 0) - 405537848) | 0;\n b = (((b << 20) | (b >>> 12)) + c) | 0;\n a += (((b & d) | (c & ~d)) + (k[9] ?? 0) + 568446438) | 0;\n a = (((a << 5) | (a >>> 27)) + b) | 0;\n d += (((a & c) | (b & ~c)) + (k[14] ?? 0) - 1019803690) | 0;\n d = (((d << 9) | (d >>> 23)) + a) | 0;\n c += (((d & b) | (a & ~b)) + (k[3] ?? 0) - 187363961) | 0;\n c = (((c << 14) | (c >>> 18)) + d) | 0;\n b += (((c & a) | (d & ~a)) + (k[8] ?? 0) + 1163531501) | 0;\n b = (((b << 20) | (b >>> 12)) + c) | 0;\n a += (((b & d) | (c & ~d)) + (k[13] ?? 0) - 1444681467) | 0;\n a = (((a << 5) | (a >>> 27)) + b) | 0;\n d += (((a & c) | (b & ~c)) + (k[2] ?? 0) - 51403784) | 0;\n d = (((d << 9) | (d >>> 23)) + a) | 0;\n c += (((d & b) | (a & ~b)) + (k[7] ?? 0) + 1735328473) | 0;\n c = (((c << 14) | (c >>> 18)) + d) | 0;\n b += (((c & a) | (d & ~a)) + (k[12] ?? 0) - 1926607734) | 0;\n b = (((b << 20) | (b >>> 12)) + c) | 0;\n // hh()\n a += ((b ^ c ^ d) + (k[5] ?? 0) - 378558) | 0;\n a = (((a << 4) | (a >>> 28)) + b) | 0;\n d += ((a ^ b ^ c) + (k[8] ?? 0) - 2022574463) | 0;\n d = (((d << 11) | (d >>> 21)) + a) | 0;\n c += ((d ^ a ^ b) + (k[11] ?? 0) + 1839030562) | 0;\n c = (((c << 16) | (c >>> 16)) + d) | 0;\n b += ((c ^ d ^ a) + (k[14] ?? 0) - 35309556) | 0;\n b = (((b << 23) | (b >>> 9)) + c) | 0;\n a += ((b ^ c ^ d) + (k[1] ?? 0) - 1530992060) | 0;\n a = (((a << 4) | (a >>> 28)) + b) | 0;\n d += ((a ^ b ^ c) + (k[4] ?? 0) + 1272893353) | 0;\n d = (((d << 11) | (d >>> 21)) + a) | 0;\n c += ((d ^ a ^ b) + (k[7] ?? 0) - 155497632) | 0;\n c = (((c << 16) | (c >>> 16)) + d) | 0;\n b += ((c ^ d ^ a) + (k[10] ?? 0) - 1094730640) | 0;\n b = (((b << 23) | (b >>> 9)) + c) | 0;\n a += ((b ^ c ^ d) + (k[13] ?? 0) + 681279174) | 0;\n a = (((a << 4) | (a >>> 28)) + b) | 0;\n d += ((a ^ b ^ c) + (k[0] ?? 0) - 358537222) | 0;\n d = (((d << 11) | (d >>> 21)) + a) | 0;\n c += ((d ^ a ^ b) + (k[3] ?? 0) - 722521979) | 0;\n c = (((c << 16) | (c >>> 16)) + d) | 0;\n b += ((c ^ d ^ a) + (k[6] ?? 0) + 76029189) | 0;\n b = (((b << 23) | (b >>> 9)) + c) | 0;\n a += ((b ^ c ^ d) + (k[9] ?? 0) - 640364487) | 0;\n a = (((a << 4) | (a >>> 28)) + b) | 0;\n d += ((a ^ b ^ c) + (k[12] ?? 0) - 421815835) | 0;\n d = (((d << 11) | (d >>> 21)) + a) | 0;\n c += ((d ^ a ^ b) + (k[15] ?? 0) + 530742520) | 0;\n c = (((c << 16) | (c >>> 16)) + d) | 0;\n b += ((c ^ d ^ a) + (k[2] ?? 0) - 995338651) | 0;\n b = (((b << 23) | (b >>> 9)) + c) | 0;\n // ii()\n a += ((c ^ (b | ~d)) + (k[0] ?? 0) - 198630844) | 0;\n a = (((a << 6) | (a >>> 26)) + b) | 0;\n d += ((b ^ (a | ~c)) + (k[7] ?? 0) + 1126891415) | 0;\n d = (((d << 10) | (d >>> 22)) + a) | 0;\n c += ((a ^ (d | ~b)) + (k[14] ?? 0) - 1416354905) | 0;\n c = (((c << 15) | (c >>> 17)) + d) | 0;\n b += ((d ^ (c | ~a)) + (k[5] ?? 0) - 57434055) | 0;\n b = (((b << 21) | (b >>> 11)) + c) | 0;\n a += ((c ^ (b | ~d)) + (k[12] ?? 0) + 1700485571) | 0;\n a = (((a << 6) | (a >>> 26)) + b) | 0;\n d += ((b ^ (a | ~c)) + (k[3] ?? 0) - 1894986606) | 0;\n d = (((d << 10) | (d >>> 22)) + a) | 0;\n c += ((a ^ (d | ~b)) + (k[10] ?? 0) - 1051523) | 0;\n c = (((c << 15) | (c >>> 17)) + d) | 0;\n b += ((d ^ (c | ~a)) + (k[1] ?? 0) - 2054922799) | 0;\n b = (((b << 21) | (b >>> 11)) + c) | 0;\n a += ((c ^ (b | ~d)) + (k[8] ?? 0) + 1873313359) | 0;\n a = (((a << 6) | (a >>> 26)) + b) | 0;\n d += ((b ^ (a | ~c)) + (k[15] ?? 0) - 30611744) | 0;\n d = (((d << 10) | (d >>> 22)) + a) | 0;\n c += ((a ^ (d | ~b)) + (k[6] ?? 0) - 1560198380) | 0;\n c = (((c << 15) | (c >>> 17)) + d) | 0;\n b += ((d ^ (c | ~a)) + (k[13] ?? 0) + 1309151649) | 0;\n b = (((b << 21) | (b >>> 11)) + c) | 0;\n a += ((c ^ (b | ~d)) + (k[4] ?? 0) - 145523070) | 0;\n a = (((a << 6) | (a >>> 26)) + b) | 0;\n d += ((b ^ (a | ~c)) + (k[11] ?? 0) - 1120210379) | 0;\n d = (((d << 10) | (d >>> 22)) + a) | 0;\n c += ((a ^ (d | ~b)) + (k[2] ?? 0) + 718787259) | 0;\n c = (((c << 15) | (c >>> 17)) + d) | 0;\n b += ((d ^ (c | ~a)) + (k[9] ?? 0) - 343485551) | 0;\n b = (((b << 21) | (b >>> 11)) + c) | 0;\n\n x[0] = (a + (x[0] ?? 0)) | 0;\n x[1] = (b + (x[1] ?? 0)) | 0;\n x[2] = (c + (x[2] ?? 0)) | 0;\n x[3] = (d + (x[3] ?? 0)) | 0;\n }\n\n private _dataLength = 0;\n private _bufferLength = 0;\n\n private _state: Int32Array = new Int32Array(4);\n private _buffer: ArrayBuffer = new ArrayBuffer(68);\n private _buffer8: Uint8Array;\n private _buffer32: Uint32Array;\n\n constructor() {\n this._buffer8 = new Uint8Array(this._buffer, 0, 68);\n this._buffer32 = new Uint32Array(this._buffer, 0, 17);\n this.start();\n }\n\n /**\n * Initialise buffer to be hashed\n */\n public start() {\n this._dataLength = 0;\n this._bufferLength = 0;\n this._state.set(Md5.stateIdentity);\n return this;\n }\n\n // Char to code point to to array conversion:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt\n // #Example.3A_Fixing_charCodeAt_to_handle_non-Basic-Multilingual-Plane_characters_if_their_presence_earlier_in_the_string_is_unknown\n\n /**\n * Append a UTF-8 string to the hash buffer\n * @param str String to append\n */\n public appendStr(str: string) {\n const buf8 = this._buffer8;\n const buf32 = this._buffer32;\n let bufLen = this._bufferLength;\n let code: number;\n let i: number;\n\n for (i = 0; i < str.length; i += 1) {\n code = str.charCodeAt(i);\n if (code < 128) {\n buf8[bufLen++] = code;\n } else if (code < 0x800) {\n buf8[bufLen++] = (code >>> 6) + 0xc0;\n buf8[bufLen++] = (code & 0x3f) | 0x80;\n } else if (code < 0xd800 || code > 0xdbff) {\n buf8[bufLen++] = (code >>> 12) + 0xe0;\n buf8[bufLen++] = ((code >>> 6) & 0x3f) | 0x80;\n buf8[bufLen++] = (code & 0x3f) | 0x80;\n } else {\n code =\n (code - 0xd800) * 0x400 + (str.charCodeAt(++i) - 0xdc00) + 0x10000;\n if (code > 0x10ffff) {\n throw new Error(\n \"Unicode standard supports code points up to U+10FFFF\",\n );\n }\n buf8[bufLen++] = (code >>> 18) + 0xf0;\n buf8[bufLen++] = ((code >>> 12) & 0x3f) | 0x80;\n buf8[bufLen++] = ((code >>> 6) & 0x3f) | 0x80;\n buf8[bufLen++] = (code & 0x3f) | 0x80;\n }\n if (bufLen >= 64) {\n this._dataLength += 64;\n Md5._md5cycle(this._state, buf32);\n bufLen -= 64;\n buf32[0] = buf32[16] ?? 0;\n }\n }\n this._bufferLength = bufLen;\n return this;\n }\n\n /**\n * Append an ASCII string to the hash buffer\n * @param str String to append\n */\n public appendAsciiStr(str: string) {\n const buf8 = this._buffer8;\n const buf32 = this._buffer32;\n let bufLen = this._bufferLength;\n let i: number;\n let j = 0;\n\n for (;;) {\n i = Math.min(str.length - j, 64 - bufLen);\n while (i--) {\n buf8[bufLen++] = str.charCodeAt(j++);\n }\n if (bufLen < 64) {\n break;\n }\n this._dataLength += 64;\n Md5._md5cycle(this._state, buf32);\n bufLen = 0;\n }\n this._bufferLength = bufLen;\n return this;\n }\n\n /**\n * Append a byte array to the hash buffer\n * @param input array to append\n */\n public appendByteArray(input: Uint8Array) {\n const buf8 = this._buffer8;\n const buf32 = this._buffer32;\n let bufLen = this._bufferLength;\n let i: number;\n let j = 0;\n\n for (;;) {\n i = Math.min(input.length - j, 64 - bufLen);\n while (i--) {\n buf8[bufLen++] = input[j++] ?? 0;\n }\n if (bufLen < 64) {\n break;\n }\n this._dataLength += 64;\n Md5._md5cycle(this._state, buf32);\n bufLen = 0;\n }\n this._bufferLength = bufLen;\n return this;\n }\n\n /**\n * Get the state of the hash buffer\n */\n public getState(): HasherState {\n const s = this._state;\n\n return {\n buffer: String.fromCharCode.apply(null, Array.from(this._buffer8)),\n buflen: this._bufferLength,\n length: this._dataLength,\n state: [s[0] ?? 0, s[1] ?? 0, s[2] ?? 0, s[3] ?? 0],\n };\n }\n\n /**\n * Override the current state of the hash buffer\n * @param state New hash buffer state\n */\n public setState(state: HasherState) {\n const buf = state.buffer;\n const x = state.state;\n const s = this._state;\n let i: number;\n\n this._dataLength = state.length;\n this._bufferLength = state.buflen;\n s[0] = x[0] ?? 0;\n s[1] = x[1] ?? 0;\n s[2] = x[2] ?? 0;\n s[3] = x[3] ?? 0;\n\n for (i = 0; i < buf.length; i += 1) {\n this._buffer8[i] = buf.charCodeAt(i);\n }\n }\n\n /**\n * Hash the current state of the hash buffer and return the result\n * @param raw Whether to return the value as an `Int32Array`\n */\n public end(raw = false) {\n const bufLen = this._bufferLength;\n const buf8 = this._buffer8;\n const buf32 = this._buffer32;\n const i = (bufLen >> 2) + 1;\n\n this._dataLength += bufLen;\n const dataBitsLen = this._dataLength * 8;\n\n buf8[bufLen] = 0x80;\n buf8[bufLen + 1] = buf8[bufLen + 2] = buf8[bufLen + 3] = 0;\n buf32.set(Md5.buffer32Identity.subarray(i), i);\n\n if (bufLen > 55) {\n Md5._md5cycle(this._state, buf32);\n buf32.set(Md5.buffer32Identity);\n }\n\n // Do the final computation based on the tail and length\n // Beware that the final length may not fit in 32 bits so we take care of that\n if (dataBitsLen <= 0xffffffff) {\n buf32[14] = dataBitsLen;\n } else {\n const matches = dataBitsLen.toString(16).match(/(.*?)(.{0,8})$/);\n if (matches === null) {\n return;\n }\n\n const lo = Number.parseInt(matches[2] ?? \"\", 16);\n const hi = Number.parseInt(matches[1] ?? \"\", 16) || 0;\n\n buf32[14] = lo;\n buf32[15] = hi;\n }\n\n Md5._md5cycle(this._state, buf32);\n\n return raw ? this._state : Md5._hex(this._state);\n }\n}\n\nif (Md5.hashStr(\"hello\") !== \"5d41402abc4b2a76b9719d911017c592\") {\n throw new Error(\"Md5 self test failed.\");\n}\n","import { Effect } from \"effect\";\nimport { UploadistaError } from \"../errors/uploadista-error\";\n\n// only call a function once\nexport function once<T, A extends unknown[], Return>(\n fn: (this: T, ...args: A) => Return,\n) {\n let called = false;\n let value: Return | undefined;\n const f = function (this: T, ...args: A): Return {\n if (called) {\n if (value) {\n return value;\n }\n throw new Error(\"Function called more than once\");\n }\n called = true;\n value = fn.apply(this, args);\n return value;\n };\n return f;\n}\n\n/**\n * Effect-based once utilities\n */\nexport const OnceEffect = {\n /**\n * Creates an Effect-based once function that only executes once\n * @param effect - The effect to execute only once\n * @returns Effect that caches the result after first execution\n */\n make: <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n ): Effect.Effect<A, E | UploadistaError, R> => {\n let cached: A | undefined;\n let called = false;\n\n return Effect.gen(function* () {\n if (called) {\n if (cached !== undefined) {\n return cached;\n }\n yield* new UploadistaError({\n code: \"UNKNOWN_ERROR\",\n status: 500,\n body: \"Effect called more than once with undefined result\",\n }).toEffect();\n }\n\n called = true;\n cached = yield* effect;\n return cached;\n });\n },\n\n /**\n * Creates a legacy once function wrapper\n * @param fn - Function to wrap\n * @returns Once-wrapped function\n */\n legacy: once,\n};\n","type DebounceOptions = {\n // Whether the first call to the debounced function is run immediately.\n leading?: boolean;\n\n // Whether the last call to the debounced function is run after delay\n // milliseconds have elapsed since the last call.\n trailing?: boolean;\n};\n\nconst defaultDebounceOptions: DebounceOptions = {\n leading: false,\n trailing: true,\n};\n\n/**\n * Returns `fn` wrapped by a function that delays invoking `fn` for `delay`\n * milliseconds since the last call. Set `options.leading` to invoke `fn` on\n * the leading edge of the delay, and/or set `options.trailing` to invoke `fn`\n * on the trailing edge of the delay (true by default).\n *\n * Example for `debounce(fn, 30, {leading: true, trailing: true})`,\n * where `fn` is called twice, with the second call made 20 ms after the first:\n *\n * Time: 0 20 50 (ms)\n * Timeline: |----------------------------------------------------------------|\n * ^ ^ ^\n * | | |\n * | First call. | Second call 20ms after the | End of delay.\n * | (instant leading | first. | (trailing edge\n * | edge call) | | call)\n * |-----------------------------|\n * | 30 ms delay for debounce. |\n *\n *\n * Note that if both `options.leading` and `options.trailing` are true, `fn`\n * will only be invoked on the trailing edge if the debounced function is called\n * more than once during the delay.\n *\n * @param fn - Function to debounce.\n * @param delay - Milliseconds to delay calling `fn` since the last call.\n * @param debounceOptions - See `DebounceOptions` and `defaultDebounceOptions`.\n * @returns A debounced `fn`.\n */\nexport function debounce<T, A extends unknown[]>(\n fn: (this: T, ...args: A) => void,\n delay: number,\n debounceOptions: DebounceOptions = {},\n): (this: T, ...args: A) => void {\n const options = { ...defaultDebounceOptions, ...debounceOptions };\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return function (this: T, ...args: A): void {\n if (options.leading && !timer) {\n // Leading edge.\n // Call fn on the leading edge, when debouncing hasn't started yet.\n console.log(\"leading\");\n fn.apply(this, args);\n\n // Debounce the next call.\n timer = setTimeout(() => {\n timer = undefined;\n }, delay);\n } else {\n // Trailing edge.\n // Postpone calling fn until the delay has elapsed since the last call.\n // Each call clears any previously delayed call and resets the delay, so\n // the postponed call will always be the last one.\n clearTimeout(timer);\n timer = setTimeout(() => {\n if (options.trailing) {\n // Call fn on the trailing edge.\n fn.apply(this, args);\n\n if (options.leading) {\n // Debounce next leading call since a trailing call was just made.\n setTimeout(() => {\n timer = undefined;\n }, delay);\n }\n } else {\n // No trailing call. Since the delay has elapsed since the last call,\n // immediately reset the debouncing delay.\n timer = undefined;\n }\n }, delay);\n }\n };\n}\n","import { debounce } from \"./debounce.js\";\n\nexport function throttle<T, A extends unknown[], Return>(\n fn: (this: T, ...args: A) => Return,\n wait: number,\n {\n leading = true,\n trailing = true,\n }: { leading?: boolean; trailing?: boolean } = {},\n) {\n return debounce(fn, wait, {\n leading,\n trailing,\n });\n}\n\n/**\n * Effect-based throttle utilities\n */\nexport const ThrottleEffect = {\n /**\n * Creates a legacy throttle function wrapper\n * @param fn - Function to throttle\n * @param wait - Wait time in milliseconds\n * @param options - Throttle options\n * @returns Throttled function\n */\n legacy: throttle,\n};\n"],"mappings":"oFAyDA,IAAa,EAAb,MAAa,CAAI,CAQf,OAAc,QAAQ,EAAa,EAAM,GAAO,CAC9C,OAAO,EAAI,cAAc,OAAO,CAAC,UAAU,EAAI,CAAC,IAAI,EAAI,CAU1D,OAAc,aAAa,EAAa,EAAM,GAAO,CACnD,OAAO,EAAI,cAAc,OAAO,CAAC,eAAe,EAAI,CAAC,IAAI,EAAI,CAI/D,OAAe,cAAgB,IAAI,WAAW,CAC5C,WAAY,WAAY,YAAa,UACtC,CAAC,CAEF,OAAe,iBAAmB,IAAI,WAAW,CAC/C,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAC9C,CAAC,CAEF,OAAe,SAAW,mBAC1B,OAAe,OAAmB,EAAE,CAGpC,OAAe,cAAgB,IAAI,EAEnC,OAAe,KAAK,EAAuB,CACzC,IAAM,EAAK,EAAI,SACT,EAAK,EAAI,OACX,EACA,EACA,EACA,EAEJ,IAAK,EAAI,EAAG,EAAI,EAAG,GAAK,EAGtB,IAFA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,EAAe,CACtC,EAAQ,SAAW,CAAC,GAGtB,QAAQ,IAAI,UAAU,CACtB,EAAG,MAAM,KAAM,EAAK,CAGpB,EAAQ,eAAiB,CACvB,EAAQ,IAAA,IACP,EAAM,GAMT,aAAa,EAAM,CACnB,EAAQ,eAAiB,CACnB,EAAQ,UAEV,EAAG,MAAM,KAAM,EAAK,CAEhB,EAAQ,SAEV,eAAiB,CACf,EAAQ,IAAA,IACP,EAAM,EAKX,EAAQ,IAAA,IAET,EAAM,GCnFf,SAAgB,EACd,EACA,EACA,CACE,UAAU,GACV,WAAW,IACkC,EAAE,CACjD,CACA,OAAO,EAAS,EAAI,EAAM,CACxB,UACA,WACD,CAAC,CAMJ,MAAa,EAAiB,CAQ5B,OAAQ,EACT"}
@@ -165,4 +165,4 @@ declare const ThrottleEffect: {
165
165
  };
166
166
  //#endregion
167
167
  export { Md5 as a, isSupportedAlgorithm as c, GenerateIdRandom as d, GenerateIdService as f, once as i, GenerateId as l, GenerateIdTimestamp as m, throttle as n, ChecksumAlgorithm as o, GenerateIdShape as p, OnceEffect as r, computeChecksum as s, ThrottleEffect as t, GenerateIdLive as u };
168
- //# sourceMappingURL=index-Bg1UKKmY.d.cts.map
168
+ //# sourceMappingURL=throttle-Da0OA8JT.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"throttle-Da0OA8JT.d.cts","names":[],"sources":["../src/utils/generate-id.ts","../src/utils/checksum.ts","../src/utils/md5.ts","../src/utils/once.ts","../src/utils/throttle.ts"],"mappings":";;;;KAEY,eAAA;EACV,UAAA,QAAkB,MAAA,CAAO,MAAA;AAAA;AAAA,cACzB,eAAA;6BAK6B,MAAA,CAAO,MAAA;AAAA;AAAA,cAFzB,UAAA,SAAmB,eAAA;;;;cAQnB,iBAAA;EAAA,2BANkB,MAAA,CAAO,MAAA;AAAA;;;;;cAYzB,gBAAA;EAAA,2BAZkB,MAAA,CAAO,MAAA;AAAA;AAAA,cAgBzB,cAAA,EAAc,KAAA,CAAA,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