@lunora/workflow 1.0.0-alpha.71 → 1.0.0-alpha.73
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/README.md +1 -1
- package/dist/do/index.d.mts +1 -1
- package/dist/do/index.d.ts +1 -1
- package/dist/do/index.mjs +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{createRunStep-DhQvb-FU.mjs → createRunStep-Dbtj78J5.mjs} +1 -1
- package/dist/packem_shared/{createWorkflowContext-CiNtEzpn.mjs → createWorkflowContext-DBUnSy0_.mjs} +1 -1
- package/dist/packem_shared/{createWorkflowRunContext-CMweH87g.mjs → createWorkflowRunContext-C007IGZ9.mjs} +1 -1
- package/dist/packem_shared/createWorkflows-BwR_J9mp.mjs +1 -0
- package/dist/packem_shared/run-step-DJ3bnM1Q.mjs +1 -0
- package/dist/packem_shared/{types.d-5O82Xdxt.d.mts → types.d-DUrUHeVi.d.mts} +32 -4
- package/dist/packem_shared/{types.d-5O82Xdxt.d.ts → types.d-DUrUHeVi.d.ts} +32 -4
- package/package.json +3 -3
- package/dist/packem_shared/createWorkflows-BTny3jXV.mjs +0 -1
- package/dist/packem_shared/run-step-CMkT6BI4.mjs +0 -1
package/README.md
CHANGED
|
@@ -192,7 +192,7 @@ export const checkout = mutation.input({ orderId: v.string() }).mutation(async (
|
|
|
192
192
|
});
|
|
193
193
|
```
|
|
194
194
|
|
|
195
|
-
A handle exposes `create({ id?, params?, retention? })`, `createBatch(
|
|
195
|
+
A handle exposes `create({ id?, params?, retention? })`, `createBatch({ instances })` or `createBatch({ count, params?, retention? })` (returns `{ created, errors }`, one error per instance it did not create), `deleteBatch([...ids])` (up to 100), `get(id)`, and `sendEvent(instanceId, event, payload)` — the typed delivery of a declared event (see above). `create`/`get` return the native Cloudflare instance, which exposes its own lifecycle: `status()`, `pause()`, `resume()`, `restart()`, `terminate()`, `delete()`, `subscribe({ cursor?, filter? })` (streams the instance's event history, then new events), and the untyped `sendEvent({ type, payload })`.
|
|
196
196
|
|
|
197
197
|
`defineWorkflow` also takes deploy settings, which codegen writes into the workflow's `wrangler.jsonc` entry: `schedules` (cron expressions that each start an instance), `limits: { steps }`, and `defaultRetention: { successRetention, errorRetention }`. Scheduled workflows are refused on the Node and celld targets.
|
|
198
198
|
|
package/dist/do/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from 'cloudflare:workers';
|
|
2
|
-
import { W as WorkflowDefinition } from "../packem_shared/types.d-
|
|
2
|
+
import { W as WorkflowDefinition } from "../packem_shared/types.d-DUrUHeVi.mjs";
|
|
3
3
|
import '@lunora/values';
|
|
4
4
|
/**
|
|
5
5
|
* Base class for the generated `WorkflowEntrypoint` classes. Applies a
|
package/dist/do/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from 'cloudflare:workers';
|
|
2
|
-
import { W as WorkflowDefinition } from "../packem_shared/types.d-
|
|
2
|
+
import { W as WorkflowDefinition } from "../packem_shared/types.d-DUrUHeVi.js";
|
|
3
3
|
import '@lunora/values';
|
|
4
4
|
/**
|
|
5
5
|
* Base class for the generated `WorkflowEntrypoint` classes. Applies a
|
package/dist/do/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{WorkflowEntrypoint as l}from"cloudflare:workers";import{NonRetryableError as i}from"cloudflare:workflows";import{convertNonRetryableError as h}from"../packem_shared/NonRetryableError-BPu01mU8.mjs";import{extractBranchMarker as m,stripBranchMarker as x,signalBranchParentSafe as p,errorOutcome as f,okOutcome as u}from"../packem_shared/MAX_BRANCHES-Bcw3dss9.mjs";import{createWorkflowRunContext as y}from"../packem_shared/createWorkflowRunContext-
|
|
1
|
+
import{WorkflowEntrypoint as l}from"cloudflare:workers";import{NonRetryableError as i}from"cloudflare:workflows";import{convertNonRetryableError as h}from"../packem_shared/NonRetryableError-BPu01mU8.mjs";import{extractBranchMarker as m,stripBranchMarker as x,signalBranchParentSafe as p,errorOutcome as f,okOutcome as u}from"../packem_shared/MAX_BRANCHES-Bcw3dss9.mjs";import{createWorkflowRunContext as y}from"../packem_shared/createWorkflowRunContext-C007IGZ9.mjs";class N extends l{#r;#t;constructor(t,e,o,r){super(t,e),this.#t=o,this.#r=r??"workflow"}async run(t,e){const o=e,r=m(t.payload),c=r?{...t,payload:x(t.payload)}:t,a=y({env:this.env,exports:this.ctx.exports,event:c,exportName:this.#r,nonRetryableErrorClass:i,step:o});let n;try{n=await this.#t.handler(a)}catch(s){return r&&await p({env:this.env,exports:this.ctx.exports,log:a.log,step:o},r,f(s)),h(s,i)}return r&&await p({env:this.env,exports:this.ctx.exports,log:a.log,step:o},r,u(n)),n}}export{N as default};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as Workflows, L as LunoraWorkflowsOptions, b as WorkflowEventDefinition, S as StepArgsValidator, c as StepConfig, d as StepDefinition, e as WorkflowConfig, W as WorkflowDefinition, f as WorkflowBranch, g as WorkflowInstanceStatus, h as WorkflowEventLike, i as WorkflowStepLike, j as WorkflowRunContext, k as WorkflowLogger, l as WorkflowRunFunction, m as WorkflowRunStepFunction, n as WorkflowWaitForEventFunction } from "./packem_shared/types.d-
|
|
2
|
-
export type { A as ArgsOf, B as BranchCompensationParams, F as FunctionKind, o as FunctionReference, I as InferStepArgs, R as RunFunctionOptions, p as RunStepOptions, q as StepHandler, r as StepRollbackContext, s as StepRollbackHandler, t as StepRunContext, u as WaitForEventOptions, v as WorkflowBatchDeleteResult, w as WorkflowBindingLike, x as WorkflowBranchOutputs, y as
|
|
1
|
+
import { a as Workflows, L as LunoraWorkflowsOptions, b as WorkflowEventDefinition, S as StepArgsValidator, c as StepConfig, d as StepDefinition, e as WorkflowConfig, W as WorkflowDefinition, f as WorkflowBranch, g as WorkflowInstanceStatus, h as WorkflowEventLike, i as WorkflowStepLike, j as WorkflowRunContext, k as WorkflowLogger, l as WorkflowRunFunction, m as WorkflowRunStepFunction, n as WorkflowWaitForEventFunction } from "./packem_shared/types.d-DUrUHeVi.mjs";
|
|
2
|
+
export type { A as ArgsOf, B as BranchCompensationParams, F as FunctionKind, o as FunctionReference, I as InferStepArgs, R as RunFunctionOptions, p as RunStepOptions, q as StepHandler, r as StepRollbackContext, s as StepRollbackHandler, t as StepRunContext, u as WaitForEventOptions, v as WorkflowBatchDeleteResult, w as WorkflowBindingLike, x as WorkflowBranchOutputs, y as WorkflowCreateBatchError, z as WorkflowCreateBatchOptions, C as WorkflowCreateBatchResult, D as WorkflowCreateOptions, E as WorkflowDelayFunctionLike, G as WorkflowHandle, H as WorkflowHandler, J as WorkflowInstanceEventLike, K as WorkflowInstanceLike, M as WorkflowInstanceSubscribeOptionsLike, N as WorkflowInstanceSubscriptionLike, O as WorkflowParallelFunction, P as WorkflowRetention, Q as WorkflowRollbackContextLike, T as WorkflowRollbackHandlerLike, U as WorkflowSpawnFunction, V as WorkflowSpawnOptions, X as WorkflowStatusResult, Y as WorkflowStepConfigLike, Z as WorkflowStepContextLike, _ as WorkflowStepRollbackOptionsLike } from "./packem_shared/types.d-DUrUHeVi.mjs";
|
|
3
3
|
import { Validator } from '@lunora/values';
|
|
4
4
|
import { LunoraError } from '@lunora/errors';
|
|
5
5
|
/** Wiring info for one declared workflow, emitted by codegen into the generated shard. */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as Workflows, L as LunoraWorkflowsOptions, b as WorkflowEventDefinition, S as StepArgsValidator, c as StepConfig, d as StepDefinition, e as WorkflowConfig, W as WorkflowDefinition, f as WorkflowBranch, g as WorkflowInstanceStatus, h as WorkflowEventLike, i as WorkflowStepLike, j as WorkflowRunContext, k as WorkflowLogger, l as WorkflowRunFunction, m as WorkflowRunStepFunction, n as WorkflowWaitForEventFunction } from "./packem_shared/types.d-
|
|
2
|
-
export type { A as ArgsOf, B as BranchCompensationParams, F as FunctionKind, o as FunctionReference, I as InferStepArgs, R as RunFunctionOptions, p as RunStepOptions, q as StepHandler, r as StepRollbackContext, s as StepRollbackHandler, t as StepRunContext, u as WaitForEventOptions, v as WorkflowBatchDeleteResult, w as WorkflowBindingLike, x as WorkflowBranchOutputs, y as
|
|
1
|
+
import { a as Workflows, L as LunoraWorkflowsOptions, b as WorkflowEventDefinition, S as StepArgsValidator, c as StepConfig, d as StepDefinition, e as WorkflowConfig, W as WorkflowDefinition, f as WorkflowBranch, g as WorkflowInstanceStatus, h as WorkflowEventLike, i as WorkflowStepLike, j as WorkflowRunContext, k as WorkflowLogger, l as WorkflowRunFunction, m as WorkflowRunStepFunction, n as WorkflowWaitForEventFunction } from "./packem_shared/types.d-DUrUHeVi.js";
|
|
2
|
+
export type { A as ArgsOf, B as BranchCompensationParams, F as FunctionKind, o as FunctionReference, I as InferStepArgs, R as RunFunctionOptions, p as RunStepOptions, q as StepHandler, r as StepRollbackContext, s as StepRollbackHandler, t as StepRunContext, u as WaitForEventOptions, v as WorkflowBatchDeleteResult, w as WorkflowBindingLike, x as WorkflowBranchOutputs, y as WorkflowCreateBatchError, z as WorkflowCreateBatchOptions, C as WorkflowCreateBatchResult, D as WorkflowCreateOptions, E as WorkflowDelayFunctionLike, G as WorkflowHandle, H as WorkflowHandler, J as WorkflowInstanceEventLike, K as WorkflowInstanceLike, M as WorkflowInstanceSubscribeOptionsLike, N as WorkflowInstanceSubscriptionLike, O as WorkflowParallelFunction, P as WorkflowRetention, Q as WorkflowRollbackContextLike, T as WorkflowRollbackHandlerLike, U as WorkflowSpawnFunction, V as WorkflowSpawnOptions, X as WorkflowStatusResult, Y as WorkflowStepConfigLike, Z as WorkflowStepContextLike, _ as WorkflowStepRollbackOptionsLike } from "./packem_shared/types.d-DUrUHeVi.js";
|
|
3
3
|
import { Validator } from '@lunora/values';
|
|
4
4
|
import { LunoraError } from '@lunora/errors';
|
|
5
5
|
/** Wiring info for one declared workflow, emitted by codegen into the generated shard. */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createWorkflowContext as e}from"./packem_shared/createWorkflowContext-
|
|
1
|
+
import{createWorkflowContext as e}from"./packem_shared/createWorkflowContext-DBUnSy0_.mjs";import{default as f}from"./packem_shared/createWorkflows-BwR_J9mp.mjs";import{defineWorkflowEvent as n,isWorkflowEventDefinition as i}from"./packem_shared/defineWorkflowEvent-suERPEEV.mjs";import{defineStep as p,isStepDefinition as s}from"./packem_shared/defineStep-D1-9eOnA.mjs";import{defineWorkflow as x,isWorkflowDefinition as w,workflowClassName as c,workflowDefaultName as k}from"./packem_shared/defineWorkflow-DynRL6LP.mjs";import{NonRetryableError as W,convertNonRetryableError as R,isNonRetryableError as N,toNativeNonRetryableError as v}from"./packem_shared/NonRetryableError-BPu01mU8.mjs";import{MAX_BRANCHES as d,branch as u}from"./packem_shared/MAX_BRANCHES-Bcw3dss9.mjs";import{WorkflowsRestError as D,createWorkflowsRestClient as S}from"./packem_shared/WorkflowsRestError-CxLJskBZ.mjs";import{createWorkflowRunContext as A}from"./packem_shared/createWorkflowRunContext-C007IGZ9.mjs";import{c as h,v as B}from"./packem_shared/run-step-DJ3bnM1Q.mjs";import{createWaitForEvent as H}from"./packem_shared/createWaitForEvent-D5Ohn2Pz.mjs";import{isDuplicateInstanceError as M}from"./packem_shared/isDuplicateInstanceError-CecnqNAa.mjs";export{d as MAX_BRANCHES,W as NonRetryableError,D as WorkflowsRestError,u as branch,R as convertNonRetryableError,h as createRunStep,H as createWaitForEvent,e as createWorkflowContext,A as createWorkflowRunContext,f as createWorkflows,S as createWorkflowsRestClient,p as defineStep,x as defineWorkflow,n as defineWorkflowEvent,M as isDuplicateInstanceError,N as isNonRetryableError,s as isStepDefinition,w as isWorkflowDefinition,i as isWorkflowEventDefinition,v as toNativeNonRetryableError,B as validateStepArgs,c as workflowClassName,k as workflowDefaultName};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as p,v as o}from"./run-step-
|
|
1
|
+
import{c as p,v as o}from"./run-step-DJ3bnM1Q.mjs";import"./defineWorkflowEvent-suERPEEV.mjs";import"./NonRetryableError-BPu01mU8.mjs";export{p as createRunStep,o as validateStepArgs};
|
package/dist/packem_shared/{createWorkflowContext-CiNtEzpn.mjs → createWorkflowContext-DBUnSy0_.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as s}from"./workflow-binding-Dm9hBzx_.mjs";import a from"./createWorkflows-
|
|
1
|
+
import{r as s}from"./workflow-binding-Dm9hBzx_.mjs";import a from"./createWorkflows-BwR_J9mp.mjs";const l=(t,c,n)=>{const o={};for(const e of c){const r=s(t,n,e.className,["create","createBatch","get"]);r!==void 0&&(o[e.exportName]=r)}return a({bindings:o})};export{l as createWorkflowContext};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as I,d as R,c as x,p as k,w as N}from"./run-step-
|
|
1
|
+
import{l as I,d as R,c as x,p as k,w as N}from"./run-step-DJ3bnM1Q.mjs";import{LunoraError as C}from"@lunora/errors";import{r as T}from"./workflow-binding-Dm9hBzx_.mjs";import{workflowClassName as y}from"./defineWorkflow-DynRL6LP.mjs";import{raiseNonRetryable as v}from"./NonRetryableError-BPu01mU8.mjs";import{createSpawn as O,createParallel as $}from"./MAX_BRANCHES-Bcw3dss9.mjs";import{createWaitForEvent as S}from"./createWaitForEvent-D5Ohn2Pz.mjs";const _=r=>({debug:(t,...n)=>{console.debug(r,t,...n)},error:(t,...n)=>{console.error(r,t,...n)},info:(t,...n)=>{console.info(r,t,...n)},warn:(t,...n)=>{console.warn(r,t,...n)}}),j=r=>{let t="";for(let a=0;a<r.length;a+=32768)t+=String.fromCharCode(...r.subarray(a,a+32768));return btoa(t)},P=r=>{const t=atob(r),n=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)n[a]=t.codePointAt(a)??0;return n},U="$lunora.wire$",b=64,p=1024,g="__proto__",E={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},h={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},s=(r,t=0)=>{if(t>b)throw new RangeError(`wire-codec: value nesting exceeds the ${b}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===U)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(e=>s(e,t+1));case"bigint":{const e=r[2];if(typeof e!="string"||e.length>p||!/^-?\d+$/.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${p} digits)`);return BigInt(e)}case"date":{const e=s(r[2],t+1);if(typeof e!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(e)}case"map":{const e=r[2];return new Map(e.map(o=>{if(!Array.isArray(o)||o.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[s(o[0],t+1),s(o[1],t+1)]}))}case"set":return new Set(r[2].map(e=>s(e,t+1)));case"url":{const e=r[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(e)}case"error":{const e=r[2],o=r[3];if(typeof e!="string"||typeof o!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const m=(Object.hasOwn(h,e)?h[e]:void 0)??Error,c=new m(o);c.name!==e&&Object.defineProperty(c,"name",{configurable:!0,value:e,writable:!0});const f=s(r[4],t+1);if(f===null||typeof f!="object"||Array.isArray(f))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(f))d===g?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:f[d],writable:!0}):c[d]=f[d];return r.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:s(r[5],t+1),writable:!0}),c}case"bytes":{const e=r[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const o=P(e);if(j(o)!==e)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const m=r[3]??"Uint8Array";if(m==="ArrayBuffer")return o.buffer.byteLength===o.byteLength?o.buffer:o.slice().buffer;const c=Object.hasOwn(E,m)?E[m]:void 0;return c?new c(o.slice().buffer):o}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(e=>s(e,t+1))}return r.map(i=>s(i,t+1))}const n=r,a={};for(const i of Object.keys(n)){const e=s(n[i],t+1);i===g?Object.defineProperty(a,i,{configurable:!0,enumerable:!0,value:e,writable:!0}):a[i]=e}return a},H=r=>{const t=_(`[workflow:${r.exportName}]`),n=I({env:r.env,fetchImpl:r.fetchImpl,label:"@lunora/workflow"}),a=N(n),i=R(r.exportName,r.event.instanceId),e=k(a,`${i}#body`),o=l=>{const u=y(l),w=T(r.env,r.exports,u,["create","get"]);if(w===void 0)throw new C("INTERNAL",`@lunora/workflow: cannot spawn child workflow "${l}" — no "${u}" on ctx.exports or env (is it declared in lunora/workflows.ts?)`);return w},m=r.exportName.replaceAll(/\W/gu,"_");let c=0;const f=l=>{if(l!==void 0)return l;const u=`${r.event.instanceId}-${m}-c${String(c)}`;return c+=1,u},d={env:r.env,exports:r.exports,instanceId:r.event.instanceId,log:t,nextChildId:f,parentClassName:y(r.exportName),resolveBinding:o,step:r.step},A=(()=>{try{return s(r.event.payload)}catch(l){return v(`@lunora/workflow: workflow "${r.exportName}" params could not be decoded — ${l instanceof Error?l.message:String(l)}`,l,r.nonRetryableErrorClass)}})();return{env:r.env,exports:r.exports,event:r.event,...r.fetchImpl===void 0?{}:{fetchImpl:r.fetchImpl},log:t,parallel:$(d),params:A,run:e,runStep:x({dedupNamespace:i,env:r.env,log:t,nonRetryableErrorClass:r.nonRetryableErrorClass,run:n,step:r.step}),spawn:O(d),step:r.step,waitForEvent:S({nonRetryableErrorClass:r.nonRetryableErrorClass,step:r.step})}};export{H as createWorkflowRunContext};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as o}from"@lunora/errors";import{h as w,B as l}from"./branch-marker-CCpWfS5k.mjs";import{eventDefinitionProblem as f}from"./defineWorkflowEvent-suERPEEV.mjs";const c=r=>{if(w(r?.params))throw new o("BAD_REQUEST",`@lunora/workflow: params ${l}`)},i=r=>({create:async e=>(c(e),r.create(e)),createBatch:async e=>{const a="instances"in e?e.instances:[{params:e.params}];for(const t of a)c(t);return r.createBatch(e)},deleteBatch:async e=>r.deleteBatch(e),get:async e=>r.get(e),sendEvent:async(e,a,t)=>{const n=f(a);if(n!==void 0)throw new o("BAD_REQUEST",`@lunora/workflow: sendEvent ${n}`);await(await r.get(e)).sendEvent({payload:a.payload.parse(t),type:a.type})}}),E=r=>{const e=r.bindings??{};return{get:a=>{const t=e[a];if(t===void 0){const n=Object.keys(e),s=n.length===0?"no workflows are declared":`known workflows: ${n.join(", ")}`;throw new o("INTERNAL",`@lunora/workflow: no workflow named "${a}" (${s})`)}return i(t)}}};export{E as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as A,isLunoraError as V}from"@lunora/errors";import{parseValidatorMap as W}from"@lunora/values";import{RESERVED_EVENT_TYPE_PREFIX as $}from"./defineWorkflowEvent-suERPEEV.mjs";import{raiseNonRetryable as R,convertNonRetryableError as G}from"./NonRetryableError-BPu01mU8.mjs";const _=9e5,z="DISPATCH_IN_PROGRESS",X="x-lunora-dispatch-declined",Y=(r,t,o)=>{if(t===void 0)return{dispose:()=>{},signal:r};const a=new AbortController,n=setTimeout(()=>{a.abort(o())},t);return{dispose:()=>{clearTimeout(n)},signal:a.signal}},T=r=>{let t="";for(let o=0;o<r.length;o+=32768)t+=String.fromCharCode(...r.subarray(o,o+32768));return btoa(t)},Q=r=>{const t=atob(r),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.codePointAt(a)??0;return o},g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",C=r=>{let t="",o=0;const a=r.length-2;for(;o<a;o+=3){const e=r[o]<<16|r[o+1]<<8|r[o+2];t+=g.charAt(e>>18&63)+g.charAt(e>>12&63)+g.charAt(e>>6&63)+g.charAt(e&63)}const n=r.length-o;if(n===1){const e=r[o]<<16;t+=g.charAt(e>>18&63)+g.charAt(e>>12&63)}else if(n===2){const e=r[o]<<16|r[o+1]<<8;t+=g.charAt(e>>18&63)+g.charAt(e>>12&63)+g.charAt(e>>6&63)}return t};new TextDecoder;const k=new TextEncoder,D="=",Z=r=>{for(let t=0;t<r.length;t+=1)if(r.charCodeAt(t)>255)return!1;return!0},q=r=>C(k.encode(JSON.stringify(r))),rr=r=>!r.startsWith(D)&&Z(r)?r:`${D}${C(k.encode(r))}`,f="$lunora.wire$",S=64,I=1024,O="__proto__",U={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},j={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},tr=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},b=(r,t=0)=>{if(t>S)throw new RangeError(`wire-codec: value nesting exceeds the ${S}-level limit`);if(r===void 0)return[f,"undefined"];if(r===null)return null;const o=typeof r;if(o==="bigint"){const e=r.toString();if(e.length>I)throw new RangeError(`wire-codec: over-long bigint (max ${I} digits)`);return[f,"bigint",e]}if(o==="number"){const e=r;return Number.isNaN(e)?[f,"nan"]:e===1/0?[f,"inf"]:e===-1/0?[f,"-inf"]:e}if(o!=="object")return r;if(r instanceof Date)return[f,"date",b(r.getTime(),t+1)];if(r instanceof Error){const e=r,s=b(Object.fromEntries(Object.keys(e).map(c=>[c,e[c]])),t+1),i=[f,"error",String(e.name),String(e.message),s];return e.cause!==void 0&&i.push(b(e.cause,t+1)),i}if(r instanceof URL)return[f,"url",r.href];if(r instanceof Map)return[f,"map",[...r.entries()].map(([e,s])=>[b(e,t+1),b(s,t+1)])];if(r instanceof Set)return[f,"set",[...r].map(e=>b(e,t+1))];if(r instanceof ArrayBuffer)return[f,"bytes",T(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,s=e.constructor.name,i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return s==="Uint8Array"?[f,"bytes",T(i)]:[f,"bytes",T(i),s]}if(Array.isArray(r)){const e=r.map(s=>b(s,t+1));return e.length>0&&e[0]===f?[f,"arr",e]:e}if(!tr(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=r,n={};for(const e of Object.keys(a)){const s=a[e];if(s===void 0)continue;const i=b(s,t+1);e===O?Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):n[e]=i}return n},p=(r,t=0)=>{if(t>S)throw new RangeError(`wire-codec: value nesting exceeds the ${S}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===f)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(n=>p(n,t+1));case"bigint":{const n=r[2];if(typeof n!="string"||n.length>I||!/^-?\d+$/.test(n))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${I} digits)`);return BigInt(n)}case"date":{const n=p(r[2],t+1);if(typeof n!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(n)}case"map":{const n=r[2];return new Map(n.map(e=>{if(!Array.isArray(e)||e.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[p(e[0],t+1),p(e[1],t+1)]}))}case"set":return new Set(r[2].map(n=>p(n,t+1)));case"url":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(n)}case"error":{const n=r[2],e=r[3];if(typeof n!="string"||typeof e!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(j,n)?j[n]:void 0)??Error,i=new s(e);i.name!==n&&Object.defineProperty(i,"name",{configurable:!0,value:n,writable:!0});const c=p(r[4],t+1);if(c===null||typeof c!="object"||Array.isArray(c))throw new TypeError("wire-codec: malformed error — props must be an object");for(const u of Object.keys(c))u===O?Object.defineProperty(i,u,{configurable:!0,enumerable:!0,value:c[u],writable:!0}):i[u]=c[u];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:p(r[5],t+1),writable:!0}),i}case"bytes":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const e=Q(n);if(T(e)!==n)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=r[3]??"Uint8Array";if(s==="ArrayBuffer")return e.buffer.byteLength===e.byteLength?e.buffer:e.slice().buffer;const i=Object.hasOwn(U,s)?U[s]:void 0;return i?new i(e.slice().buffer):e}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(n=>p(n,t+1))}return r.map(n=>p(n,t+1))}const o=r,a={};for(const n of Object.keys(o)){const e=p(o[n],t+1);n===O?Object.defineProperty(a,n,{configurable:!0,enumerable:!0,value:e,writable:!0}):a[n]=e}return a},er=(r,t,o)=>{try{return b(o)}catch(a){throw new TypeError(`${r}: cannot encode args for '${t}' — ${a instanceof Error?a.message:String(a)}`,a instanceof Error?{cause:a}:void 0)}},nr="/_lunora/scheduler/dispatch",x=3e4,or=r=>{let t=r.length;for(;t>0&&r[t-1]==="/";)t-=1;return r.slice(0,t)},B=Symbol("lunoraDispatchFailure"),F=Symbol("lunoraDispatchDecline"),ar=Symbol("lunoraDispatchMessageId"),H=(r,t)=>(t!==void 0&&Object.defineProperty(r,ar,{value:t}),r),sr=(r,t)=>(Object.defineProperty(r,B,{value:!0}),H(r,t)),ir=(r,t,o,a)=>{const{status:n}=t;try{const e=JSON.parse(o)?.error;if(typeof e=="object"&&e!==null&&typeof e.code=="string"){const{code:s,data:i,message:c}=e,u=sr(new A(s,typeof c=="string"?c:void 0,{data:i,status:n}),a);return t.headers.get(X)==="1"&&Object.defineProperty(u,F,{value:!0}),u}}catch{}return H(new A("INTERNAL",`${r}: function dispatch failed (${String(n)}): ${o}`,{status:n}),a)},cr=new Set([400,403,404,422]),ur=new Set([z,"DISPATCH_UNAUTHENTICATED"]),K=r=>V(r)&&r[B]===!0,lr=r=>K(r)&&cr.has(r.status)&&!ur.has(r.code),fr=r=>K(r)&&r[F]===!0,dr=(r,t,o)=>new A("INTERNAL",`${r}: function dispatch to "${t}" timed out after ${String(o)}ms`,{status:503}),Rr=r=>{const{label:t}=r,o=globalThis.fetch,a=r.fetchImpl??(typeof o=="function"?o.bind(globalThis):void 0);return async(n,e,s={})=>{if(typeof a!="function")throw new TypeError(`${t}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const i=()=>r.argsAlreadyEncoded===!0?e??{}:er(t,n.__lunoraRef,e??{}),c=r.env.LUNORA_ORIGIN_URL;if(typeof c!="string"||c.length===0)throw new A("INTERNAL",`${t}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const u=r.env.LUNORA_ADMIN_TOKEN;if(typeof u!="string"||u.length===0)throw new A("INTERNAL",`${t}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const w=`${or(c)}${nr}`,h={authorization:`Bearer ${u}`,"content-type":"application/json"};r.traceparent!==void 0&&r.traceparent.length>0&&(h.traceparent=r.traceparent),r.identity?.userId!==void 0&&(h["x-lunora-userid"]=rr(r.identity.userId)),r.identity?.claims!==void 0&&(h["x-lunora-identity"]=q(r.identity.claims));const d=s.timeoutMs??x,E=Y(void 0,d,()=>new DOMException(`dispatch timed out after ${String(d)}ms`,"TimeoutError")),m=y=>{throw y instanceof Error&&y.name==="TimeoutError"?dr(t,n.__lunoraRef,d):y};let l;try{try{l=await a(w,{body:JSON.stringify({args:i(),functionPath:n.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:h,method:"POST",signal:E.signal})}catch(N){return m(N)}if(!l.ok){let N;try{N=await l.text()}catch(J){return m(J)}throw ir(t,l,N,s.messageId)}let y;try{y=await l.text()}catch(N){return m(N)}if(y.length===0)return;let v;try{v=JSON.parse(y)}catch{throw new A("INTERNAL",`${t}: function dispatch returned a non-JSON body (${String(l.status)}): ${y}`,{status:l.status})}if(v===null||typeof v!="object"||Array.isArray(v)||!("result"in v))throw new A("INTERNAL",`${t}: function dispatch returned a JSON body that is not a { result } envelope (${String(l.status)}): ${y}`,{status:l.status});return p(v.result)}finally{E.dispose()}}},Or=(r,t)=>`${r}/${t}`,L=(r,t)=>{let o=0;return(a,n,e)=>(o+=1,r(a,n,{...e,dedupId:e?.dedupId??`${t}.${String(o)}`}))},yr=1e3,pr=3e4,mr=2e3,hr=1e3,gr=6e5,br={day:864e5,hour:36e5,millisecond:1,minute:6e4,second:1e3,week:6048e5},wr=/^(\d+(?:\.\d+)?)\s*([a-z]+?)s?$/iu,Er=r=>{if(r===void 0)return gr;if(typeof r=="number")return Number.isFinite(r)&&r>0?r:void 0;const t=wr.exec(r.trim()),o=t===null?void 0:br[(t[2]??"").toLowerCase()];return t===null||o===void 0?void 0:Number(t[1])*o},M=(r,t)=>{const o=Er(r?.timeout);return o===void 0?void 0:t+o-mr},Ar=async r=>{await new Promise(t=>{setTimeout(t,r)})},P=(r,t)=>async(o,a,n)=>{const e=async(s,i)=>{try{const c=s===void 0||t===void 0?n:{...n,timeoutMs:Math.min(x,t-Date.now())};return await r(o,a,c)}catch(c){if(!fr(c))throw c;const u=Date.now(),w=s??u,h=w+_-u,d=t===void 0?Number.POSITIVE_INFINITY:t-u-hr,E=Math.min(h,d);if(E<=0)throw c;await Ar(Math.min(i,E));const m=Date.now();if(m>=w+_||t!==void 0&&m>=t)throw c;return e(w,Math.min(i*2,pr))}};return e(void 0,yr)},vr=(r,t)=>W(r,t,"step args"),$r=r=>{let t=0;return async(o,a,n)=>{const e=`${r.dedupNamespace}#step${String(t)}`;t+=1;const s=n?.config??o.config,i=n?.name??o.name;if(i.startsWith($))return R(`@lunora/workflow: ctx.runStep step name "${i}" is reserved — the "${$}" prefix is used by the framework's own steps`,void 0,r.nonRetryableErrorClass);const c=vr(o.args,a),u=async d=>{const E={attempt:d.attempt,config:d.config,env:r.env,log:r.log,run:L(P(r.run,M(d.config,Date.now())),e),step:d.step};let m;try{m=await o.handler(E,c)}catch(l){return lr(l)?R(l.message,l,r.nonRetryableErrorClass):G(l,r.nonRetryableErrorClass)}if(!o.returns)return m;try{return o.returns.parse(m)}catch(l){const y=l instanceof Error?l.message:String(l);return R(`step "${o.name}" returns validation failed: ${y}`,l,r.nonRetryableErrorClass)}},w=o.rollback,h=w?{rollback:async d=>{await w({args:c,env:r.env,error:d.error,log:r.log,output:d.output,run:L(P(r.run,M(o.rollbackConfig,Date.now())),`${e}rollback`)})},rollbackConfig:o.rollbackConfig}:void 0;return s===void 0?r.step.do(i,u,h):r.step.do(i,s,u,h)}};export{$r as c,Or as d,Rr as l,L as p,vr as v,P as w};
|
|
@@ -61,6 +61,31 @@ interface WorkflowCreateOptions<Params = Record<string, unknown>> {
|
|
|
61
61
|
/** Instance retention policy (defaults to the workflow's `defaultRetention`, else the plan default). */
|
|
62
62
|
retention?: WorkflowRetention;
|
|
63
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* Options for `Workflow.createBatch`, in the object form Cloudflare's binding takes:
|
|
66
|
+
* explicit `instances`, or `count` instances that share one `params` and `retention`.
|
|
67
|
+
* The array form is deprecated upstream and is not accepted here: it left out any
|
|
68
|
+
* instance it failed to create, and reported nothing for it.
|
|
69
|
+
*/
|
|
70
|
+
type WorkflowCreateBatchOptions<Params = Record<string, unknown>> = {
|
|
71
|
+
instances: ReadonlyArray<WorkflowCreateOptions<Params>>;
|
|
72
|
+
} | {
|
|
73
|
+
count: number;
|
|
74
|
+
params?: Params;
|
|
75
|
+
retention?: WorkflowRetention;
|
|
76
|
+
};
|
|
77
|
+
/** One instance a batch did not create. `index` is its position in the input (`count` form: its position among the `count`). */
|
|
78
|
+
interface WorkflowCreateBatchError {
|
|
79
|
+
code: number;
|
|
80
|
+
id?: string;
|
|
81
|
+
index: number;
|
|
82
|
+
message: string;
|
|
83
|
+
}
|
|
84
|
+
/** Result of `Workflow.createBatch`: the instances that were created, and an error for each one that was not. */
|
|
85
|
+
interface WorkflowCreateBatchResult {
|
|
86
|
+
created: WorkflowInstanceLike[];
|
|
87
|
+
errors: WorkflowCreateBatchError[];
|
|
88
|
+
}
|
|
64
89
|
/** Result of `Workflow.deleteBatch`. Mirrors Cloudflare's `WorkflowBatchDeleteResult`: one entry per input position. */
|
|
65
90
|
interface WorkflowBatchDeleteResult {
|
|
66
91
|
deleted: {
|
|
@@ -132,7 +157,7 @@ interface WorkflowInstanceLike {
|
|
|
132
157
|
*/
|
|
133
158
|
interface WorkflowBindingLike<Params = Record<string, unknown>> {
|
|
134
159
|
create: (options?: WorkflowCreateOptions<Params>) => Promise<WorkflowInstanceLike>;
|
|
135
|
-
createBatch: (
|
|
160
|
+
createBatch: (options: WorkflowCreateBatchOptions<Params>) => Promise<WorkflowCreateBatchResult>;
|
|
136
161
|
deleteBatch: (instanceIds: ReadonlyArray<string>) => Promise<WorkflowBatchDeleteResult>;
|
|
137
162
|
get: (id: string) => Promise<WorkflowInstanceLike>;
|
|
138
163
|
}
|
|
@@ -620,8 +645,11 @@ interface WorkflowDefinition<Params = Record<string, unknown>, Output = unknown>
|
|
|
620
645
|
interface WorkflowHandle<Params = Record<string, unknown>> {
|
|
621
646
|
/** Start a new instance (optionally with an id + params). */
|
|
622
647
|
create: (options?: WorkflowCreateOptions<Params>) => Promise<WorkflowInstanceLike>;
|
|
623
|
-
/**
|
|
624
|
-
|
|
648
|
+
/**
|
|
649
|
+
* Start many instances in one batched RPC. Returns what was created and a
|
|
650
|
+
* per-instance error for each one that was not, so a failed instance is never silently dropped.
|
|
651
|
+
*/
|
|
652
|
+
createBatch: (options: WorkflowCreateBatchOptions<Params>) => Promise<WorkflowCreateBatchResult>;
|
|
625
653
|
/** Delete up to 100 instances and their stored state; ids that do not exist come back as per-instance errors. */
|
|
626
654
|
deleteBatch: (instanceIds: ReadonlyArray<string>) => Promise<WorkflowBatchDeleteResult>;
|
|
627
655
|
/** Get a handle to an existing instance by id. */
|
|
@@ -655,4 +683,4 @@ interface LunoraWorkflowsOptions {
|
|
|
655
683
|
*/
|
|
656
684
|
bindings: Record<string, WorkflowBindingLike>;
|
|
657
685
|
}
|
|
658
|
-
export { ArgsOf as A, BranchCompensationParams as B,
|
|
686
|
+
export { ArgsOf as A, BranchCompensationParams as B, WorkflowCreateBatchResult as C, WorkflowCreateOptions as D, WorkflowDelayFunctionLike as E, FunctionKind as F, WorkflowHandle as G, WorkflowHandler as H, InferStepArgs as I, WorkflowInstanceEventLike as J, WorkflowInstanceLike as K, LunoraWorkflowsOptions as L, WorkflowInstanceSubscribeOptionsLike as M, WorkflowInstanceSubscriptionLike as N, WorkflowParallelFunction as O, WorkflowRetention as P, WorkflowRollbackContextLike as Q, RunFunctionOptions as R, StepArgsValidator as S, WorkflowRollbackHandlerLike as T, WorkflowSpawnFunction as U, WorkflowSpawnOptions as V, WorkflowDefinition as W, WorkflowStatusResult as X, WorkflowStepConfigLike as Y, WorkflowStepContextLike as Z, WorkflowStepRollbackOptionsLike as _, Workflows as a, WorkflowEventDefinition as b, StepConfig as c, StepDefinition as d, WorkflowConfig as e, WorkflowBranch as f, WorkflowInstanceStatus as g, WorkflowEventLike as h, WorkflowStepLike as i, WorkflowRunContext as j, WorkflowLogger as k, WorkflowRunFunction as l, WorkflowRunStepFunction as m, WorkflowWaitForEventFunction as n, FunctionReference as o, RunStepOptions as p, StepHandler as q, StepRollbackContext as r, StepRollbackHandler as s, StepRunContext as t, WaitForEventOptions as u, WorkflowBatchDeleteResult as v, WorkflowBindingLike as w, WorkflowBranchOutputs as x, WorkflowCreateBatchError as y, WorkflowCreateBatchOptions as z };
|
|
@@ -61,6 +61,31 @@ interface WorkflowCreateOptions<Params = Record<string, unknown>> {
|
|
|
61
61
|
/** Instance retention policy (defaults to the workflow's `defaultRetention`, else the plan default). */
|
|
62
62
|
retention?: WorkflowRetention;
|
|
63
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* Options for `Workflow.createBatch`, in the object form Cloudflare's binding takes:
|
|
66
|
+
* explicit `instances`, or `count` instances that share one `params` and `retention`.
|
|
67
|
+
* The array form is deprecated upstream and is not accepted here: it left out any
|
|
68
|
+
* instance it failed to create, and reported nothing for it.
|
|
69
|
+
*/
|
|
70
|
+
type WorkflowCreateBatchOptions<Params = Record<string, unknown>> = {
|
|
71
|
+
instances: ReadonlyArray<WorkflowCreateOptions<Params>>;
|
|
72
|
+
} | {
|
|
73
|
+
count: number;
|
|
74
|
+
params?: Params;
|
|
75
|
+
retention?: WorkflowRetention;
|
|
76
|
+
};
|
|
77
|
+
/** One instance a batch did not create. `index` is its position in the input (`count` form: its position among the `count`). */
|
|
78
|
+
interface WorkflowCreateBatchError {
|
|
79
|
+
code: number;
|
|
80
|
+
id?: string;
|
|
81
|
+
index: number;
|
|
82
|
+
message: string;
|
|
83
|
+
}
|
|
84
|
+
/** Result of `Workflow.createBatch`: the instances that were created, and an error for each one that was not. */
|
|
85
|
+
interface WorkflowCreateBatchResult {
|
|
86
|
+
created: WorkflowInstanceLike[];
|
|
87
|
+
errors: WorkflowCreateBatchError[];
|
|
88
|
+
}
|
|
64
89
|
/** Result of `Workflow.deleteBatch`. Mirrors Cloudflare's `WorkflowBatchDeleteResult`: one entry per input position. */
|
|
65
90
|
interface WorkflowBatchDeleteResult {
|
|
66
91
|
deleted: {
|
|
@@ -132,7 +157,7 @@ interface WorkflowInstanceLike {
|
|
|
132
157
|
*/
|
|
133
158
|
interface WorkflowBindingLike<Params = Record<string, unknown>> {
|
|
134
159
|
create: (options?: WorkflowCreateOptions<Params>) => Promise<WorkflowInstanceLike>;
|
|
135
|
-
createBatch: (
|
|
160
|
+
createBatch: (options: WorkflowCreateBatchOptions<Params>) => Promise<WorkflowCreateBatchResult>;
|
|
136
161
|
deleteBatch: (instanceIds: ReadonlyArray<string>) => Promise<WorkflowBatchDeleteResult>;
|
|
137
162
|
get: (id: string) => Promise<WorkflowInstanceLike>;
|
|
138
163
|
}
|
|
@@ -620,8 +645,11 @@ interface WorkflowDefinition<Params = Record<string, unknown>, Output = unknown>
|
|
|
620
645
|
interface WorkflowHandle<Params = Record<string, unknown>> {
|
|
621
646
|
/** Start a new instance (optionally with an id + params). */
|
|
622
647
|
create: (options?: WorkflowCreateOptions<Params>) => Promise<WorkflowInstanceLike>;
|
|
623
|
-
/**
|
|
624
|
-
|
|
648
|
+
/**
|
|
649
|
+
* Start many instances in one batched RPC. Returns what was created and a
|
|
650
|
+
* per-instance error for each one that was not, so a failed instance is never silently dropped.
|
|
651
|
+
*/
|
|
652
|
+
createBatch: (options: WorkflowCreateBatchOptions<Params>) => Promise<WorkflowCreateBatchResult>;
|
|
625
653
|
/** Delete up to 100 instances and their stored state; ids that do not exist come back as per-instance errors. */
|
|
626
654
|
deleteBatch: (instanceIds: ReadonlyArray<string>) => Promise<WorkflowBatchDeleteResult>;
|
|
627
655
|
/** Get a handle to an existing instance by id. */
|
|
@@ -655,4 +683,4 @@ interface LunoraWorkflowsOptions {
|
|
|
655
683
|
*/
|
|
656
684
|
bindings: Record<string, WorkflowBindingLike>;
|
|
657
685
|
}
|
|
658
|
-
export { ArgsOf as A, BranchCompensationParams as B,
|
|
686
|
+
export { ArgsOf as A, BranchCompensationParams as B, WorkflowCreateBatchResult as C, WorkflowCreateOptions as D, WorkflowDelayFunctionLike as E, FunctionKind as F, WorkflowHandle as G, WorkflowHandler as H, InferStepArgs as I, WorkflowInstanceEventLike as J, WorkflowInstanceLike as K, LunoraWorkflowsOptions as L, WorkflowInstanceSubscribeOptionsLike as M, WorkflowInstanceSubscriptionLike as N, WorkflowParallelFunction as O, WorkflowRetention as P, WorkflowRollbackContextLike as Q, RunFunctionOptions as R, StepArgsValidator as S, WorkflowRollbackHandlerLike as T, WorkflowSpawnFunction as U, WorkflowSpawnOptions as V, WorkflowDefinition as W, WorkflowStatusResult as X, WorkflowStepConfigLike as Y, WorkflowStepContextLike as Z, WorkflowStepRollbackOptionsLike as _, Workflows as a, WorkflowEventDefinition as b, StepConfig as c, StepDefinition as d, WorkflowConfig as e, WorkflowBranch as f, WorkflowInstanceStatus as g, WorkflowEventLike as h, WorkflowStepLike as i, WorkflowRunContext as j, WorkflowLogger as k, WorkflowRunFunction as l, WorkflowRunStepFunction as m, WorkflowWaitForEventFunction as n, FunctionReference as o, RunStepOptions as p, StepHandler as q, StepRollbackContext as r, StepRollbackHandler as s, StepRunContext as t, WaitForEventOptions as u, WorkflowBatchDeleteResult as v, WorkflowBindingLike as w, WorkflowBranchOutputs as x, WorkflowCreateBatchError as y, WorkflowCreateBatchOptions as z };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/workflow",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.73",
|
|
4
4
|
"description": "Durable workflows for Lunora: defineWorkflow over Cloudflare Workflows, generated WorkflowEntrypoint classes, and the ctx.workflows surface",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
52
|
-
"@lunora/values": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
52
|
+
"@lunora/values": "1.0.0-alpha.61"
|
|
53
53
|
},
|
|
54
54
|
"engines": {
|
|
55
55
|
"node": "^22.15.0 || >=24.11.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";import{h as w,B as l}from"./branch-marker-CCpWfS5k.mjs";import{eventDefinitionProblem as f}from"./defineWorkflowEvent-suERPEEV.mjs";const c=o=>{if(w(o?.params))throw new a("BAD_REQUEST",`@lunora/workflow: params ${l}`)},i=o=>({create:async e=>(c(e),o.create(e)),createBatch:async e=>{for(const r of e)c(r);return o.createBatch(e)},deleteBatch:async e=>o.deleteBatch(e),get:async e=>o.get(e),sendEvent:async(e,r,n)=>{const t=f(r);if(t!==void 0)throw new a("BAD_REQUEST",`@lunora/workflow: sendEvent ${t}`);await(await o.get(e)).sendEvent({payload:r.payload.parse(n),type:r.type})}}),h=o=>{const e=o.bindings??{};return{get:r=>{const n=e[r];if(n===void 0){const t=Object.keys(e),s=t.length===0?"no workflows are declared":`known workflows: ${t.join(", ")}`;throw new a("INTERNAL",`@lunora/workflow: no workflow named "${r}" (${s})`)}return i(n)}}};export{h as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as E,isLunoraError as V}from"@lunora/errors";import{parseValidatorMap as W}from"@lunora/values";import{RESERVED_EVENT_TYPE_PREFIX as R}from"./defineWorkflowEvent-suERPEEV.mjs";import{raiseNonRetryable as O,convertNonRetryableError as G}from"./NonRetryableError-BPu01mU8.mjs";const _=9e5,z="DISPATCH_IN_PROGRESS",X="x-lunora-dispatch-declined",Y=(r,t,o)=>{if(t===void 0)return{dispose:()=>{},signal:r};const a=new AbortController,n=setTimeout(()=>{a.abort(o())},t);return{dispose:()=>{clearTimeout(n)},signal:a.signal}},T=r=>{let t="";for(let o=0;o<r.length;o+=32768)t+=String.fromCharCode(...r.subarray(o,o+32768));return btoa(t)},Q=r=>{const t=atob(r),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.codePointAt(a)??0;return o},h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",C=r=>{let t="",o=0;const a=r.length-2;for(;o<a;o+=3){const e=r[o]<<16|r[o+1]<<8|r[o+2];t+=h.charAt(e>>18&63)+h.charAt(e>>12&63)+h.charAt(e>>6&63)+h.charAt(e&63)}const n=r.length-o;if(n===1){const e=r[o]<<16;t+=h.charAt(e>>18&63)+h.charAt(e>>12&63)}else if(n===2){const e=r[o]<<16|r[o+1]<<8;t+=h.charAt(e>>18&63)+h.charAt(e>>12&63)+h.charAt(e>>6&63)}return t};new TextDecoder;const k=new TextEncoder,$="=",Z=r=>{for(let t=0;t<r.length;t+=1)if(r.charCodeAt(t)>255)return!1;return!0},q=r=>C(k.encode(JSON.stringify(r))),rr=r=>!r.startsWith($)&&Z(r)?r:`${$}${C(k.encode(r))}`,f="$lunora.wire$",S=64,U=1024,I="__proto__",D={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},j={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},tr=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},g=(r,t=0)=>{if(t>S)throw new RangeError(`wire-codec: value nesting exceeds the ${S}-level limit`);if(r===void 0)return[f,"undefined"];if(r===null)return null;const o=typeof r;if(o==="bigint")return[f,"bigint",r.toString()];if(o==="number"){const e=r;return Number.isNaN(e)?[f,"nan"]:e===1/0?[f,"inf"]:e===-1/0?[f,"-inf"]:e}if(o!=="object")return r;if(r instanceof Date)return[f,"date",g(r.getTime(),t+1)];if(r instanceof Error){const e=r,s={};for(const c of Object.keys(e)){if(e[c]===void 0)continue;const u=g(e[c],t+1);c===I?Object.defineProperty(s,c,{configurable:!0,enumerable:!0,value:u,writable:!0}):s[c]=u}const i=[f,"error",String(e.name),String(e.message),s];return e.cause!==void 0&&i.push(g(e.cause,t+1)),i}if(r instanceof URL)return[f,"url",r.href];if(r instanceof Map)return[f,"map",[...r.entries()].map(([e,s])=>[g(e,t+1),g(s,t+1)])];if(r instanceof Set)return[f,"set",[...r].map(e=>g(e,t+1))];if(r instanceof ArrayBuffer)return[f,"bytes",T(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,s=e.constructor.name,i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return s==="Uint8Array"?[f,"bytes",T(i)]:[f,"bytes",T(i),s]}if(Array.isArray(r)){const e=r.map(s=>g(s,t+1));return e.length>0&&e[0]===f?[f,"arr",e]:e}if(!tr(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=r,n={};for(const e of Object.keys(a)){const s=a[e];if(s===void 0)continue;const i=g(s,t+1);e===I?Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):n[e]=i}return n},p=(r,t=0)=>{if(t>S)throw new RangeError(`wire-codec: value nesting exceeds the ${S}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===f)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(n=>p(n,t+1));case"bigint":{const n=r[2];if(typeof n!="string"||n.length>U||!/^-?\d+$/.test(n))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${U} digits)`);return BigInt(n)}case"date":{const n=p(r[2],t+1);if(typeof n!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(n)}case"map":{const n=r[2];return new Map(n.map(e=>{if(!Array.isArray(e)||e.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[p(e[0],t+1),p(e[1],t+1)]}))}case"set":return new Set(r[2].map(n=>p(n,t+1)));case"url":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(n)}case"error":{const n=r[2],e=r[3];if(typeof n!="string"||typeof e!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(j,n)?j[n]:void 0)??Error,i=new s(e);i.name!==n&&Object.defineProperty(i,"name",{configurable:!0,value:n,writable:!0});const c=p(r[4],t+1);if(c===null||typeof c!="object"||Array.isArray(c))throw new TypeError("wire-codec: malformed error — props must be an object");for(const u of Object.keys(c))u===I?Object.defineProperty(i,u,{configurable:!0,enumerable:!0,value:c[u],writable:!0}):i[u]=c[u];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:p(r[5],t+1),writable:!0}),i}case"bytes":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const e=Q(n);if(T(e)!==n)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=r[3]??"Uint8Array";if(s==="ArrayBuffer")return e.buffer.byteLength===e.byteLength?e.buffer:e.slice().buffer;const i=Object.hasOwn(D,s)?D[s]:void 0;return i?new i(e.slice().buffer):e}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(n=>p(n,t+1))}return r.map(n=>p(n,t+1))}const o=r,a={};for(const n of Object.keys(o)){const e=p(o[n],t+1);n===I?Object.defineProperty(a,n,{configurable:!0,enumerable:!0,value:e,writable:!0}):a[n]=e}return a},er=(r,t,o)=>{try{return g(o)}catch(a){throw new TypeError(`${r}: cannot encode args for '${t}' — ${a instanceof Error?a.message:String(a)}`,a instanceof Error?{cause:a}:void 0)}},nr="/_lunora/scheduler/dispatch",x=3e4,or=r=>{let t=r.length;for(;t>0&&r[t-1]==="/";)t-=1;return r.slice(0,t)},B=Symbol("lunoraDispatchFailure"),F=Symbol("lunoraDispatchDecline"),ar=Symbol("lunoraDispatchMessageId"),H=(r,t)=>(t!==void 0&&Object.defineProperty(r,ar,{value:t}),r),sr=(r,t)=>(Object.defineProperty(r,B,{value:!0}),H(r,t)),ir=(r,t,o,a)=>{const{status:n}=t;try{const e=JSON.parse(o)?.error;if(typeof e=="object"&&e!==null&&typeof e.code=="string"){const{code:s,data:i,message:c}=e,u=sr(new E(s,typeof c=="string"?c:void 0,{data:i,status:n}),a);return t.headers.get(X)==="1"&&Object.defineProperty(u,F,{value:!0}),u}}catch{}return H(new E("INTERNAL",`${r}: function dispatch failed (${String(n)}): ${o}`,{status:n}),a)},cr=new Set([400,403,404,422]),ur=new Set([z,"DISPATCH_UNAUTHENTICATED"]),K=r=>V(r)&&r[B]===!0,lr=r=>K(r)&&cr.has(r.status)&&!ur.has(r.code),fr=r=>K(r)&&r[F]===!0,dr=(r,t,o)=>new E("INTERNAL",`${r}: function dispatch to "${t}" timed out after ${String(o)}ms`,{status:503}),Or=r=>{const{label:t}=r,o=globalThis.fetch,a=r.fetchImpl??(typeof o=="function"?o.bind(globalThis):void 0);return async(n,e,s={})=>{if(typeof a!="function")throw new TypeError(`${t}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const i=()=>r.argsAlreadyEncoded===!0?e??{}:er(t,n.__lunoraRef,e??{}),c=r.env.LUNORA_ORIGIN_URL;if(typeof c!="string"||c.length===0)throw new E("INTERNAL",`${t}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const u=r.env.LUNORA_ADMIN_TOKEN;if(typeof u!="string"||u.length===0)throw new E("INTERNAL",`${t}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const w=`${or(c)}${nr}`,b={authorization:`Bearer ${u}`,"content-type":"application/json"};r.traceparent!==void 0&&r.traceparent.length>0&&(b.traceparent=r.traceparent),r.identity?.userId!==void 0&&(b["x-lunora-userid"]=rr(r.identity.userId)),r.identity?.claims!==void 0&&(b["x-lunora-identity"]=q(r.identity.claims));const d=s.timeoutMs??x,A=Y(void 0,d,()=>new DOMException(`dispatch timed out after ${String(d)}ms`,"TimeoutError")),m=y=>{throw y instanceof Error&&y.name==="TimeoutError"?dr(t,n.__lunoraRef,d):y};let l;try{try{l=await a(w,{body:JSON.stringify({args:i(),functionPath:n.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:b,method:"POST",signal:A.signal})}catch(N){return m(N)}if(!l.ok){let N;try{N=await l.text()}catch(J){return m(J)}throw ir(t,l,N,s.messageId)}let y;try{y=await l.text()}catch(N){return m(N)}if(y.length===0)return;let v;try{v=JSON.parse(y)}catch{throw new E("INTERNAL",`${t}: function dispatch returned a non-JSON body (${String(l.status)}): ${y}`,{status:l.status})}if(v===null||typeof v!="object"||Array.isArray(v)||!("result"in v))throw new E("INTERNAL",`${t}: function dispatch returned a JSON body that is not a { result } envelope (${String(l.status)}): ${y}`,{status:l.status});return p(v.result)}finally{A.dispose()}}},Rr=(r,t)=>`${r}/${t}`,L=(r,t)=>{let o=0;return(a,n,e)=>(o+=1,r(a,n,{...e,dedupId:e?.dedupId??`${t}.${String(o)}`}))},yr=1e3,pr=3e4,mr=2e3,br=1e3,hr=6e5,gr={day:864e5,hour:36e5,millisecond:1,minute:6e4,second:1e3,week:6048e5},wr=/^(\d+(?:\.\d+)?)\s*([a-z]+?)s?$/iu,Ar=r=>{if(r===void 0)return hr;if(typeof r=="number")return Number.isFinite(r)&&r>0?r:void 0;const t=wr.exec(r.trim()),o=t===null?void 0:gr[(t[2]??"").toLowerCase()];return t===null||o===void 0?void 0:Number(t[1])*o},M=(r,t)=>{const o=Ar(r?.timeout);return o===void 0?void 0:t+o-mr},Er=async r=>{await new Promise(t=>{setTimeout(t,r)})},P=(r,t)=>async(o,a,n)=>{const e=async(s,i)=>{try{const c=s===void 0||t===void 0?n:{...n,timeoutMs:Math.min(x,t-Date.now())};return await r(o,a,c)}catch(c){if(!fr(c))throw c;const u=Date.now(),w=s??u,b=w+_-u,d=t===void 0?Number.POSITIVE_INFINITY:t-u-br,A=Math.min(b,d);if(A<=0)throw c;await Er(Math.min(i,A));const m=Date.now();if(m>=w+_||t!==void 0&&m>=t)throw c;return e(w,Math.min(i*2,pr))}};return e(void 0,yr)},vr=(r,t)=>W(r,t,"step args"),_r=r=>{let t=0;return async(o,a,n)=>{const e=`${r.dedupNamespace}#step${String(t)}`;t+=1;const s=n?.config??o.config,i=n?.name??o.name;if(i.startsWith(R))return O(`@lunora/workflow: ctx.runStep step name "${i}" is reserved — the "${R}" prefix is used by the framework's own steps`,void 0,r.nonRetryableErrorClass);const c=vr(o.args,a),u=async d=>{const A={attempt:d.attempt,config:d.config,env:r.env,log:r.log,run:L(P(r.run,M(d.config,Date.now())),e),step:d.step};let m;try{m=await o.handler(A,c)}catch(l){return lr(l)?O(l.message,l,r.nonRetryableErrorClass):G(l,r.nonRetryableErrorClass)}if(!o.returns)return m;try{return o.returns.parse(m)}catch(l){const y=l instanceof Error?l.message:String(l);return O(`step "${o.name}" returns validation failed: ${y}`,l,r.nonRetryableErrorClass)}},w=o.rollback,b=w?{rollback:async d=>{await w({args:c,env:r.env,error:d.error,log:r.log,output:d.output,run:L(P(r.run,M(o.rollbackConfig,Date.now())),`${e}rollback`)})},rollbackConfig:o.rollbackConfig}:void 0;return s===void 0?r.step.do(i,u,b):r.step.do(i,s,u,b)}};export{_r as c,Rr as d,Or as l,L as p,vr as v,P as w};
|