@uploadista/core 0.0.8 → 0.0.10
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.
- package/dist/checksum-DgutVB-2.cjs +1 -0
- package/dist/checksum-Do_Vh-tB.mjs +2 -0
- package/dist/checksum-Do_Vh-tB.mjs.map +1 -0
- package/dist/errors/index.cjs +1 -1
- package/dist/errors/{index.d.ts → index.d.mts} +2 -2
- package/dist/errors/index.mjs +1 -0
- package/dist/flow/index.cjs +1 -1
- package/dist/flow/index.d.cts +2 -2
- package/dist/flow/index.d.mts +6 -0
- package/dist/flow/index.mjs +1 -0
- package/dist/flow-C_doYlGf.cjs +1 -0
- package/dist/flow-DEohelFR.mjs +2 -0
- package/dist/flow-DEohelFR.mjs.map +1 -0
- package/dist/{index-Bq0Zkv4L.d.ts → index-BQ8Ns-NS.d.mts} +74 -9
- package/dist/index-BQ8Ns-NS.d.mts.map +1 -0
- package/dist/{index-xTZ5vAgA.d.cts → index-Bg1HsPC1.d.cts} +73 -8
- package/dist/index-Bg1HsPC1.d.cts.map +1 -0
- package/dist/{index-CU5XRZOh.d.ts → index-C2nrn_49.d.mts} +2 -2
- package/dist/index-C2nrn_49.d.mts.map +1 -0
- package/dist/{index-BQIgMrBX.d.ts → index-CsLVxsad.d.mts} +2 -2
- package/dist/index-CsLVxsad.d.mts.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.mts +6 -0
- package/dist/index.mjs +1 -0
- package/dist/stream-limiter-Bj_iImMm.cjs +1 -0
- package/dist/stream-limiter-CEpDLQVB.mjs +2 -0
- package/dist/stream-limiter-CEpDLQVB.mjs.map +1 -0
- package/dist/streams/index.cjs +1 -1
- package/dist/streams/index.d.mts +3 -0
- package/dist/streams/index.mjs +1 -0
- package/dist/types/index.cjs +1 -1
- package/dist/types/index.d.cts +1 -1
- package/dist/types/index.d.mts +6 -0
- package/dist/types/index.mjs +1 -0
- package/dist/types-BYfvxhhG.mjs +2 -0
- package/dist/types-BYfvxhhG.mjs.map +1 -0
- package/dist/types-C80hlY_o.cjs +1 -0
- package/dist/upload/index.cjs +1 -1
- package/dist/upload/index.d.cts +1 -1
- package/dist/upload/index.d.mts +6 -0
- package/dist/upload/index.mjs +1 -0
- package/dist/upload-CcmxSO5u.mjs +2 -0
- package/dist/upload-CcmxSO5u.mjs.map +1 -0
- package/dist/upload-IZuHoQqL.cjs +1 -0
- package/dist/{uploadista-error-BOHJtDRc.cjs → uploadista-error-CQ1ADme7.cjs} +2 -2
- package/dist/{uploadista-error-kZCQLC_U.d.ts → uploadista-error-DHajuvP1.d.mts} +1 -1
- package/dist/uploadista-error-DHajuvP1.d.mts.map +1 -0
- package/dist/{uploadista-error-CDkJ_Vrc.js → uploadista-error-U9YxwNtM.mjs} +1 -1
- package/dist/uploadista-error-U9YxwNtM.mjs.map +1 -0
- package/dist/utils/index.cjs +1 -1
- package/dist/utils/{index.d.ts → index.d.mts} +2 -2
- package/dist/utils/index.mjs +1 -0
- package/dist/{utils-BbLQplqQ.cjs → utils-C6k-Fs99.mjs} +2 -1
- package/dist/utils-C6k-Fs99.mjs.map +1 -0
- package/dist/utils-DzDTNMnq.cjs +1 -0
- package/package.json +38 -30
- package/src/flow/flow-server.ts +122 -25
- package/src/flow/flow.ts +2 -0
- package/src/types/upload-file.ts +11 -0
- package/dist/checksum-CPiON71t.cjs +0 -1
- package/dist/checksum-_Vagjoys.js +0 -2
- package/dist/checksum-_Vagjoys.js.map +0 -1
- package/dist/errors/index.js +0 -1
- package/dist/flow/index.d.ts +0 -6
- package/dist/flow/index.js +0 -1
- package/dist/flow-CSHZVjcf.js +0 -2
- package/dist/flow-CSHZVjcf.js.map +0 -1
- package/dist/flow-zlCaikPS.cjs +0 -1
- package/dist/index-BQIgMrBX.d.ts.map +0 -1
- package/dist/index-Bq0Zkv4L.d.ts.map +0 -1
- package/dist/index-CU5XRZOh.d.ts.map +0 -1
- package/dist/index-xTZ5vAgA.d.cts.map +0 -1
- package/dist/index.d.ts +0 -6
- package/dist/index.js +0 -1
- package/dist/stream-limiter-CTLrikR_.js +0 -2
- package/dist/stream-limiter-CTLrikR_.js.map +0 -1
- package/dist/stream-limiter-CaCFrKY1.cjs +0 -1
- package/dist/streams/index.d.ts +0 -3
- package/dist/streams/index.js +0 -1
- package/dist/types/index.d.ts +0 -6
- package/dist/types/index.js +0 -1
- package/dist/types-BVbqP7yA.cjs +0 -1
- package/dist/types-DqllXpuL.js +0 -2
- package/dist/types-DqllXpuL.js.map +0 -1
- package/dist/upload/index.d.ts +0 -6
- package/dist/upload/index.js +0 -1
- package/dist/upload-C_n7Smfl.js +0 -2
- package/dist/upload-C_n7Smfl.js.map +0 -1
- package/dist/upload-kFnf82ds.cjs +0 -1
- package/dist/uploadista-error-CDkJ_Vrc.js.map +0 -1
- package/dist/uploadista-error-kZCQLC_U.d.ts.map +0 -1
- package/dist/utils/index.js +0 -1
- package/dist/utils-B5sYo1z9.js +0 -2
- package/dist/utils-B5sYo1z9.js.map +0 -1
- /package/dist/{errors-8i_aMxOE.js → errors-C0zLx77t.mjs} +0 -0
- /package/dist/{errors-D-K-vxsP.cjs → errors-CRm1FHHT.cjs} +0 -0
- /package/dist/{index-BoGG5KAY.d.ts → index-DEHBdV_z.d.mts} +0 -0
- /package/dist/{streams-Bs3GDNKJ.js → streams-CJKKIAwy.mjs} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require(`./types-C80hlY_o.cjs`),t=require(`./uploadista-error-CQ1ADme7.cjs`);let n=require(`effect`);var r=class extends n.Context.Tag(`UploadistaGenerateIdService`)(){};const i=r.Service,a=r.of({generateId:()=>n.Effect.succeed(crypto.randomUUID())}),o=n.Layer.succeed(r,a),s=r.of({generateId:()=>n.Effect.succeed(`${Date.now()}-${Math.random().toString(36).slice(2,11)}`)}),c=[`sha256`];function l(e){return c.includes(e)}function u(e,r){return n.Effect.gen(function*(){if(!l(r))return yield*t.n.fromCode(`UNSUPPORTED_CHECKSUM_ALGORITHM`,{body:`Checksum algorithm '${r}' is not supported. Supported algorithms: ${c.join(`, `)}`,details:{algorithm:r,supportedAlgorithms:c}}).toEffect();let i=r.toUpperCase().replace(/\d+/,`-$&`),a=yield*n.Effect.tryPromise({try:()=>crypto.subtle.digest(i,e),catch:e=>t.n.fromCode(`UNKNOWN_ERROR`,{body:`Failed to compute checksum: ${e instanceof Error?e.message:`Unknown error`}`,cause:e,details:{algorithm:r}})});return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,`0`)).join(``)})}Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return u}});
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./uploadista-error-U9YxwNtM.mjs";import{Context as t,Effect as n,Layer as r}from"effect";var i=class extends t.Tag(`UploadistaGenerateIdService`)(){};const a=i.Service,o=i.of({generateId:()=>n.succeed(crypto.randomUUID())}),s=r.succeed(i,o),c=i.of({generateId:()=>n.succeed(`${Date.now()}-${Math.random().toString(36).slice(2,11)}`)}),l=[`sha256`];function u(e){return l.includes(e)}function d(t,r){return n.gen(function*(){if(!u(r))return yield*e.fromCode(`UNSUPPORTED_CHECKSUM_ALGORITHM`,{body:`Checksum algorithm '${r}' is not supported. Supported algorithms: ${l.join(`, `)}`,details:{algorithm:r,supportedAlgorithms:l}}).toEffect();let i=r.toUpperCase().replace(/\d+/,`-$&`),a=yield*n.tryPromise({try:()=>crypto.subtle.digest(i,t),catch:t=>e.fromCode(`UNKNOWN_ERROR`,{body:`Failed to compute checksum: ${t instanceof Error?t.message:`Unknown error`}`,cause:t,details:{algorithm:r}})});return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,`0`)).join(``)})}export{o as a,s as i,u as n,a as o,i as r,c as s,d as t};
|
|
2
|
+
//# sourceMappingURL=checksum-Do_Vh-tB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checksum-Do_Vh-tB.mjs","names":[],"sources":["../src/utils/generate-id.ts","../src/utils/checksum.ts"],"sourcesContent":["import { Context, Effect, Layer } from \"effect\";\n\nexport type GenerateIdShape = {\n generateId: () => Effect.Effect<string>;\n};\n\n// Declaring a tag for a service that generates random id\nexport class GenerateId extends Context.Tag(\"UploadistaGenerateIdService\")<\n GenerateId,\n { readonly generateId: () => Effect.Effect<string> }\n>() {}\n\n/**\n * Effect-based ID generation services\n */\nexport const GenerateIdService = GenerateId.Service;\n\n/**\n * Generates a random UUID using Effect\n * @returns Effect that produces a random UUID string\n */\nexport const GenerateIdRandom = GenerateId.of({\n generateId: () => Effect.succeed(crypto.randomUUID()),\n});\n\nexport const GenerateIdLive = Layer.succeed(GenerateId, GenerateIdRandom);\n\n/**\n * Generates a timestamp-based ID using Effect\n * @returns Effect that produces a timestamp-based ID\n */\nexport const GenerateIdTimestamp = GenerateId.of({\n generateId: () =>\n Effect.succeed(`${Date.now()}-${Math.random().toString(36).slice(2, 11)}`),\n});\n","import { Effect } from \"effect\";\nimport { UploadistaError } from \"../errors/uploadista-error\";\n\n/**\n * Supported checksum algorithms\n */\nconst SUPPORTED_ALGORITHMS = [\"sha256\"] as const;\nexport type ChecksumAlgorithm = (typeof SUPPORTED_ALGORITHMS)[number];\n\n/**\n * Check if a checksum algorithm is supported\n */\nexport function isSupportedAlgorithm(algorithm: string): algorithm is ChecksumAlgorithm {\n return SUPPORTED_ALGORITHMS.includes(algorithm as ChecksumAlgorithm);\n}\n\n/**\n * Compute checksum of file bytes using the Web Crypto API.\n * This works across all modern platforms: browsers, Node.js 15+, Deno, Bun, and Cloudflare Workers.\n *\n * @param bytes - File content as Uint8Array\n * @param algorithm - Hashing algorithm to use (currently only 'sha256' is supported)\n * @returns Effect that resolves to hex-encoded checksum string\n */\nexport function computeChecksum(\n bytes: Uint8Array,\n algorithm: string,\n): Effect.Effect<string, UploadistaError> {\n return Effect.gen(function* () {\n // Validate algorithm is supported\n if (!isSupportedAlgorithm(algorithm)) {\n return yield* UploadistaError.fromCode(\"UNSUPPORTED_CHECKSUM_ALGORITHM\", {\n body: `Checksum algorithm '${algorithm}' is not supported. Supported algorithms: ${SUPPORTED_ALGORITHMS.join(\", \")}`,\n details: { algorithm, supportedAlgorithms: SUPPORTED_ALGORITHMS },\n }).toEffect();\n }\n\n // Map algorithm name to Web Crypto API algorithm name\n const webCryptoAlgorithm = algorithm.toUpperCase().replace(/\\d+/, \"-$&\"); // \"sha256\" -> \"SHA-256\"\n\n // Compute hash using Web Crypto API (available in browsers, Node.js 15+, Deno, Bun, Cloudflare Workers)\n // Pass Uint8Array directly - it's a valid BufferSource\n const hashBuffer = yield* Effect.tryPromise({\n try: () => crypto.subtle.digest(webCryptoAlgorithm, bytes as BufferSource),\n catch: (error) =>\n UploadistaError.fromCode(\"UNKNOWN_ERROR\", {\n body: `Failed to compute checksum: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n cause: error,\n details: { algorithm },\n }),\n });\n\n // Convert ArrayBuffer to hex string\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\n return hashHex;\n });\n}\n"],"mappings":"4GAOA,IAAa,EAAb,cAAgC,EAAQ,IAAI,8BAA8B,EAGvE,AAAC,GAKJ,MAAa,EAAoB,EAAW,QAM/B,EAAmB,EAAW,GAAG,CAC5C,eAAkB,EAAO,QAAQ,OAAO,YAAY,CAAC,CACtD,CAAC,CAEW,EAAiB,EAAM,QAAQ,EAAY,EAAiB,CAM5D,EAAsB,EAAW,GAAG,CAC/C,eACE,EAAO,QAAQ,GAAG,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAG,GAAG,GAAG,CAC7E,CAAC,CC5BI,EAAuB,CAAC,SAAS,CAMvC,SAAgB,EAAqB,EAAmD,CACtF,OAAO,EAAqB,SAAS,EAA+B,CAWtE,SAAgB,EACd,EACA,EACwC,CACxC,OAAO,EAAO,IAAI,WAAa,CAE7B,GAAI,CAAC,EAAqB,EAAU,CAClC,OAAO,MAAO,EAAgB,SAAS,iCAAkC,CACvE,KAAM,uBAAuB,EAAU,4CAA4C,EAAqB,KAAK,KAAK,GAClH,QAAS,CAAE,YAAW,oBAAqB,EAAsB,CAClE,CAAC,CAAC,UAAU,CAIf,IAAM,EAAqB,EAAU,aAAa,CAAC,QAAQ,MAAO,MAAM,CAIlE,EAAa,MAAO,EAAO,WAAW,CAC1C,QAAW,OAAO,OAAO,OAAO,EAAoB,EAAsB,CAC1E,MAAQ,GACN,EAAgB,SAAS,gBAAiB,CACxC,KAAM,+BAA+B,aAAiB,MAAQ,EAAM,QAAU,kBAC9E,MAAO,EACP,QAAS,CAAE,YAAW,CACvB,CAAC,CACL,CAAC,CAQF,OALkB,MAAM,KAAK,IAAI,WAAW,EAAW,CAAC,CAErD,IAAK,GAAS,EAAK,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAAC,CACjD,KAAK,GAAG,EAGX"}
|
package/dist/errors/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=require(`../uploadista-error-
|
|
1
|
+
const e=require(`../uploadista-error-CQ1ADme7.cjs`);require(`../errors-CRm1FHHT.cjs`),exports.ERRORS=e.t,exports.ERROR_CATALOG=e.t,exports.UploadistaError=e.n,exports.httpFailure=e.r,exports.isUploadistaError=e.i;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as isUploadistaError, i as httpFailure, n as UploadistaError, r as UploadistaErrorCode, t as ERROR_CATALOG } from "../uploadista-error-
|
|
2
|
-
import "../index-
|
|
1
|
+
import { a as isUploadistaError, i as httpFailure, n as UploadistaError, r as UploadistaErrorCode, t as ERROR_CATALOG } from "../uploadista-error-DHajuvP1.mjs";
|
|
2
|
+
import "../index-DEHBdV_z.mjs";
|
|
3
3
|
export { ERROR_CATALOG as ERRORS, ERROR_CATALOG, UploadistaError, UploadistaErrorCode, httpFailure, isUploadistaError };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"../uploadista-error-U9YxwNtM.mjs";import"../errors-C0zLx77t.mjs";export{r as ERRORS,r as ERROR_CATALOG,t as UploadistaError,n as httpFailure,e as isUploadistaError};
|
package/dist/flow/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
require(`../uploadista-error-
|
|
1
|
+
require(`../types-C80hlY_o.cjs`),require(`../uploadista-error-CQ1ADme7.cjs`),require(`../errors-CRm1FHHT.cjs`);const e=require(`../flow-C_doYlGf.cjs`);require(`../upload-IZuHoQqL.cjs`),require(`../checksum-DgutVB-2.cjs`),require(`../stream-limiter-Bj_iImMm.cjs`),exports.CredentialProvider=e.u,exports.EventType=e.j,exports.FlowProvider=e.b,exports.FlowServer=e.x,exports.FlowWaitUntil=e.S,exports.ImageAiPlugin=e.l,exports.ImagePlugin=e.c,exports.NodeType=e.O,exports.ParallelScheduler=e.D,exports.ZipPlugin=e.r,exports.completeNodeExecution=e.v,exports.createFlow=e.n,exports.createFlowEdge=e.M,exports.createFlowNode=e.k,exports.createFlowServer=e.C,exports.createFlowWithSchema=e.T,exports.createInputNode=e.m,exports.createStorageNode=e.f,exports.createTransformNode=e.d,exports.describeImageParamsSchema=e.s,exports.flowServer=e.w,exports.getFlowData=e.E,exports.getNodeData=e.A,exports.inputDataSchema=e.h,exports.inputNodeParamsSchema=e.g,exports.optimizeParamsSchema=e.o,exports.removeBackgroundParamsSchema=e.a,exports.resizeParamsSchema=e.i,exports.resolveUploadMetadata=e._,exports.runArgsSchema=e.t,exports.storageParamsSchema=e.p,exports.waitingNodeExecution=e.y;
|
package/dist/flow/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "../uploadista-error-B4dn0Ch6.cjs";
|
|
2
2
|
import "../index-BtBZHVmz.cjs";
|
|
3
|
-
import { $ as FlowServerShape, A as ImageAiContext, An as
|
|
3
|
+
import { $ as FlowServerShape, A as ImageAiContext, An as FlowEventFlowError, B as StorageParams, Bn as FlowEventNodeStart, C as describeImageParamsSchema, Cn as TypeCompatibilityChecker, D as resizeParamsSchema, Dn as FlowEvent, E as ResizeParams, En as EventType, F as ExecutionLevel, Fn as FlowEventNodeEnd, G as createInputNode, Gn as createFlowNode, H as storageParamsSchema, Hn as ConditionOperator, I as ParallelScheduler, In as FlowEventNodeError, J as FlowProvider, K as inputDataSchema, Kn as getNodeData, L as ParallelSchedulerConfig, Ln as FlowEventNodePause, M as ImageAiPluginShape, Mn as FlowEventFlowStart, N as CredentialProvider, Nn as FlowEventJobEnd, O as OptimizeParams, On as FlowEventFlowCancel, P as CredentialProviderShape, Pn as FlowEventJobStart, Q as FlowServerOptions, R as TransformNodeConfig, Rn as FlowEventNodeResponse, S as DescribeImageParams, Sn as NodeTypeMap, T as ImagePluginShape, Tn as waitingNodeExecution, U as InputData, Un as ConditionValue, V as createStorageNode, Vn as ConditionField, W as InputNodeParams, Wn as NodeType, X as FlowServer, Y as FlowProviderShape, Z as FlowServerLayer, _ as ZipParams, _n as FlowConfig, a as FlowCondition, at as FlowJobStatus, b as RemoveBackgroundParams, bn as NodeConnectionValidator, c as FlowPluginRequirements, d as NodeDefinitionsRecord, dn as FlowData, et as FlowWaitUntil, f as TypedFlow, fn as FlowExecutionResult, g as ZipInput, gn as createFlowEdge, h as createFlow, hn as FlowEdge, i as runArgsSchema, it as FlowJob, j as ImageAiPlugin, jn as FlowEventFlowPause, k as optimizeParamsSchema, kn as FlowEventFlowEnd, l as FlowRequirements, m as TypedFlowEdge, mn as getFlowData, n as resolveUploadMetadata, nt as createFlowServer, o as FlowInputMap, ot as FlowJobTask, p as TypedFlowConfig, pn as createFlowWithSchema, q as inputNodeParamsSchema, r as RunArgs, rt as flowServer, s as FlowOutputMap, st as FlowJobTaskStatus, t as ResolvedUploadMetadata, tt as WaitUntilCallback, u as NodeDefinition, un as Flow, v as ZipPlugin, vn as FlowNode, w as ImagePlugin, wn as completeNodeExecution, x as removeBackgroundParamsSchema, xn as NodeExecutionResult, y as ZipPluginShape, yn as FlowNodeData, z as createTransformNode, zn as FlowEventNodeResume } from "../index-Bg1HsPC1.cjs";
|
|
4
4
|
import "../index-eLYBkDBH.cjs";
|
|
5
5
|
import "../index-6oHIyVO9.cjs";
|
|
6
|
-
export { ConditionField, ConditionOperator, ConditionValue, CredentialProvider, CredentialProviderShape, DescribeImageParams, EventType, ExecutionLevel, Flow, FlowCondition, FlowConfig, FlowData, FlowEdge, FlowEvent, FlowEventFlowCancel, FlowEventFlowEnd, FlowEventFlowError, FlowEventFlowPause, FlowEventFlowStart, FlowEventJobEnd, FlowEventJobStart, FlowEventNodeEnd, FlowEventNodeError, FlowEventNodePause, FlowEventNodeResponse, FlowEventNodeResume, FlowEventNodeStart, FlowExecutionResult, FlowInputMap, FlowJob, FlowJobStatus, FlowJobTask, FlowJobTaskStatus, FlowNode, FlowNodeData, FlowOutputMap, FlowPluginRequirements, FlowProvider, FlowProviderShape, FlowRequirements, FlowServer, FlowServerLayer, FlowServerOptions, FlowServerShape, ImageAiContext, ImageAiPlugin, ImageAiPluginShape, ImagePlugin, ImagePluginShape, InputData, InputNodeParams, NodeConnectionValidator, NodeDefinition, NodeDefinitionsRecord, NodeExecutionResult, NodeType, NodeTypeMap, OptimizeParams, ParallelScheduler, ParallelSchedulerConfig, RemoveBackgroundParams, ResizeParams, ResolvedUploadMetadata, RunArgs, StorageParams, TransformNodeConfig, TypeCompatibilityChecker, TypedFlow, TypedFlowConfig, TypedFlowEdge, ZipInput, ZipParams, ZipPlugin, ZipPluginShape, completeNodeExecution, createFlow, createFlowEdge, createFlowNode, createFlowServer, createFlowWithSchema, createInputNode, createStorageNode, createTransformNode, describeImageParamsSchema, flowServer, getFlowData, getNodeData, inputDataSchema, inputNodeParamsSchema, optimizeParamsSchema, removeBackgroundParamsSchema, resizeParamsSchema, resolveUploadMetadata, runArgsSchema, storageParamsSchema, waitingNodeExecution };
|
|
6
|
+
export { ConditionField, ConditionOperator, ConditionValue, CredentialProvider, CredentialProviderShape, DescribeImageParams, EventType, ExecutionLevel, Flow, FlowCondition, FlowConfig, FlowData, FlowEdge, FlowEvent, FlowEventFlowCancel, FlowEventFlowEnd, FlowEventFlowError, FlowEventFlowPause, FlowEventFlowStart, FlowEventJobEnd, FlowEventJobStart, FlowEventNodeEnd, FlowEventNodeError, FlowEventNodePause, FlowEventNodeResponse, FlowEventNodeResume, FlowEventNodeStart, FlowExecutionResult, FlowInputMap, FlowJob, FlowJobStatus, FlowJobTask, FlowJobTaskStatus, FlowNode, FlowNodeData, FlowOutputMap, FlowPluginRequirements, FlowProvider, FlowProviderShape, FlowRequirements, FlowServer, FlowServerLayer, FlowServerOptions, FlowServerShape, FlowWaitUntil, ImageAiContext, ImageAiPlugin, ImageAiPluginShape, ImagePlugin, ImagePluginShape, InputData, InputNodeParams, NodeConnectionValidator, NodeDefinition, NodeDefinitionsRecord, NodeExecutionResult, NodeType, NodeTypeMap, OptimizeParams, ParallelScheduler, ParallelSchedulerConfig, RemoveBackgroundParams, ResizeParams, ResolvedUploadMetadata, RunArgs, StorageParams, TransformNodeConfig, TypeCompatibilityChecker, TypedFlow, TypedFlowConfig, TypedFlowEdge, WaitUntilCallback, ZipInput, ZipParams, ZipPlugin, ZipPluginShape, completeNodeExecution, createFlow, createFlowEdge, createFlowNode, createFlowServer, createFlowWithSchema, createInputNode, createStorageNode, createTransformNode, describeImageParamsSchema, flowServer, getFlowData, getNodeData, inputDataSchema, inputNodeParamsSchema, optimizeParamsSchema, removeBackgroundParamsSchema, resizeParamsSchema, resolveUploadMetadata, runArgsSchema, storageParamsSchema, waitingNodeExecution };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import "../uploadista-error-DHajuvP1.mjs";
|
|
2
|
+
import "../index-DEHBdV_z.mjs";
|
|
3
|
+
import { $ as FlowServerShape, A as ImageAiContext, An as FlowEventFlowError, B as StorageParams, Bn as FlowEventNodeStart, C as describeImageParamsSchema, Cn as TypeCompatibilityChecker, D as resizeParamsSchema, Dn as FlowEvent, E as ResizeParams, En as EventType, F as ExecutionLevel, Fn as FlowEventNodeEnd, G as createInputNode, Gn as createFlowNode, H as storageParamsSchema, Hn as ConditionOperator, I as ParallelScheduler, In as FlowEventNodeError, J as FlowProvider, K as inputDataSchema, Kn as getNodeData, L as ParallelSchedulerConfig, Ln as FlowEventNodePause, M as ImageAiPluginShape, Mn as FlowEventFlowStart, N as CredentialProvider, Nn as FlowEventJobEnd, O as OptimizeParams, On as FlowEventFlowCancel, P as CredentialProviderShape, Pn as FlowEventJobStart, Q as FlowServerOptions, R as TransformNodeConfig, Rn as FlowEventNodeResponse, S as DescribeImageParams, Sn as NodeTypeMap, T as ImagePluginShape, Tn as waitingNodeExecution, U as InputData, Un as ConditionValue, V as createStorageNode, Vn as ConditionField, W as InputNodeParams, Wn as NodeType, X as FlowServer, Y as FlowProviderShape, Z as FlowServerLayer, _ as ZipParams, _n as FlowConfig, a as FlowCondition, at as FlowJobStatus, b as RemoveBackgroundParams, bn as NodeConnectionValidator, c as FlowPluginRequirements, d as NodeDefinitionsRecord, dn as FlowData, et as FlowWaitUntil, f as TypedFlow, fn as FlowExecutionResult, g as ZipInput, gn as createFlowEdge, h as createFlow, hn as FlowEdge, i as runArgsSchema, it as FlowJob, j as ImageAiPlugin, jn as FlowEventFlowPause, k as optimizeParamsSchema, kn as FlowEventFlowEnd, l as FlowRequirements, m as TypedFlowEdge, mn as getFlowData, n as resolveUploadMetadata, nt as createFlowServer, o as FlowInputMap, ot as FlowJobTask, p as TypedFlowConfig, pn as createFlowWithSchema, q as inputNodeParamsSchema, r as RunArgs, rt as flowServer, s as FlowOutputMap, st as FlowJobTaskStatus, t as ResolvedUploadMetadata, tt as WaitUntilCallback, u as NodeDefinition, un as Flow, v as ZipPlugin, vn as FlowNode, w as ImagePlugin, wn as completeNodeExecution, x as removeBackgroundParamsSchema, xn as NodeExecutionResult, y as ZipPluginShape, yn as FlowNodeData, z as createTransformNode, zn as FlowEventNodeResume } from "../index-BQ8Ns-NS.mjs";
|
|
4
|
+
import "../index-C2nrn_49.mjs";
|
|
5
|
+
import "../index-CsLVxsad.mjs";
|
|
6
|
+
export { ConditionField, ConditionOperator, ConditionValue, CredentialProvider, CredentialProviderShape, DescribeImageParams, EventType, ExecutionLevel, Flow, FlowCondition, FlowConfig, FlowData, FlowEdge, FlowEvent, FlowEventFlowCancel, FlowEventFlowEnd, FlowEventFlowError, FlowEventFlowPause, FlowEventFlowStart, FlowEventJobEnd, FlowEventJobStart, FlowEventNodeEnd, FlowEventNodeError, FlowEventNodePause, FlowEventNodeResponse, FlowEventNodeResume, FlowEventNodeStart, FlowExecutionResult, FlowInputMap, FlowJob, FlowJobStatus, FlowJobTask, FlowJobTaskStatus, FlowNode, FlowNodeData, FlowOutputMap, FlowPluginRequirements, FlowProvider, FlowProviderShape, FlowRequirements, FlowServer, FlowServerLayer, FlowServerOptions, FlowServerShape, FlowWaitUntil, ImageAiContext, ImageAiPlugin, ImageAiPluginShape, ImagePlugin, ImagePluginShape, InputData, InputNodeParams, NodeConnectionValidator, NodeDefinition, NodeDefinitionsRecord, NodeExecutionResult, NodeType, NodeTypeMap, OptimizeParams, ParallelScheduler, ParallelSchedulerConfig, RemoveBackgroundParams, ResizeParams, ResolvedUploadMetadata, RunArgs, StorageParams, TransformNodeConfig, TypeCompatibilityChecker, TypedFlow, TypedFlowConfig, TypedFlowEdge, WaitUntilCallback, ZipInput, ZipParams, ZipPlugin, ZipPluginShape, completeNodeExecution, createFlow, createFlowEdge, createFlowNode, createFlowServer, createFlowWithSchema, createInputNode, createStorageNode, createTransformNode, describeImageParamsSchema, flowServer, getFlowData, getNodeData, inputDataSchema, inputNodeParamsSchema, optimizeParamsSchema, removeBackgroundParamsSchema, resizeParamsSchema, resolveUploadMetadata, runArgsSchema, storageParamsSchema, waitingNodeExecution };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"../uploadista-error-U9YxwNtM.mjs";import"../errors-C0zLx77t.mjs";import{A as e,C as t,D as n,E as r,M as i,O as a,S as o,T as s,_ as c,a as l,b as u,c as d,d as f,f as p,g as m,h,i as g,j as _,k as v,l as y,m as b,n as x,o as S,p as C,r as w,s as T,t as E,u as D,v as O,w as k,x as A,y as j}from"../flow-DEohelFR.mjs";import"../types-BYfvxhhG.mjs";import"../upload-CcmxSO5u.mjs";import"../checksum-Do_Vh-tB.mjs";import"../stream-limiter-CEpDLQVB.mjs";export{D as CredentialProvider,_ as EventType,u as FlowProvider,A as FlowServer,o as FlowWaitUntil,y as ImageAiPlugin,d as ImagePlugin,a as NodeType,n as ParallelScheduler,w as ZipPlugin,O as completeNodeExecution,x as createFlow,i as createFlowEdge,v as createFlowNode,t as createFlowServer,s as createFlowWithSchema,b as createInputNode,p as createStorageNode,f as createTransformNode,T as describeImageParamsSchema,k as flowServer,r as getFlowData,e as getNodeData,h as inputDataSchema,m as inputNodeParamsSchema,S as optimizeParamsSchema,l as removeBackgroundParamsSchema,g as resizeParamsSchema,c as resolveUploadMetadata,E as runArgsSchema,C as storageParamsSchema,j as waitingNodeExecution};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require(`./types-C80hlY_o.cjs`),t=require(`./uploadista-error-CQ1ADme7.cjs`),n=require(`./upload-IZuHoQqL.cjs`);let r=require(`effect`),i=require(`zod`);function a({source:e,target:t,sourcePort:n,targetPort:r}){return{source:e,target:t,sourcePort:n,targetPort:r}}let o=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}({}),s=function(e){return e.input=`input`,e.process=`process`,e.output=`output`,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}){return r.Effect.succeed({id:e,name:n,description:i,type:a,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`?f:{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})}})}}),condition:l,multiInput:u,multiOutput:d,retry:p})}const l=e=>({id:e.id,name:e.name,description:e.description,type:e.type});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}}};const d=(e,t)=>{if(e===t)return!0;try{return!!(e&&t&&typeof e==`object`&&typeof t==`object`)}catch{return!0}};var f=class{typeChecker;constructor(e=d){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`]}}}};const p=e=>({id:e.id,name:e.name,nodes:e.nodes.map(l),edges:e.edges});function m(e){return r.Effect.gen(function*(){let n=yield*r.Effect.all(e.nodes.map(e=>r.Effect.isEffect(e)?e:r.Effect.succeed(e))),{flowId:a,name:s,onEvent:c,checkJobStatus:l,edges:d,inputSchema:p,outputSchema:m,typeChecker:h}=e,g=n,_=new f(h),v=()=>{let e={},t={},n={};return g.forEach(r=>{e[r.id]=[],n[r.id]=[],t[r.id]=0}),d.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}},y=()=>{let{graph:e,inDegree:t}=v(),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},b=(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)},x=(e,t)=>{let{reverseGraph:n}=v(),r=n[e]||[],i={};return r.forEach(e=>{let n=t.get(e);n!==void 0&&(i[e]=n)}),i},S=e=>{let t=g.filter(e=>e.type===`input`),n={};return t.forEach(t=>{e&&typeof e==`object`&&t.id in e&&(n[t.id]=p.parse(e[t.id]))}),n},C=e=>{let t=g.filter(e=>e.type===`output`),n={};return t.forEach(t=>{let r=e.get(t.id);r!==void 0&&(n[t.id]=r)}),n},w=(e,n,i,s,u,d,f)=>r.Effect.gen(function*(){let p=u.get(e);if(!p)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 ${a} was paused by user at job ${d}`}).toEffect();if(e===`cancelled`)return yield*t.n.fromCode(`FLOW_CANCELLED`,{cause:`Flow ${a} was cancelled by user at job ${d}`}).toEffect()}c&&(yield*c({jobId:d,flowId:a,nodeId:e,eventType:o.NodeStart,nodeName:p.name,nodeType:p.type}));let m=p.retry?.maxRetries??0,h=p.retry?.retryDelay??1e3,g=p.retry?.exponentialBackoff??!0,_=0,v=null;for(;_<=m;)try{let l,u={};if(p.type===`input`){if(l=i[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=x(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(p.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(p.type===`conditional`&&!(yield*b(p,l)))return c&&(yield*c({jobId:d,flowId:a,nodeId:e,eventType:o.NodeEnd,nodeName:p.name})),{nodeId:e,result:l,success:!0,waiting:!1};let m=yield*p.run({data:l,inputs:u,jobId:d,flowId:a,storageId:n,clientId:f});if(m.type===`waiting`){let t=m.partialData;return c&&(yield*c({jobId:d,flowId:a,nodeId:e,eventType:o.NodePause,nodeName:p.name,partialData:t})),{nodeId:e,result:t,success:!0,waiting:!0}}let h=m.data;return c&&(yield*c({jobId:d,flowId:a,nodeId:e,eventType:o.NodeEnd,nodeName:p.name,result:h})),{nodeId:e,result:h,success:!0,waiting:!1}}catch(n){if(v=n instanceof t.n?n:t.n.fromCode(`FLOW_NODE_ERROR`,{cause:n}),_<m){_++;let t=g?h*2**(_-1):h;yield*r.Effect.logWarning(`Node ${e} (${p.name}) failed, retrying (${_}/${m}) after ${t}ms`),yield*r.Effect.sleep(t);continue}return c&&(yield*c({jobId:d,flowId:a,nodeId:e,eventType:o.NodeError,nodeName:p.name,error:v.body,retryCount:_})),yield*v.toEffect()}return v?yield*v.toEffect():yield*t.n.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Unexpected error in retry loop`)}).toEffect()}),T=({inputs:n,storageId:s,jobId:l,resumeFrom:f,clientId:p})=>r.Effect.gen(function*(){!f&&c&&(yield*c({jobId:l,eventType:o.FlowStart,flowId:a}));let h=S(n||{}),_,v,b;if(f)_=f.executionOrder,v=f.nodeResults,b=f.currentIndex;else if(_=y(),v=new Map,b=0,_.length!==g.length)return yield*t.n.fromCode(`FLOW_CYCLE_ERROR`).toEffect();let x=new Map(g.map(e=>[e.id,e]));if(e.parallelExecution?.enabled??!1){yield*r.Effect.logDebug(`Flow ${a}: Executing in parallel mode (maxConcurrency: ${e.parallelExecution?.maxConcurrency??4})`);let t=new u({maxConcurrency:e.parallelExecution?.maxConcurrency??4}),n=t.groupNodesByExecutionLevel(g,d);yield*r.Effect.logDebug(`Flow ${a}: Grouped nodes into ${n.length} execution levels`);let i={};g.forEach(e=>{i[e.id]=[]}),d.forEach(e=>{i[e.target]?.push(e.source)});for(let e of n){yield*r.Effect.logDebug(`Flow ${a}: Executing level ${e.level} with nodes: ${e.nodes.join(`, `)}`);let n=e.nodes.map(e=>()=>r.Effect.gen(function*(){if(f&&e===f.executionOrder[b]&&c){let t=x.get(e);t&&(yield*c({jobId:l,flowId:a,nodeId:e,eventType:o.NodeResume,nodeName:t.name,nodeType:t.type}))}return{nodeId:e,nodeResult:yield*w(e,s,h,v,x,l,p)}})),i=yield*t.executeNodesInParallel(n);for(let{nodeId:e,nodeResult:t}of i){if(t.waiting)return t.result!==void 0&&v.set(e,t.result),{type:`paused`,nodeId:e,executionState:{executionOrder:_,currentIndex:_.indexOf(e),inputs:h}};t.success&&v.set(e,t.result)}}}else{yield*r.Effect.logDebug(`Flow ${a}: Executing in sequential mode`);for(let e=b;e<_.length;e++){let n=_[e];if(!n)return yield*t.n.fromCode(`FLOW_NODE_NOT_FOUND`).toEffect();if(f&&e===b&&c){let e=x.get(n);e&&(yield*c({jobId:l,flowId:a,nodeId:n,eventType:o.NodeResume,nodeName:e.name,nodeType:e.type}))}let r=yield*w(n,s,h,v,x,l,p);if(r.waiting)return r.result!==void 0&&v.set(r.nodeId,r.result),{type:`paused`,nodeId:r.nodeId,executionState:{executionOrder:_,currentIndex:e,inputs:h}};r.success&&v.set(r.nodeId,r.result)}}let T=C(v),E=i.z.record(i.z.string(),m).safeParse(T);if(!E.success){let e=`Flow output validation failed: ${E.error.message}. Expected outputs: ${JSON.stringify(Object.keys(C(v)))}. Output nodes: ${g.filter(e=>e.type===`output`).map(e=>e.id).join(`, `)}`;return c&&(yield*c({jobId:l,eventType:o.FlowError,flowId:a,error:e})),yield*t.n.fromCode(`FLOW_OUTPUT_VALIDATION_ERROR`,{body:e,cause:E.error}).toEffect()}let D=E.data;return c&&(yield*c({jobId:l,eventType:o.FlowEnd,flowId:a,result:D})),{type:`completed`,result:D}});return{id:a,name:s,nodes:g,edges:d,inputSchema:p,outputSchema:m,onEvent:c,checkJobStatus:l,run:({inputs:e,storageId:t,jobId:n,clientId:r})=>T({inputs:e,storageId:t,jobId:n,clientId:r}),resume:({jobId:e,storageId:t,nodeResults:n,executionState:r,clientId:i})=>T({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=g;return _.validateFlow(e,d)},validateInputs:e=>_.validateData(e,p),validateOutputs:e=>_.validateData(e,m)}})}var h=class e extends r.Context.Tag(`FlowWaitUntil`)(){static optional=r.Effect.serviceOption(e)},g=class extends r.Context.Tag(`FlowProvider`)(){},_=class extends r.Context.Tag(`FlowServer`)(){};const v=e=>typeof e==`object`&&!!e&&`id`in e;function y(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 s=>r.Effect.gen(function*(){switch(e.onEvent&&(yield*r.Effect.catchAll(e.onEvent(s),e=>(r.Effect.logError(`Original onEvent failed`,e),r.Effect.succeed({eventId:null})))),yield*n.emit(t,s),r.Effect.logInfo(`Updating job ${t} with event ${s.eventType}`),s.eventType){case o.FlowStart:yield*a({status:`running`});break;case o.FlowEnd:break;case o.FlowError:yield*a({status:`failed`,error:s.error});break;case o.NodeStart:yield*r.Effect.gen(function*(){let e=yield*i.get(t);if(e){let n=e.tasks.find(e=>e.nodeId===s.nodeId)?e.tasks.map(e=>e.nodeId===s.nodeId?{...e,status:`running`,updatedAt:new Date}:e):[...e.tasks,{nodeId:s.nodeId,status:`running`,createdAt:new Date,updatedAt:new Date}];yield*i.set(t,{...e,tasks:n,updatedAt:new Date})}});break;case o.NodePause:yield*r.Effect.gen(function*(){let e=yield*i.get(t);if(e){let n=e.tasks.find(e=>e.nodeId===s.nodeId)?e.tasks.map(e=>e.nodeId===s.nodeId?{...e,status:`paused`,result:s.partialData,updatedAt:new Date}:e):[...e.tasks,{nodeId:s.nodeId,status:`paused`,result:s.partialData,createdAt:new Date,updatedAt:new Date}];yield*i.set(t,{...e,tasks:n,updatedAt:new Date})}});break;case o.NodeResume:yield*r.Effect.gen(function*(){let e=yield*i.get(t);if(e){let n=e.tasks.map(e=>e.nodeId===s.nodeId?{...e,status:`running`,updatedAt:new Date}:e);yield*i.set(t,{...e,tasks:n,updatedAt:new Date})}});break;case o.NodeEnd:yield*r.Effect.gen(function*(){let n=yield*i.get(t);if(n){let r=n.tasks.map(e=>e.nodeId===s.nodeId?{...e,status:`completed`,result:s.result,updatedAt:new Date}:e),a=e.nodes.find(e=>e.id===s.nodeId)?.type===`output`,o=s.result,c=n.intermediateFiles||[];a&&v(o)&&o.id?c=c.filter(e=>e!==o.id):!a&&v(o)&&o.id&&(c.includes(o.id)||c.push(o.id)),yield*i.set(t,{...n,tasks:r,intermediateFiles:c,updatedAt:new Date})}});break;case o.NodeError:yield*r.Effect.gen(function*(){let e=yield*i.get(t);if(e){let n=e.tasks.map(e=>e.nodeId===s.nodeId?{...e,status:`failed`,error:s.error,retryCount:s.retryCount,updatedAt:new Date}:e);yield*i.set(t,{...e,tasks:n,error:s.error,updatedAt:new Date})}});break}return{eventId:t}})},s=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=s(n);return yield*(yield*m({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=s(n);return yield*(yield*m({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 b(){return r.Effect.gen(function*(){let i=yield*g,a=yield*e.g,s=yield*e.c,c=yield*n.n,l=(e,n)=>r.Effect.gen(function*(){let i=yield*s.get(e);return i?yield*s.set(e,{...i,...n}):yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found`}))}),u=(e,t)=>r.Effect.gen(function*(){let n=yield*s.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*c.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*l(e,{intermediateFiles:[]}))}),d=({jobId:e,flow:n,storageId:i,clientId:c,inputs:d})=>r.Effect.gen(function*(){console.log(`[FlowServer] executeFlowInBackground started for job: ${e}`),yield*l(e,{status:`running`}),console.log(`[FlowServer] Creating flowWithEvents for job: ${e}`);let t=y(n,a,s);console.log(`[FlowServer] Running flow for job: ${e}`);let r=yield*t.run({inputs:d,storageId:i,jobId:e,clientId:c});return console.log(`[FlowServer] Flow completed for job: ${e}, result type: ${r.type}`),r.type===`paused`?yield*l(e,{status:`paused`,pausedAt:r.nodeId,executionState:r.executionState,updatedAt:new Date}):(yield*l(e,{status:`completed`,result:r.result,updatedAt:new Date,endedAt:new Date}),yield*u(e,c)),r}).pipe(r.Effect.catchAll(n=>r.Effect.gen(function*(){yield*r.Effect.logError(`Flow execution 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*l(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 d=yield*s.get(e);throw d&&(yield*a.emit(e,{jobId:e,eventType:o.FlowError,flowId:d.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*u(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)}))),n})));return{getFlow:(e,t)=>r.Effect.gen(function*(){return yield*i.getFlow(e,t)}),getFlowData:(e,t)=>r.Effect.gen(function*(){return p(yield*i.getFlow(e,t))}),runFlow:({flowId:e,storageId:n,clientId:a,inputs:o})=>r.Effect.gen(function*(){let c=yield*h.optional,l=yield*r.Effect.try({try:()=>G.parse({inputs:o}),catch:e=>t.n.fromCode(`FLOW_INPUT_VALIDATION_ERROR`,{cause:e})}),u=crypto.randomUUID(),f=new Date,p={id:u,flowId:e,storageId:n,clientId:a,status:`started`,createdAt:f,updatedAt:f,tasks:[]};yield*s.set(u,p);let m=yield*i.getFlow(e,a);console.log(`[FlowServer] About to fork flow execution for job: ${u}`);let g=d({jobId:u,flow:m,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)(g);c.value(t)}else console.log(`[FlowServer] Using Effect.forkDaemon for job: ${u}`),yield*r.Effect.forkDaemon(g);return console.log(`[FlowServer] Flow execution started for job: ${u}`),p}),getJobStatus:e=>r.Effect.gen(function*(){return(yield*s.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:d})=>r.Effect.gen(function*(){let f=yield*h.optional,p=yield*s.get(e);if(!p)return console.error(`Job not found`),yield*r.Effect.fail(t.n.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${e} not found`}));if(p.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: ${p.status})`}));if(p.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 ${p.pausedAt}, not ${n}`}));if(!p.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 m={...p.tasks.reduce((e,t)=>(t.result!==void 0&&(e[t.nodeId]=t.result),e),{}),[n]:c},g={...p.executionState.inputs,[n]:c};yield*l(e,{status:`running`});let _=yield*i.getFlow(p.flowId,p.clientId),v=r.Effect.gen(function*(){let n=y(_,a,s);if(!p.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:p.storageId,nodeResults:m,executionState:{...p.executionState,inputs:g},clientId:p.clientId});return i.type===`paused`?yield*l(e,{status:`paused`,pausedAt:i.nodeId,executionState:i.executionState,updatedAt:new Date}):(yield*l(e,{status:`completed`,pausedAt:void 0,executionState:void 0,result:i.result,updatedAt:new Date,endedAt:new Date}),yield*u(e,d)),i}).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*l(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*s.get(e);throw c&&(yield*a.emit(e,{jobId:e,eventType:o.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*u(e,d).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)}))),n}))).pipe(r.Effect.tapErrorCause(e=>r.Effect.logError(`Flow resume failed`,e)));if(r.Option.isSome(f)){console.log(`[FlowServer] Using waitUntil for resume job: ${e}`);let t=yield*r.Effect.runtime(),n=r.Runtime.runPromise(t)(v);f.value(n)}else console.log(`[FlowServer] Using Effect.forkDaemon for resume job: ${e}`),yield*r.Effect.forkDaemon(v);return(yield*s.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*s.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 c=i.tasks.find(e=>e.status===`running`)?.nodeId;return yield*l(e,{status:`paused`,pausedAt:c,updatedAt:new Date}),yield*a.emit(e,{jobId:e,flowId:i.flowId,eventType:o.FlowPause,pausedAt:c}),(yield*s.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*s.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*l(e,{status:`cancelled`,updatedAt:new Date,endedAt:new Date}),yield*a.emit(e,{jobId:e,flowId:i.flowId,eventType:o.FlowCancel}),yield*u(e,n),(yield*s.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 x=r.Layer.effect(_,b()),S=e=>({type:`complete`,data:e}),C=e=>({type:`waiting`,partialData:e});function w(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 T=i.z.object({operation:i.z.literal(`init`),storageId:i.z.string(),metadata:i.z.record(i.z.string(),i.z.any()).optional()}),E=i.z.object({operation:i.z.literal(`finalize`),uploadId:i.z.string()}),D=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()}),O=i.z.union([T,E,D]),k=i.z.object({allowedMimeTypes:i.z.array(i.z.string()).optional(),minSize:i.z.number().positive().optional(),maxSize:i.z.number().positive().optional()});function A(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 j(i,a){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,inputSchema:O,outputSchema:e.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 C(yield*o.createUpload(t,l))}case`finalize`:{let t=yield*o.getUpload(e.uploadId),{type:n}=w(t.metadata);return yield*A({type:n,size:t.size||0},a),S(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*A({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 S({...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 M=i.z.object({});function N(i,a=e=>r.Effect.succeed(e)){return r.Effect.gen(function*(){let o=yield*n.n;return yield*c({id:i,name:`Storage`,description:`Stores a file in the storage`,type:s.output,inputSchema:e.i,outputSchema:e.i,run:({data:e,storageId:n,flowId:s,jobId:c,clientId:l})=>r.Effect.gen(function*(){let{type:u,fileName:d,metadata:f,metadataJson:p}=w(e.metadata),m={flowId:s,nodeId:i,jobId:c},h=f?{...e,metadata:f}:e,g=yield*o.getUpload(e.id);if(!g.id)return yield*r.Effect.fail(t.n.fromCode(`FILE_READ_ERROR`,Error(`Upload Key is undefined`)));if(g.storage.id===n)return S(yield*a({...h,flow:m}));let _=yield*o.read(e.id,l),v=new ReadableStream({start(e){e.enqueue(_),e.close()}}),y=yield*o.upload({storageId:n,size:_.byteLength,type:u,fileName:d,lastModified:0,metadata:p,flow:m},l,v),b=w(y.metadata);return S(yield*a(b.metadata?{...y,metadata:b.metadata}:y))})})})}function P({id:t,name:i,description:a,transform:o}){return r.Effect.gen(function*(){let l=yield*n.n;return yield*c({id:t,name:i,description:a,type:s.process,inputSchema:e.i,outputSchema:e.i,run:({data:e,storageId:n,flowId:i,jobId:a,clientId:s})=>r.Effect.gen(function*(){let r={flowId:i,nodeId:t,jobId:a},c=yield*o(yield*l.read(e.id,s),e),u=c instanceof Uint8Array?c:c.bytes,d=c instanceof Uint8Array?void 0:c.type,f=c instanceof Uint8Array?void 0:c.fileName,p=new ReadableStream({start(e){e.enqueue(u),e.close()}}),{type:m,fileName:h,metadata:g,metadataJson:_}=w(e.metadata),v=yield*l.upload({storageId:n,size:u.byteLength,type:d??m,fileName:f??h,lastModified:0,metadata:_,flow:r},s,p);return S(g?{...v,metadata:g}:v)})})})}var F=class extends r.Context.Tag(`CredentialProvider`)(){},I=class extends r.Context.Tag(`ImageAiPlugin`)(){},L=class extends r.Context.Tag(`ImagePlugin`)(){};const R=i.z.object({serviceType:i.z.enum([`replicate`]).optional()}),z=i.z.object({quality:i.z.number().min(0).max(100),format:i.z.enum([`jpeg`,`webp`,`png`,`avif`])}),B=i.z.object({serviceType:i.z.enum([`replicate`]).optional()}),V=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`);var H=class extends r.Context.Tag(`ZipPlugin`)(){};const U=(e,t)=>{if(e.length===0)return t;let[n,...r]=e;return r.reduce((e,t)=>i.z.union([e,t]),n)};function W(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}`)})))),c=Object.fromEntries(o),l=o.map(([,e])=>e),u=o.filter(([,e])=>e.type===s.input).map(([,e])=>e.inputSchema),d=o.filter(([,e])=>e.type===s.output).map(([,e])=>e.outputSchema),f=e.inputSchema??U(u,i.z.unknown()),p=e.outputSchema??U(d,i.z.unknown()),h=e.edges.map(e=>({source:c[e.source]?.id??e.source,target:c[e.target]?.id??e.target,sourcePort:e.sourcePort,targetPort:e.targetPort}));return yield*m({flowId:e.flowId,name:e.name,nodes:l,edges:h,inputSchema:f,outputSchema:p,typeChecker:e.typeChecker,onEvent:e.onEvent,parallelExecution:e.parallelExecution})})}const G=i.z.object({inputs:i.z.record(i.z.string(),i.z.any())});Object.defineProperty(exports,`A`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return C}});
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e}from"./uploadista-error-U9YxwNtM.mjs";import{c as t,g as n,i as r}from"./types-BYfvxhhG.mjs";import{a as i,n as a,o}from"./upload-CcmxSO5u.mjs";import{Context as s,Effect as c,Layer as l,Option as u,Runtime as d}from"effect";import{z as f}from"zod";function p({source:e,target:t,sourcePort:n,targetPort:r}){return{source:e,target:t,sourcePort:n,targetPort:r}}let m=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}({}),h=function(e){return e.input=`input`,e.process=`process`,e.output=`output`,e.conditional=`conditional`,e.multiplex=`multiplex`,e.merge=`merge`,e}({});function g({id:t,name:n,description:r,type:i,inputSchema:a,outputSchema:o,run:s,condition:l,multiInput:u=!1,multiOutput:d=!1,pausable:f=!1,retry:p}){return c.succeed({id:t,name:n,description:r,type:i,inputSchema:a,outputSchema:o,pausable:f,run:({data:r,jobId:i,flowId:l,storageId:u,clientId:d})=>c.gen(function*(){let f=yield*s({data:yield*c.try({try:()=>a.parse(r),catch:r=>{let i=r instanceof Error?r.message:String(r);return e.fromCode(`FLOW_INPUT_VALIDATION_ERROR`,{body:`Node '${n}' (${t}) input validation failed: ${i}`,cause:r})}}),jobId:i,storageId:u,flowId:l,clientId:d});return f.type===`waiting`?f:{type:`complete`,data:yield*c.try({try:()=>o.parse(f.data),catch:r=>{let i=r instanceof Error?r.message:String(r);return e.fromCode(`FLOW_OUTPUT_VALIDATION_ERROR`,{body:`Node '${n}' (${t}) output validation failed: ${i}`,cause:r})}})}}),condition:l,multiInput:u,multiOutput:d,retry:p})}const _=e=>({id:e.id,name:e.name,description:e.description,type:e.type});var v=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 c.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}}};const y=(e,t)=>{if(e===t)return!0;try{return!!(e&&t&&typeof e==`object`&&typeof t==`object`)}catch{return!0}};var b=class{typeChecker;constructor(e=y){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`]}}}};const x=e=>({id:e.id,name:e.name,nodes:e.nodes.map(_),edges:e.edges});function S(t){return c.gen(function*(){let n=yield*c.all(t.nodes.map(e=>c.isEffect(e)?e:c.succeed(e))),{flowId:r,name:i,onEvent:a,checkJobStatus:o,edges:s,inputSchema:l,outputSchema:u,typeChecker:d}=t,p=n,h=new b(d),g=()=>{let e={},t={},n={};return p.forEach(r=>{e[r.id]=[],n[r.id]=[],t[r.id]=0}),s.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}},_=()=>{let{graph:e,inDegree:t}=g(),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},y=(e,t)=>{if(!e.condition)return c.succeed(!0);let{field:n,operator:r,value:i}=e.condition,a=t,o=a?.metadata?.[n]||a?.[n],s=(()=>{switch(r){case`equals`:return o===i;case`notEquals`:return o!==i;case`greaterThan`:return Number(o)>Number(i);case`lessThan`:return Number(o)<Number(i);case`contains`:return String(o).includes(String(i));case`startsWith`:return String(o).startsWith(String(i));default:return!0}})();return c.succeed(s)},x=(e,t)=>{let{reverseGraph:n}=g(),r=n[e]||[],i={};return r.forEach(e=>{let n=t.get(e);n!==void 0&&(i[e]=n)}),i},S=e=>{let t=p.filter(e=>e.type===`input`),n={};return t.forEach(t=>{e&&typeof e==`object`&&t.id in e&&(n[t.id]=l.parse(e[t.id]))}),n},C=e=>{let t=p.filter(e=>e.type===`output`),n={};return t.forEach(t=>{let r=e.get(t.id);r!==void 0&&(n[t.id]=r)}),n},w=(t,n,i,s,l,u,d)=>c.gen(function*(){let f=l.get(t);if(!f)return yield*e.fromCode(`FLOW_NODE_NOT_FOUND`).toEffect();if(o){let t=yield*o(u);if(t===`paused`)return yield*e.fromCode(`FLOW_PAUSED`,{cause:`Flow ${r} was paused by user at job ${u}`}).toEffect();if(t===`cancelled`)return yield*e.fromCode(`FLOW_CANCELLED`,{cause:`Flow ${r} was cancelled by user at job ${u}`}).toEffect()}a&&(yield*a({jobId:u,flowId:r,nodeId:t,eventType:m.NodeStart,nodeName:f.name,nodeType:f.type}));let p=f.retry?.maxRetries??0,h=f.retry?.retryDelay??1e3,g=f.retry?.exponentialBackoff??!0,_=0,v=null;for(;_<=p;)try{let o,l={};if(f.type===`input`){if(o=i[t],o===void 0)return yield*c.logError(`Input node ${t} has no input data`),yield*e.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Input node ${t} has no input data`)}).toEffect()}else{if(l=x(t,s),Object.keys(l).length===0)return yield*c.logError(`Node ${t} has no input data`),yield*e.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Node ${t} has no input data`)}).toEffect();if(f.multiInput)o=l;else{let n=Object.keys(l)[0];if(!n)return yield*e.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Node ${t} has no input data`)}).toEffect();o=l[n]}}if(f.type===`conditional`&&!(yield*y(f,o)))return a&&(yield*a({jobId:u,flowId:r,nodeId:t,eventType:m.NodeEnd,nodeName:f.name})),{nodeId:t,result:o,success:!0,waiting:!1};let p=yield*f.run({data:o,inputs:l,jobId:u,flowId:r,storageId:n,clientId:d});if(p.type===`waiting`){let e=p.partialData;return a&&(yield*a({jobId:u,flowId:r,nodeId:t,eventType:m.NodePause,nodeName:f.name,partialData:e})),{nodeId:t,result:e,success:!0,waiting:!0}}let h=p.data;return a&&(yield*a({jobId:u,flowId:r,nodeId:t,eventType:m.NodeEnd,nodeName:f.name,result:h})),{nodeId:t,result:h,success:!0,waiting:!1}}catch(n){if(v=n instanceof e?n:e.fromCode(`FLOW_NODE_ERROR`,{cause:n}),_<p){_++;let e=g?h*2**(_-1):h;yield*c.logWarning(`Node ${t} (${f.name}) failed, retrying (${_}/${p}) after ${e}ms`),yield*c.sleep(e);continue}return a&&(yield*a({jobId:u,flowId:r,nodeId:t,eventType:m.NodeError,nodeName:f.name,error:v.body,retryCount:_})),yield*v.toEffect()}return v?yield*v.toEffect():yield*e.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Unexpected error in retry loop`)}).toEffect()}),T=({inputs:n,storageId:i,jobId:o,resumeFrom:l,clientId:d})=>c.gen(function*(){!l&&a&&(yield*a({jobId:o,eventType:m.FlowStart,flowId:r}));let h=S(n||{}),g,y,b;if(l)g=l.executionOrder,y=l.nodeResults,b=l.currentIndex;else if(g=_(),y=new Map,b=0,g.length!==p.length)return yield*e.fromCode(`FLOW_CYCLE_ERROR`).toEffect();let x=new Map(p.map(e=>[e.id,e]));if(t.parallelExecution?.enabled??!1){yield*c.logDebug(`Flow ${r}: Executing in parallel mode (maxConcurrency: ${t.parallelExecution?.maxConcurrency??4})`);let e=new v({maxConcurrency:t.parallelExecution?.maxConcurrency??4}),n=e.groupNodesByExecutionLevel(p,s);yield*c.logDebug(`Flow ${r}: Grouped nodes into ${n.length} execution levels`);let u={};p.forEach(e=>{u[e.id]=[]}),s.forEach(e=>{u[e.target]?.push(e.source)});for(let t of n){yield*c.logDebug(`Flow ${r}: Executing level ${t.level} with nodes: ${t.nodes.join(`, `)}`);let n=t.nodes.map(e=>()=>c.gen(function*(){if(l&&e===l.executionOrder[b]&&a){let t=x.get(e);t&&(yield*a({jobId:o,flowId:r,nodeId:e,eventType:m.NodeResume,nodeName:t.name,nodeType:t.type}))}return{nodeId:e,nodeResult:yield*w(e,i,h,y,x,o,d)}})),s=yield*e.executeNodesInParallel(n);for(let{nodeId:e,nodeResult:t}of s){if(t.waiting)return t.result!==void 0&&y.set(e,t.result),{type:`paused`,nodeId:e,executionState:{executionOrder:g,currentIndex:g.indexOf(e),inputs:h}};t.success&&y.set(e,t.result)}}}else{yield*c.logDebug(`Flow ${r}: Executing in sequential mode`);for(let t=b;t<g.length;t++){let n=g[t];if(!n)return yield*e.fromCode(`FLOW_NODE_NOT_FOUND`).toEffect();if(l&&t===b&&a){let e=x.get(n);e&&(yield*a({jobId:o,flowId:r,nodeId:n,eventType:m.NodeResume,nodeName:e.name,nodeType:e.type}))}let s=yield*w(n,i,h,y,x,o,d);if(s.waiting)return s.result!==void 0&&y.set(s.nodeId,s.result),{type:`paused`,nodeId:s.nodeId,executionState:{executionOrder:g,currentIndex:t,inputs:h}};s.success&&y.set(s.nodeId,s.result)}}let T=C(y),E=f.record(f.string(),u).safeParse(T);if(!E.success){let t=`Flow output validation failed: ${E.error.message}. Expected outputs: ${JSON.stringify(Object.keys(C(y)))}. Output nodes: ${p.filter(e=>e.type===`output`).map(e=>e.id).join(`, `)}`;return a&&(yield*a({jobId:o,eventType:m.FlowError,flowId:r,error:t})),yield*e.fromCode(`FLOW_OUTPUT_VALIDATION_ERROR`,{body:t,cause:E.error}).toEffect()}let D=E.data;return a&&(yield*a({jobId:o,eventType:m.FlowEnd,flowId:r,result:D})),{type:`completed`,result:D}});return{id:r,name:i,nodes:p,edges:s,inputSchema:l,outputSchema:u,onEvent:a,checkJobStatus:o,run:({inputs:e,storageId:t,jobId:n,clientId:r})=>T({inputs:e,storageId:t,jobId:n,clientId:r}),resume:({jobId:e,storageId:t,nodeResults:n,executionState:r,clientId:i})=>T({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=p;return h.validateFlow(e,s)},validateInputs:e=>h.validateData(e,l),validateOutputs:e=>h.validateData(e,u)}})}var C=class e extends s.Tag(`FlowWaitUntil`)(){static optional=c.serviceOption(e)},w=class extends s.Tag(`FlowProvider`)(){},T=class extends s.Tag(`FlowServer`)(){};const E=e=>typeof e==`object`&&!!e&&`id`in e;function D(t,n,r){let i=e=>{let i=t=>c.gen(function*(){let n=yield*r.get(e);n&&(yield*r.set(e,{...n,...t,updatedAt:new Date}))});return a=>c.gen(function*(){switch(t.onEvent&&(yield*c.catchAll(t.onEvent(a),e=>(c.logError(`Original onEvent failed`,e),c.succeed({eventId:null})))),yield*n.emit(e,a),c.logInfo(`Updating job ${e} with event ${a.eventType}`),a.eventType){case m.FlowStart:yield*i({status:`running`});break;case m.FlowEnd:break;case m.FlowError:yield*i({status:`failed`,error:a.error});break;case m.NodeStart:yield*c.gen(function*(){let t=yield*r.get(e);if(t){let n=t.tasks.find(e=>e.nodeId===a.nodeId)?t.tasks.map(e=>e.nodeId===a.nodeId?{...e,status:`running`,updatedAt:new Date}:e):[...t.tasks,{nodeId:a.nodeId,status:`running`,createdAt:new Date,updatedAt:new Date}];yield*r.set(e,{...t,tasks:n,updatedAt:new Date})}});break;case m.NodePause:yield*c.gen(function*(){let t=yield*r.get(e);if(t){let n=t.tasks.find(e=>e.nodeId===a.nodeId)?t.tasks.map(e=>e.nodeId===a.nodeId?{...e,status:`paused`,result:a.partialData,updatedAt:new Date}:e):[...t.tasks,{nodeId:a.nodeId,status:`paused`,result:a.partialData,createdAt:new Date,updatedAt:new Date}];yield*r.set(e,{...t,tasks:n,updatedAt:new Date})}});break;case m.NodeResume:yield*c.gen(function*(){let t=yield*r.get(e);if(t){let n=t.tasks.map(e=>e.nodeId===a.nodeId?{...e,status:`running`,updatedAt:new Date}:e);yield*r.set(e,{...t,tasks:n,updatedAt:new Date})}});break;case m.NodeEnd:yield*c.gen(function*(){let n=yield*r.get(e);if(n){let i=n.tasks.map(e=>e.nodeId===a.nodeId?{...e,status:`completed`,result:a.result,updatedAt:new Date}:e),o=t.nodes.find(e=>e.id===a.nodeId)?.type===`output`,s=a.result,c=n.intermediateFiles||[];o&&E(s)&&s.id?c=c.filter(e=>e!==s.id):!o&&E(s)&&s.id&&(c.includes(s.id)||c.push(s.id)),yield*r.set(e,{...n,tasks:i,intermediateFiles:c,updatedAt:new Date})}});break;case m.NodeError:yield*c.gen(function*(){let t=yield*r.get(e);if(t){let n=t.tasks.map(e=>e.nodeId===a.nodeId?{...e,status:`failed`,error:a.error,retryCount:a.retryCount,updatedAt:new Date}:e);yield*r.set(e,{...t,tasks:n,error:a.error,updatedAt:new Date})}});break}return{eventId:e}})},a=t=>t=>c.gen(function*(){let n=yield*r.get(t);return n?n.status===`paused`?`paused`:n.status===`cancelled`?`cancelled`:`running`:yield*c.fail(e.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${t} not found`}))});return{...t,run:e=>c.gen(function*(){let n=e.jobId||crypto.randomUUID(),r=i(n),o=a(n);return yield*(yield*S({flowId:t.id,name:t.name,nodes:t.nodes,edges:t.edges,inputSchema:t.inputSchema,outputSchema:t.outputSchema,onEvent:r,checkJobStatus:o})).run({...e,jobId:n,clientId:e.clientId})}),resume:e=>c.gen(function*(){let n=e.jobId,r=i(n),o=a(n);return yield*(yield*S({flowId:t.id,name:t.name,nodes:t.nodes,edges:t.edges,inputSchema:t.inputSchema,outputSchema:t.outputSchema,onEvent:r,checkJobStatus:o})).resume(e)})}}function O(){return c.gen(function*(){let r=yield*w,i=yield*n,o=yield*t,s=yield*a,l=(t,n)=>c.gen(function*(){let r=yield*o.get(t);return r?yield*o.set(t,{...r,...n}):yield*c.fail(e.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${t} not found`}))}),f=(e,t)=>c.gen(function*(){let n=yield*o.get(e);!n||!n.intermediateFiles||n.intermediateFiles.length===0||(yield*c.logInfo(`Cleaning up ${n.intermediateFiles.length} intermediate files for job ${e}`),yield*c.all(n.intermediateFiles.map(e=>c.gen(function*(){yield*s.delete(e,t),yield*c.logDebug(`Deleted intermediate file ${e}`)}).pipe(c.catchAll(t=>c.gen(function*(){return yield*c.logWarning(`Failed to delete intermediate file ${e}: ${t}`),c.succeed(void 0)})))),{concurrency:5}),yield*l(e,{intermediateFiles:[]}))}),p=({jobId:t,flow:n,storageId:r,clientId:a,inputs:s})=>c.gen(function*(){console.log(`[FlowServer] executeFlowInBackground started for job: ${t}`),yield*l(t,{status:`running`}),console.log(`[FlowServer] Creating flowWithEvents for job: ${t}`);let e=D(n,i,o);console.log(`[FlowServer] Running flow for job: ${t}`);let c=yield*e.run({inputs:s,storageId:r,jobId:t,clientId:a});return console.log(`[FlowServer] Flow completed for job: ${t}, result type: ${c.type}`),c.type===`paused`?yield*l(t,{status:`paused`,pausedAt:c.nodeId,executionState:c.executionState,updatedAt:new Date}):(yield*l(t,{status:`completed`,result:c.result,updatedAt:new Date,endedAt:new Date}),yield*f(t,a)),c}).pipe(c.catchAll(n=>c.gen(function*(){yield*c.logError(`Flow execution failed`,n);let r=n instanceof e?n.body:String(n);yield*c.logInfo(`Updating job ${t} to failed status with error: ${r}`),yield*l(t,{status:`failed`,error:r,updatedAt:new Date}).pipe(c.catchAll(e=>c.gen(function*(){return yield*c.logError(`Failed to update job ${t}`,e),c.succeed(void 0)})));let s=yield*o.get(t);throw s&&(yield*i.emit(t,{jobId:t,eventType:m.FlowError,flowId:s.flowId,error:r}).pipe(c.catchAll(e=>c.gen(function*(){return yield*c.logError(`Failed to emit FlowError event for job ${t}`,e),c.succeed(void 0)})))),yield*f(t,a).pipe(c.catchAll(e=>c.gen(function*(){return yield*c.logWarning(`Failed to cleanup intermediate files for job ${t}`,e),c.succeed(void 0)}))),n})));return{getFlow:(e,t)=>c.gen(function*(){return yield*r.getFlow(e,t)}),getFlowData:(e,t)=>c.gen(function*(){return x(yield*r.getFlow(e,t))}),runFlow:({flowId:t,storageId:n,clientId:i,inputs:a})=>c.gen(function*(){let s=yield*C.optional,l=yield*c.try({try:()=>$.parse({inputs:a}),catch:t=>e.fromCode(`FLOW_INPUT_VALIDATION_ERROR`,{cause:t})}),f=crypto.randomUUID(),m=new Date,h={id:f,flowId:t,storageId:n,clientId:i,status:`started`,createdAt:m,updatedAt:m,tasks:[]};yield*o.set(f,h);let g=yield*r.getFlow(t,i);console.log(`[FlowServer] About to fork flow execution for job: ${f}`);let _=p({jobId:f,flow:g,storageId:n,clientId:i,inputs:l.inputs}).pipe(c.tapErrorCause(e=>c.logError(`Flow execution failed`,e)));if(u.isSome(s)){console.log(`[FlowServer] Using waitUntil for job: ${f}`);let e=yield*c.runtime(),t=d.runPromise(e)(_);s.value(t)}else console.log(`[FlowServer] Using Effect.forkDaemon for job: ${f}`),yield*c.forkDaemon(_);return console.log(`[FlowServer] Flow execution started for job: ${f}`),h}),getJobStatus:t=>c.gen(function*(){return(yield*o.get(t))||(yield*c.fail(e.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${t} not found`})))}),resumeFlow:({jobId:t,nodeId:n,newData:a,clientId:s})=>c.gen(function*(){let p=yield*C.optional,h=yield*o.get(t);if(!h)return console.error(`Job not found`),yield*c.fail(e.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${t} not found`}));if(h.status!==`paused`)return console.error(`Job is not paused`),yield*c.fail(e.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${t} is not paused (status: ${h.status})`}));if(h.pausedAt!==n)return console.error(`Job is not paused at the expected node`),yield*c.fail(e.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${t} is paused at node ${h.pausedAt}, not ${n}`}));if(!h.executionState)return console.error(`Job has no execution state`),yield*c.fail(e.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${t} has no execution state`}));let g={...h.tasks.reduce((e,t)=>(t.result!==void 0&&(e[t.nodeId]=t.result),e),{}),[n]:a},_={...h.executionState.inputs,[n]:a};yield*l(t,{status:`running`});let v=yield*r.getFlow(h.flowId,h.clientId),y=c.gen(function*(){let n=D(v,i,o);if(!h.executionState)return yield*c.fail(e.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${t} has no execution state`}));let r=yield*n.resume({jobId:t,storageId:h.storageId,nodeResults:g,executionState:{...h.executionState,inputs:_},clientId:h.clientId});return r.type===`paused`?yield*l(t,{status:`paused`,pausedAt:r.nodeId,executionState:r.executionState,updatedAt:new Date}):(yield*l(t,{status:`completed`,pausedAt:void 0,executionState:void 0,result:r.result,updatedAt:new Date,endedAt:new Date}),yield*f(t,s)),r}).pipe(c.catchAll(n=>c.gen(function*(){yield*c.logError(`Flow resume failed`,n);let r=n instanceof e?n.body:String(n);yield*c.logInfo(`Updating job ${t} to failed status with error: ${r}`),yield*l(t,{status:`failed`,error:r,updatedAt:new Date}).pipe(c.catchAll(e=>c.gen(function*(){return yield*c.logError(`Failed to update job ${t}`,e),c.succeed(void 0)})));let a=yield*o.get(t);throw a&&(yield*i.emit(t,{jobId:t,eventType:m.FlowError,flowId:a.flowId,error:r}).pipe(c.catchAll(e=>c.gen(function*(){return yield*c.logError(`Failed to emit FlowError event for job ${t}`,e),c.succeed(void 0)})))),yield*f(t,s).pipe(c.catchAll(e=>c.gen(function*(){return yield*c.logWarning(`Failed to cleanup intermediate files for job ${t}`,e),c.succeed(void 0)}))),n}))).pipe(c.tapErrorCause(e=>c.logError(`Flow resume failed`,e)));if(u.isSome(p)){console.log(`[FlowServer] Using waitUntil for resume job: ${t}`);let e=yield*c.runtime(),n=d.runPromise(e)(y);p.value(n)}else console.log(`[FlowServer] Using Effect.forkDaemon for resume job: ${t}`),yield*c.forkDaemon(y);return(yield*o.get(t))||(yield*c.fail(e.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${t} not found after update`})))}),pauseFlow:(t,n)=>c.gen(function*(){let r=yield*o.get(t);if(!r)return yield*c.fail(e.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${t} not found`}));if(n!==null&&r.clientId!==n)return yield*c.fail(e.fromCode(`FLOW_NOT_AUTHORIZED`,{cause:`Client ${n} is not authorized to pause job ${t}`}));if(r.status!==`running`)return yield*c.fail(e.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${t} cannot be paused (current status: ${r.status})`}));let a=r.tasks.find(e=>e.status===`running`)?.nodeId;return yield*l(t,{status:`paused`,pausedAt:a,updatedAt:new Date}),yield*i.emit(t,{jobId:t,flowId:r.flowId,eventType:m.FlowPause,pausedAt:a}),(yield*o.get(t))||(yield*c.fail(e.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${t} not found after pause`})))}),cancelFlow:(t,n)=>c.gen(function*(){let r=yield*o.get(t);return r?n!==null&&r.clientId!==n?yield*c.fail(e.fromCode(`FLOW_NOT_AUTHORIZED`,{cause:`Client ${n} is not authorized to cancel job ${t}`})):r.status!==`running`&&r.status!==`paused`&&r.status!==`started`?yield*c.fail(e.fromCode(`FLOW_JOB_ERROR`,{cause:`Job ${t} cannot be cancelled (current status: ${r.status})`})):(yield*l(t,{status:`cancelled`,updatedAt:new Date,endedAt:new Date}),yield*i.emit(t,{jobId:t,flowId:r.flowId,eventType:m.FlowCancel}),yield*f(t,n),(yield*o.get(t))||(yield*c.fail(e.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${t} not found after cancellation`})))):yield*c.fail(e.fromCode(`FLOW_JOB_NOT_FOUND`,{cause:`Job ${t} not found`}))}),subscribeToFlowEvents:(e,t)=>c.gen(function*(){yield*i.subscribe(e,t)}),unsubscribeFromFlowEvents:e=>c.gen(function*(){yield*i.unsubscribe(e)})}})}const k=l.effect(T,O()),A=e=>({type:`complete`,data:e}),j=e=>({type:`waiting`,partialData:e});function M(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 N=f.object({operation:f.literal(`init`),storageId:f.string(),metadata:f.record(f.string(),f.any()).optional()}),P=f.object({operation:f.literal(`finalize`),uploadId:f.string()}),F=f.object({operation:f.literal(`url`),url:f.string(),storageId:f.string().optional(),metadata:f.record(f.string(),f.any()).optional()}),I=f.union([N,P,F]),L=f.object({allowedMimeTypes:f.array(f.string()).optional(),minSize:f.number().positive().optional(),maxSize:f.number().positive().optional()});function R(t,n){return c.gen(function*(){if(n){if(n.allowedMimeTypes&&n.allowedMimeTypes.length>0&&!n.allowedMimeTypes.some(e=>{if(e.endsWith(`/*`)){let n=e.slice(0,-2);return t.type.startsWith(n)}return t.type===e}))throw yield*e.fromCode(`VALIDATION_ERROR`,{cause:Error(`File type "${t.type}" is not allowed. Allowed types: ${n.allowedMimeTypes.join(`, `)}`)}).toEffect();if(n.minSize!==void 0&&t.size<n.minSize)throw yield*e.fromCode(`VALIDATION_ERROR`,{cause:Error(`File size (${t.size} bytes) is below minimum (${n.minSize} bytes)`)}).toEffect();if(n.maxSize!==void 0&&t.size>n.maxSize)throw yield*e.fromCode(`VALIDATION_ERROR`,{cause:Error(`File size (${t.size} bytes) exceeds maximum (${n.maxSize} bytes)`)}).toEffect()}})}function z(t,n){return c.gen(function*(){let s=yield*a;return yield*g({id:t,name:`Input`,description:`Handles file input through multiple methods - streaming upload (init/finalize) or direct URL fetch`,type:h.input,inputSchema:I,outputSchema:r,run:({data:r,flowId:a,jobId:l,clientId:u})=>c.gen(function*(){switch(r.operation){case`init`:{let e={storageId:r.storageId,size:r.metadata?.size||0,type:r.metadata?.mimeType||`application/octet-stream`,fileName:r.metadata?.originalName,lastModified:r.metadata?.size?Date.now():void 0,metadata:r.metadata?JSON.stringify(r.metadata):void 0,flow:{flowId:a,nodeId:t,jobId:l}};return j(yield*s.createUpload(e,u))}case`finalize`:{let e=yield*s.getUpload(r.uploadId),{type:t}=M(e.metadata);return yield*R({type:t,size:e.size||0},n),A(e)}case`url`:{let e=yield*o(r.url),c=yield*i(e),d=r.metadata?.mimeType||e.headers.get(`content-type`)||`application/octet-stream`,f=r.metadata?.size||Number(e.headers.get(`content-length`)||0),p=r.metadata?.originalName||r.url.split(`/`).pop()||`file`;yield*R({type:d,size:f},n);let m=new ReadableStream({start(e){e.enqueue(new Uint8Array(c)),e.close()}}),h={storageId:r.storageId||`buffer`,size:f,type:d,fileName:p,lastModified:Date.now(),metadata:r.metadata?JSON.stringify(r.metadata):void 0};return A({...yield*s.upload(h,u,m),flow:{flowId:a,nodeId:t,jobId:l}})}default:throw yield*e.fromCode(`VALIDATION_ERROR`,{cause:Error(`Invalid operation`)}).toEffect()}})})})}const B=f.object({});function V(t,n=e=>c.succeed(e)){return c.gen(function*(){let i=yield*a;return yield*g({id:t,name:`Storage`,description:`Stores a file in the storage`,type:h.output,inputSchema:r,outputSchema:r,run:({data:r,storageId:a,flowId:o,jobId:s,clientId:l})=>c.gen(function*(){let{type:u,fileName:d,metadata:f,metadataJson:p}=M(r.metadata),m={flowId:o,nodeId:t,jobId:s},h=f?{...r,metadata:f}:r,g=yield*i.getUpload(r.id);if(!g.id)return yield*c.fail(e.fromCode(`FILE_READ_ERROR`,Error(`Upload Key is undefined`)));if(g.storage.id===a)return A(yield*n({...h,flow:m}));let _=yield*i.read(r.id,l),v=new ReadableStream({start(e){e.enqueue(_),e.close()}}),y=yield*i.upload({storageId:a,size:_.byteLength,type:u,fileName:d,lastModified:0,metadata:p,flow:m},l,v),b=M(y.metadata);return A(yield*n(b.metadata?{...y,metadata:b.metadata}:y))})})})}function H({id:e,name:t,description:n,transform:i}){return c.gen(function*(){let o=yield*a;return yield*g({id:e,name:t,description:n,type:h.process,inputSchema:r,outputSchema:r,run:({data:t,storageId:n,flowId:r,jobId:a,clientId:s})=>c.gen(function*(){let c={flowId:r,nodeId:e,jobId:a},l=yield*i(yield*o.read(t.id,s),t),u=l instanceof Uint8Array?l:l.bytes,d=l instanceof Uint8Array?void 0:l.type,f=l instanceof Uint8Array?void 0:l.fileName,p=new ReadableStream({start(e){e.enqueue(u),e.close()}}),{type:m,fileName:h,metadata:g,metadataJson:_}=M(t.metadata),v=yield*o.upload({storageId:n,size:u.byteLength,type:d??m,fileName:f??h,lastModified:0,metadata:_,flow:c},s,p);return A(g?{...v,metadata:g}:v)})})})}var U=class extends s.Tag(`CredentialProvider`)(){},W=class extends s.Tag(`ImageAiPlugin`)(){},G=class extends s.Tag(`ImagePlugin`)(){};const K=f.object({serviceType:f.enum([`replicate`]).optional()}),q=f.object({quality:f.number().min(0).max(100),format:f.enum([`jpeg`,`webp`,`png`,`avif`])}),J=f.object({serviceType:f.enum([`replicate`]).optional()}),Y=f.object({width:f.number().positive().optional(),height:f.number().positive().optional(),fit:f.enum([`contain`,`cover`,`fill`])}).refine(e=>e.width||e.height,`Either width or height must be specified for resize`);var X=class extends s.Tag(`ZipPlugin`)(){};const Z=(e,t)=>{if(e.length===0)return t;let[n,...r]=e;return r.reduce((e,t)=>f.union([e,t]),n)};function Q(t){return c.gen(function*(){let n=Object.entries(t.nodes),r=e=>c.isEffect(e)?e:c.succeed(e),i=yield*c.forEach(n,([t,n])=>c.flatMap(r(n),n=>n.id===t?c.succeed([t,n]):c.fail(e.fromCode(`FLOW_NODE_ERROR`,{cause:Error(`Node key ${t} does not match node id ${n.id}`)})))),a=Object.fromEntries(i),o=i.map(([,e])=>e),s=i.filter(([,e])=>e.type===h.input).map(([,e])=>e.inputSchema),l=i.filter(([,e])=>e.type===h.output).map(([,e])=>e.outputSchema),u=t.inputSchema??Z(s,f.unknown()),d=t.outputSchema??Z(l,f.unknown()),p=t.edges.map(e=>({source:a[e.source]?.id??e.source,target:a[e.target]?.id??e.target,sourcePort:e.sourcePort,targetPort:e.targetPort}));return yield*S({flowId:t.flowId,name:t.name,nodes:o,edges:p,inputSchema:u,outputSchema:d,typeChecker:t.typeChecker,onEvent:t.onEvent,parallelExecution:t.parallelExecution})})}const $=f.object({inputs:f.record(f.string(),f.any())});export{_ as A,O as C,v as D,x as E,p as M,h as O,C as S,S as T,M as _,J as a,w as b,G as c,H as d,V as f,L as g,I as h,Y as i,m as j,g as k,W as l,z as m,Q as n,q as o,B as p,X as r,K as s,$ as t,U as u,A as v,k as w,T as x,j as y};
|
|
2
|
+
//# sourceMappingURL=flow-DEohelFR.mjs.map
|