@lunora/workflow 1.0.0-alpha.6 → 1.0.0-alpha.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +25 -2
  3. package/dist/do/index.d.mts +16 -16
  4. package/dist/do/index.d.ts +16 -16
  5. package/dist/do/index.mjs +1 -44
  6. package/dist/index.d.mts +191 -122
  7. package/dist/index.d.ts +191 -122
  8. package/dist/index.mjs +1 -9
  9. package/dist/packem_shared/MAX_BRANCHES-j59ZUUSu.mjs +1 -0
  10. package/dist/packem_shared/NonRetryableError-BPu01mU8.mjs +1 -0
  11. package/dist/packem_shared/WorkflowsRestError-Ccq1FUR1.mjs +1 -0
  12. package/dist/packem_shared/branch-marker-CCpWfS5k.mjs +1 -0
  13. package/dist/packem_shared/createRunStep-DPafHcOc.mjs +1 -0
  14. package/dist/packem_shared/createWaitForEvent-D5Ohn2Pz.mjs +1 -0
  15. package/dist/packem_shared/createWorkflowContext-zQR_9N-v.mjs +1 -0
  16. package/dist/packem_shared/createWorkflowRunContext-DhzM_oYZ.mjs +1 -0
  17. package/dist/packem_shared/createWorkflows-LvAyUyKq.mjs +1 -0
  18. package/dist/packem_shared/defineStep-D1-9eOnA.mjs +1 -0
  19. package/dist/packem_shared/defineWorkflow-tKaIifbZ.mjs +1 -0
  20. package/dist/packem_shared/defineWorkflowEvent-suERPEEV.mjs +1 -0
  21. package/dist/packem_shared/isDuplicateInstanceError-CecnqNAa.mjs +1 -0
  22. package/dist/packem_shared/run-step-IuqYPWKG.mjs +1 -0
  23. package/dist/packem_shared/types.d-DKvSidAr.d.mts +560 -0
  24. package/dist/packem_shared/types.d-DKvSidAr.d.ts +560 -0
  25. package/package.json +3 -3
  26. package/dist/packem_shared/MAX_BRANCHES-D6cQabJ1.mjs +0 -132
  27. package/dist/packem_shared/NonRetryableError-Dn2dTyBS.mjs +0 -27
  28. package/dist/packem_shared/WorkflowsRestError-zmjOxTR1.mjs +0 -117
  29. package/dist/packem_shared/createRunStep-8jOXxP2o.mjs +0 -54
  30. package/dist/packem_shared/createWorkflowContext-DfSgBq5I.mjs +0 -14
  31. package/dist/packem_shared/createWorkflowRunContext-C09mSbgk.mjs +0 -112
  32. package/dist/packem_shared/createWorkflows-BC1Mwjwe.mjs +0 -25
  33. package/dist/packem_shared/defineStep-DJQtLw7g.mjs +0 -28
  34. package/dist/packem_shared/defineWorkflow-DbUC-oCN.mjs +0 -15
  35. package/dist/packem_shared/types.d-C9W6rEWv.d.mts +0 -425
  36. package/dist/packem_shared/types.d-C9W6rEWv.d.ts +0 -425
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { a as Workflows, L as LunoraWorkflowsOptions, S as StepArgsValidator, b as StepConfig, c as StepDefinition, d as WorkflowConfig, W as WorkflowDefinition, e as WorkflowBranch, f as WorkflowInstanceStatus, g as WorkflowEventLike, h as WorkflowStepLike, i as WorkflowRunContext, j as WorkflowLogger, k as WorkflowRunFunction, l as WorkflowRunStepFunction } from "./packem_shared/types.d-C9W6rEWv.js";
2
- export type { A as ArgsOf, B as BranchCompensationParams, F as FunctionReference, I as InferStepArgs, R as RunFunctionOptions, m as RunStepOptions, n as StepHandler, o as StepRollbackContext, p as StepRollbackHandler, q as StepRunContext, r as WorkflowBindingLike, s as WorkflowBranchOutputs, t as WorkflowCreateOptions, u as WorkflowHandle, v as WorkflowHandler, w as WorkflowInstanceLike, x as WorkflowParallelFunction, y as WorkflowRollbackContextLike, z as WorkflowRollbackHandlerLike, C as WorkflowSpawnFunction, D as WorkflowSpawnOptions, E as WorkflowStatusResult, G as WorkflowStepConfigLike, H as WorkflowStepContextLike, J as WorkflowStepRollbackOptionsLike } from "./packem_shared/types.d-C9W6rEWv.js";
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-DKvSidAr.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 WorkflowBindingLike, w as WorkflowBranchOutputs, x as WorkflowCreateOptions, y as WorkflowHandle, z as WorkflowHandler, C as WorkflowInstanceLike, D as WorkflowParallelFunction, E as WorkflowRollbackContextLike, G as WorkflowRollbackHandlerLike, H as WorkflowSpawnFunction, J as WorkflowSpawnOptions, K as WorkflowStatusResult, M as WorkflowStepConfigLike, N as WorkflowStepContextLike, O as WorkflowStepRollbackOptionsLike } from "./packem_shared/types.d-DKvSidAr.js";
3
+ import { Validator } from '@lunora/values';
3
4
  import { LunoraError } from '@lunora/errors';
4
- import '@lunora/values';
5
5
  /** Wiring info for one declared workflow, emitted by codegen into the generated shard. */
6
6
  interface WorkflowBindingSpec {
7
7
  /** The Cloudflare `Workflow` binding name, e.g. `WORKFLOW_ORDER_PIPELINE`. */
@@ -10,108 +10,152 @@ interface WorkflowBindingSpec {
10
10
  exportName: string;
11
11
  }
12
12
  /**
13
- * Build the `ctx.workflows` handle for a request: resolve every spec's
14
- * `env[binding]` into the `exportName → Workflow binding` map and wrap it in
15
- * {@link createWorkflows}. A spec whose binding is absent from `env` is skipped
16
- * here — the helpful "no workflow named …" error is raised lazily by
17
- * `workflows.get(name)` when the missing workflow is actually used.
18
- */
13
+ * Build the `ctx.workflows` handle for a request: resolve every spec's
14
+ * `env[binding]` into the `exportName → Workflow binding` map and wrap it in
15
+ * {@link createWorkflows}. A spec whose binding is absent from `env` is skipped
16
+ * here — the helpful "no workflow named …" error is raised lazily by
17
+ * `workflows.get(name)` when the missing workflow is actually used.
18
+ */
19
19
  declare const createWorkflowContext: (env: Record<string, unknown>, specs: ReadonlyArray<WorkflowBindingSpec>) => Workflows;
20
20
  /**
21
- * Build the `ctx.workflows` handle from a map of `lunora/workflows.ts` export
22
- * name → Cloudflare `Workflow` binding. `get(name)` resolves the typed handle;
23
- * an unknown name throws with the list of declared workflows.
24
- */
21
+ * Build the `ctx.workflows` handle from a map of `lunora/workflows.ts` export
22
+ * name → Cloudflare `Workflow` binding. `get(name)` resolves the typed handle;
23
+ * an unknown name throws with the list of declared workflows.
24
+ */
25
25
  declare const createWorkflows: (options: LunoraWorkflowsOptions) => Workflows;
26
26
  /**
27
- * Declare a reusable durable step. Same `args` map shape a Lunora `query` /
28
- * `mutation` / `action` uses, so a step reads like a function:
29
- *
30
- * ```ts
31
- * // lunora/steps.ts
32
- * import { defineStep } from "@lunora/workflow";
33
- * import { v } from "@lunora/values";
34
- *
35
- * export const fetchImage = defineStep("fetch image", {
36
- * args: { imageKey: v.string() },
37
- * returns: v.object({ data: v.bytes() }),
38
- * handler: async (ctx, { imageKey }) => {
39
- * const object = await (ctx.env.BUCKET as R2Bucket).get(imageKey);
40
- * return { data: new Uint8Array(await object!.arrayBuffer()) };
41
- * },
42
- * rollback: async (ctx) => {
43
- * await (ctx.env.BUCKET as R2Bucket).delete(`tmp/${ctx.args.imageKey}`);
44
- * },
45
- * });
46
- * ```
47
- *
48
- * Then, inside a `defineWorkflow` handler:
49
- *
50
- * ```ts
51
- * const { data } = await ctx.runStep(fetchImage, { imageKey: ctx.params.imageKey });
52
- * ```
53
- */
27
+ * Declare an external event, its wire type, and its payload shape.
28
+ *
29
+ * ```ts
30
+ * // lunora/events.ts
31
+ * import { defineWorkflowEvent } from "@lunora/workflow";
32
+ * import { v } from "@lunora/values";
33
+ *
34
+ * export const orderApproved = defineWorkflowEvent("order-approved", v.object({ approvedBy: v.string() }));
35
+ * ```
36
+ *
37
+ * Wait on it inside a workflow body — the payload is typed and validated:
38
+ *
39
+ * ```ts
40
+ * const { approvedBy } = await ctx.waitForEvent(orderApproved, { name: "await approval", timeout: "7 days" });
41
+ * ```
42
+ *
43
+ * …and send it from a mutation/action with the same definition:
44
+ *
45
+ * ```ts
46
+ * await ctx.workflows.get("orderPipeline").sendEvent(instanceId, orderApproved, { approvedBy });
47
+ * ```
48
+ */
49
+ declare const defineWorkflowEvent: <Payload>(type: string, payload: Validator<Payload>) => WorkflowEventDefinition<Payload>;
50
+ /**
51
+ * True when a value is usable as an event definition. The brand alone is not the
52
+ * test: the predicate hands the caller a `type` and a `payload.parse`, so it checks
53
+ * for both (and for the reserved namespace) rather than trusting a public boolean.
54
+ */
55
+ declare const isWorkflowEventDefinition: (value: unknown) => value is WorkflowEventDefinition;
56
+ /**
57
+ * Declare a reusable durable step. Same `args` map shape a Lunora `query` /
58
+ * `mutation` / `action` uses, so a step reads like a function:
59
+ *
60
+ * ```ts
61
+ * // lunora/steps.ts
62
+ * import { defineStep } from "@lunora/workflow";
63
+ * import { v } from "@lunora/values";
64
+ *
65
+ * export const fetchImage = defineStep("fetch image", {
66
+ * args: { imageKey: v.string() },
67
+ * returns: v.object({ data: v.bytes() }),
68
+ * handler: async (ctx, { imageKey }) => {
69
+ * const object = await (ctx.env.BUCKET as R2Bucket).get(imageKey);
70
+ * return { data: new Uint8Array(await object!.arrayBuffer()) };
71
+ * },
72
+ * rollback: async (ctx) => {
73
+ * await (ctx.env.BUCKET as R2Bucket).delete(`tmp/${ctx.args.imageKey}`);
74
+ * },
75
+ * });
76
+ * ```
77
+ *
78
+ * Then, inside a `defineWorkflow` handler:
79
+ *
80
+ * ```ts
81
+ * const { data } = await ctx.runStep(fetchImage, { imageKey: ctx.params.imageKey });
82
+ * ```
83
+ */
54
84
  declare const defineStep: <A extends StepArgsValidator, Result>(name: string, config: StepConfig<A, Result>) => StepDefinition<A, Result>;
55
85
  /** True when a value is a `defineStep` result (the runtime brand check). */
56
86
  declare const isStepDefinition: (value: unknown) => value is StepDefinition;
57
87
  /**
58
- * The generated `WorkflowEntrypoint` class name for a `lunora/workflows.ts`
59
- * export: `orderPipeline` → `OrderPipelineWorkflow`. wrangler's
60
- * `workflows[].class_name` references it, so codegen and the config layer MUST
61
- * derive it identically — always via this helper.
62
- */
88
+ * The generated `WorkflowEntrypoint` class name for a `lunora/workflows.ts`
89
+ * export: `orderPipeline` → `OrderPipelineWorkflow`. wrangler's
90
+ * `workflows[].class_name` references it, so codegen and the config layer MUST
91
+ * derive it identically — always via this helper.
92
+ */
63
93
  declare const workflowClassName: (exportName: string) => string;
64
94
  /**
65
- * The wrangler binding name for a workflow export: `orderPipeline` →
66
- * `WORKFLOW_ORDER_PIPELINE`, `etl` → `WORKFLOW_ETL`. The `WORKFLOW_` prefix
67
- * namespaces these away from `SHARD`/`SESSION`/`SCHEDULER`/`CONTAINER_*` so a
68
- * workflow export can never collide with the built-in bindings.
69
- */
95
+ * The wrangler binding name for a workflow export: `orderPipeline` →
96
+ * `WORKFLOW_ORDER_PIPELINE`, `etl` → `WORKFLOW_ETL`. The `WORKFLOW_` prefix
97
+ * namespaces these away from `SHARD`/`SESSION`/`SCHEDULER`/`CONTAINER_*` so a
98
+ * workflow export can never collide with the built-in bindings.
99
+ */
70
100
  declare const workflowBindingName: (exportName: string) => string;
71
101
  /**
72
- * The stable workflow name wrangler registers (`workflows[].name`):
73
- * `orderPipeline` → `order-pipeline`. Used as the deployed workflow's
74
- * identifier when no explicit `name` override is given.
75
- */
102
+ * The stable workflow name wrangler registers (`workflows[].name`):
103
+ * `orderPipeline` → `order-pipeline`. Used as the deployed workflow's
104
+ * identifier when no explicit `name` override is given.
105
+ */
76
106
  declare const workflowDefaultName: (exportName: string) => string;
77
107
  /**
78
- * Declare a durable workflow deployed alongside the app. Pure validation +
79
- * branding: codegen discovers the export, emits the `WorkflowEntrypoint`
80
- * subclass (`_generated/workflows.ts`), and wires the typed `ctx.workflows`
81
- * handle; the config layer reconciles the wrangler `workflows[]` entry from the
82
- * same definition.
83
- *
84
- * ```ts
85
- * // lunora/workflows.ts
86
- * import { defineWorkflow } from "@lunora/workflow";
87
- * import { api } from "./_generated/api";
88
- *
89
- * export const orderPipeline = defineWorkflow&lt;{ orderId: string }>({
90
- * handler: async (ctx) => {
91
- * const order = await ctx.step.do("load", () => ctx.run(api.orders.get, { id: ctx.params.orderId }));
92
- * await ctx.step.sleep("cool-off", "1 minute");
93
- * await ctx.step.do("charge", () => ctx.run(api.payments.charge, { orderId: ctx.params.orderId }));
94
- * return order;
95
- * },
96
- * });
97
- * ```
98
- */
108
+ * Declare a durable workflow deployed alongside the app. Pure validation +
109
+ * branding: codegen discovers the export, emits the `WorkflowEntrypoint`
110
+ * subclass (`_generated/workflows.ts`), and wires the typed `ctx.workflows`
111
+ * handle; the config layer reconciles the wrangler `workflows[]` entry from the
112
+ * same definition.
113
+ *
114
+ * ```ts
115
+ * // lunora/workflows.ts
116
+ * import { defineWorkflow } from "@lunora/workflow";
117
+ * import { api } from "./_generated/api";
118
+ *
119
+ * export const orderPipeline = defineWorkflow<{ orderId: string }>({
120
+ * handler: async (ctx) => {
121
+ * const order = await ctx.step.do("load", () => ctx.run(api.orders.get, { id: ctx.params.orderId }));
122
+ * await ctx.step.sleep("cool-off", "1 minute");
123
+ * // A raw `step.do` retries its callback in place, so a WRITE made through
124
+ * // it needs an explicit dedup id (or use `ctx.runStep`, which pins one).
125
+ * await ctx.step.do("charge", () =>
126
+ * ctx.run(api.payments.charge, { orderId: ctx.params.orderId }, { dedupId: `charge:${ctx.params.orderId}` }),
127
+ * );
128
+ * return order;
129
+ * },
130
+ * });
131
+ * ```
132
+ */
99
133
  declare const defineWorkflow: <Params = Record<string, unknown>, Output = unknown>(config: WorkflowConfig<Params, Output>) => WorkflowDefinition<Params, Output>;
100
134
  /** True when a value is a `defineWorkflow` result (the runtime brand check). */
101
135
  declare const isWorkflowDefinition: (value: unknown) => value is WorkflowDefinition;
102
136
  /**
103
- * Throw from a workflow step (or handler) to fail the instance immediately
104
- * **without** retrying — the portable mirror of `cloudflare:workflows`'
105
- * `NonRetryableError`. Importable from Node, so workflow code stays unit-testable.
106
- *
107
- * ```ts
108
- * import { NonRetryableError } from "@lunora/workflow";
109
- *
110
- * if (order.status === "cancelled") {
111
- * throw new NonRetryableError("order already cancelled — no point retrying");
112
- * }
113
- * ```
114
- */
137
+ * Whether a `WorkflowBinding.create()` rejection is a duplicate-instance-id
138
+ * error — the idempotency signal that a *previous* attempt's create already
139
+ * applied — as opposed to a transient or config failure (Workflows service
140
+ * error, instance-creation quota, bad params).
141
+ *
142
+ * Every other failure MUST surface, so the caller retries or fails visibly
143
+ * rather than silently reporting success for work that never started.
144
+ */
145
+ declare const isDuplicateInstanceError: (error: unknown) => boolean;
146
+ /**
147
+ * Throw from a workflow step (or handler) to fail the instance immediately
148
+ * **without** retrying — the portable mirror of `cloudflare:workflows`'
149
+ * `NonRetryableError`. Importable from Node, so workflow code stays unit-testable.
150
+ *
151
+ * ```ts
152
+ * import { NonRetryableError } from "@lunora/workflow";
153
+ *
154
+ * if (order.status === "cancelled") {
155
+ * throw new NonRetryableError("order already cancelled — no point retrying");
156
+ * }
157
+ * ```
158
+ */
115
159
  declare class NonRetryableError extends Error {
116
160
  constructor(message: string, name?: string);
117
161
  }
@@ -120,34 +164,31 @@ declare const isNonRetryableError: (value: unknown) => value is NonRetryableErro
120
164
  /** Constructor shape of `cloudflare:workflows`' native `NonRetryableError`. */
121
165
  type NativeNonRetryableErrorConstructor = new (message: string, name?: string) => Error;
122
166
  /**
123
- * Rebuild a portable {@link NonRetryableError} as the native Cloudflare one,
124
- * preserving its `name`, `message`, `cause`, and `stack`. Used at the `src/do`
125
- * boundary where the native constructor is available; everywhere else the
126
- * portable error is thrown unchanged (and still honored by name).
127
- */
167
+ * Rebuild a portable {@link NonRetryableError} as the native Cloudflare one,
168
+ * preserving its `name`, `message`, `cause`, and `stack`. Used at the `src/do`
169
+ * boundary where the native constructor is available; everywhere else the
170
+ * portable error is thrown unchanged (and still honored by name).
171
+ */
128
172
  declare const toNativeNonRetryableError: (error: NonRetryableError, NativeNonRetryableError: NativeNonRetryableErrorConstructor) => Error;
129
173
  /**
130
- * If `error` is a portable {@link NonRetryableError} and a native constructor is
131
- * available, rethrow it as the native error; otherwise rethrow `error` as-is.
132
- * Always throws — the `never` return lets callers `return convertNonRetryableError(...)`.
133
- */
174
+ * If `error` is a portable {@link NonRetryableError} and a native constructor is
175
+ * available, rethrow it as the native error; otherwise rethrow `error` as-is.
176
+ * Always throws — the `never` return lets callers `return convertNonRetryableError(...)`.
177
+ */
134
178
  declare const convertNonRetryableError: (error: unknown, NativeNonRetryableError: NativeNonRetryableErrorConstructor | undefined) => never;
135
179
  /** Hard cap on branches per `ctx.parallel` call — auto-scale, never silently spawn unbounded DOs. */
136
180
  declare const MAX_BRANCHES = 100;
137
- /** The params key the parent injects so a child knows to signal completion back. Stripped before the user handler sees `ctx.params`. */
138
-
139
181
  /**
140
- * Build a single fan-out branch: a declared child workflow referenced by its
141
- * `lunora/workflows.ts` export name, plus the params it is created with. Pass the
142
- * output type as the generic argument so `ctx.parallel(...)` infers the result
143
- * tuple — e.g. `branch("imageTag", { key })` typed as `branch` of `{ tags }`.
144
- */
182
+ * Build a single fan-out branch: a declared child workflow referenced by its
183
+ * `lunora/workflows.ts` export name, plus the params it is created with. Pass the
184
+ * output type as the generic argument so `ctx.parallel(...)` infers the result
185
+ * tuple — e.g. `branch("imageTag", { key })` typed as `branch` of `{ tags }`.
186
+ */
145
187
  declare const branch: <Output = unknown>(workflow: string, params?: Record<string, unknown>, options?: {
146
188
  compensateWith?: string;
147
189
  id?: string;
148
190
  timeout?: number | string;
149
191
  }) => WorkflowBranch<Output>;
150
- /** Build the success outcome a completed branch reports to its parent. */
151
192
  /** The lifecycle mutations the REST API exposes via `PATCH .../instances/{id}`. */
152
193
  type WorkflowInstanceAction = "pause" | "resume" | "terminate";
153
194
  /** Configuration for a {@link WorkflowsRestClient}. */
@@ -194,7 +235,14 @@ interface WorkflowInstancePage {
194
235
  perPage: number;
195
236
  totalCount?: number;
196
237
  }
197
- /** Thrown when the REST API responds non-2xx or `success: false`; carries the status plus body for the caller to surface. */
238
+ /**
239
+ * Thrown when the REST API responds non-2xx or `success: false`; carries the
240
+ * status plus a capped body preview, with the full body on `cause`.
241
+ *
242
+ * The preview is capped because the Cloudflare API's auth/authorization error
243
+ * text (and its HTML gateway pages) would otherwise ride out verbatim —
244
+ * `WORKFLOWS_REST_ERROR` is non-internal, so the message reaches the browser.
245
+ */
198
246
  declare class WorkflowsRestError extends LunoraError {
199
247
  constructor(status: number, body: string);
200
248
  }
@@ -219,11 +267,11 @@ interface WorkflowsRestClient {
219
267
  }>;
220
268
  }
221
269
  /**
222
- * Build a {@link WorkflowsRestClient}. Each call hits the account-scoped REST
223
- * endpoint with the bearer token, unwraps Cloudflare's
224
- * `{ success, errors, result, result_info }` envelope, and normalizes the
225
- * snake_case payload into the camelCase shapes the studio renders.
226
- */
270
+ * Build a {@link WorkflowsRestClient}. Each call hits the account-scoped REST
271
+ * endpoint with the bearer token, unwraps Cloudflare's
272
+ * `{ success, errors, result, result_info }` envelope, and normalizes the
273
+ * snake_case payload into the camelCase shapes the studio renders.
274
+ */
227
275
  declare const createWorkflowsRestClient: (config: WorkflowsRestConfig) => WorkflowsRestClient;
228
276
  interface RunContextOptions<Params> {
229
277
  env: Record<string, unknown>;
@@ -237,17 +285,19 @@ interface RunContextOptions<Params> {
237
285
  /** Assemble the {@link WorkflowRunContext} passed to a `defineWorkflow` handler. */
238
286
  declare const createWorkflowRunContext: <Params = Record<string, unknown>>(options: RunContextOptions<Params>) => WorkflowRunContext<Params>;
239
287
  /**
240
- * Validate a step's args through its validator map, prefixing any
241
- * `ValidationError` with `step args.&lt;key>` so the failure points at the
242
- * offending field. Delegates to `@lunora/values`' shared {@link parseValidatorMap}
243
- * — the same parser the procedure builder and HTTP routes use — so the
244
- * optional-skip and error-prefix semantics stay in lockstep across the framework.
245
- */
288
+ * Validate a step's args through its validator map, prefixing any
289
+ * `ValidationError` with `step args.<key>` so the failure points at the
290
+ * offending field. Delegates to `@lunora/values`' shared {@link parseValidatorMap}
291
+ * — the same parser the procedure builder and HTTP routes use — so the
292
+ * optional-skip and error-prefix semantics stay in lockstep across the framework.
293
+ */
246
294
  declare const validateStepArgs: (validators: StepArgsValidator, source: Record<string, unknown>) => Record<string, unknown>;
247
295
  /** Dependencies needed to run a step: the native step API plus the workflow's env / runner / logger. */
248
296
  interface RunStepDeps {
249
297
  /** The Worker environment bindings, surfaced on the step context. */
250
298
  env: Record<string, unknown>;
299
+ /** This workflow instance's id — the namespace for the replay-dedup ids the steps' dispatches carry. */
300
+ instanceId: string;
251
301
  /** Structured logger surfaced on the step context. */
252
302
  log: WorkflowLogger;
253
303
  /** Native `cloudflare:workflows` `NonRetryableError` constructor — injected by `src/do`; absent in Node tests. */
@@ -258,10 +308,29 @@ interface RunStepDeps {
258
308
  step: WorkflowStepLike;
259
309
  }
260
310
  /**
261
- * Build the `ctx.runStep` function bound to one workflow invocation. Each call
262
- * runs the step through `step.do(...)`: validate args → run body → validate
263
- * result (when `returns` is declared), with any portable `NonRetryableError`
264
- * converted to the native one and any declared rollback forwarded to Cloudflare.
265
- */
311
+ * Build the `ctx.runStep` function bound to one workflow invocation. Each call
312
+ * runs the step through `step.do(...)`: validate args → run body → validate
313
+ * result (when `returns` is declared), with any portable `NonRetryableError`
314
+ * converted to the native one and any declared rollback forwarded to Cloudflare.
315
+ */
266
316
  declare const createRunStep: (deps: RunStepDeps) => WorkflowRunStepFunction;
267
- export { type LunoraWorkflowsOptions, MAX_BRANCHES, type NativeNonRetryableErrorConstructor, NonRetryableError, type StepArgsValidator, type StepConfig, type StepDefinition, type WorkflowBindingSpec, type WorkflowBranch, type WorkflowConfig, type WorkflowDefinition, type WorkflowEventLike, type WorkflowInstanceAction, type WorkflowInstanceDetail, type WorkflowInstancePage, type WorkflowInstanceStatus, type WorkflowInstanceSummary, type WorkflowLogger, type WorkflowRunContext, type WorkflowRunFunction, type WorkflowRunStepFunction, type WorkflowStepDetail, type WorkflowStepLike, type Workflows, type WorkflowsRestClient, type WorkflowsRestConfig, WorkflowsRestError, branch, convertNonRetryableError, createRunStep, createWorkflowContext, createWorkflowRunContext, createWorkflows, createWorkflowsRestClient, defineStep, defineWorkflow, isNonRetryableError, isStepDefinition, isWorkflowDefinition, toNativeNonRetryableError, validateStepArgs, workflowBindingName, workflowClassName, workflowDefaultName };
317
+ /** Dependencies one workflow invocation's `ctx.waitForEvent` closes over. */
318
+ interface WaitForEventDeps {
319
+ /** Native `cloudflare:workflows` `NonRetryableError` constructor — injected by `src/do`; absent in Node tests. */
320
+ nonRetryableErrorClass?: NativeNonRetryableErrorConstructor;
321
+ /** The native Cloudflare durable-step API. */
322
+ step: WorkflowStepLike;
323
+ }
324
+ /**
325
+ * Build `ctx.waitForEvent` for one workflow invocation.
326
+ *
327
+ * Every failure here is **non-retryable**. A malformed definition or a reserved
328
+ * step name is a deterministic programmer error, and a payload that fails the
329
+ * validator has already consumed the event — replaying the wait cannot produce a
330
+ * different value, it can only hibernate the instance until its timeout. Each is
331
+ * raised through the shared {@link raiseNonRetryable}, the same classification path
332
+ * `ctx.runStep` uses, so the native error reaches Cloudflare and the instance fails
333
+ * fast.
334
+ */
335
+ declare const createWaitForEvent: (deps: WaitForEventDeps) => WorkflowWaitForEventFunction;
336
+ export { type LunoraWorkflowsOptions, MAX_BRANCHES, type NativeNonRetryableErrorConstructor, NonRetryableError, type StepArgsValidator, type StepConfig, type StepDefinition, type WorkflowBindingSpec, type WorkflowBranch, type WorkflowConfig, type WorkflowDefinition, type WorkflowEventDefinition, type WorkflowEventLike, type WorkflowInstanceAction, type WorkflowInstanceDetail, type WorkflowInstancePage, type WorkflowInstanceStatus, type WorkflowInstanceSummary, type WorkflowLogger, type WorkflowRunContext, type WorkflowRunFunction, type WorkflowRunStepFunction, type WorkflowStepDetail, type WorkflowStepLike, type WorkflowWaitForEventFunction, type Workflows, type WorkflowsRestClient, type WorkflowsRestConfig, WorkflowsRestError, branch, convertNonRetryableError, createRunStep, createWaitForEvent, createWorkflowContext, createWorkflowRunContext, createWorkflows, createWorkflowsRestClient, defineStep, defineWorkflow, defineWorkflowEvent, isDuplicateInstanceError, isNonRetryableError, isStepDefinition, isWorkflowDefinition, isWorkflowEventDefinition, toNativeNonRetryableError, validateStepArgs, workflowBindingName, workflowClassName, workflowDefaultName };
package/dist/index.mjs CHANGED
@@ -1,9 +1 @@
1
- export { createWorkflowContext } from './packem_shared/createWorkflowContext-DfSgBq5I.mjs';
2
- export { default as createWorkflows } from './packem_shared/createWorkflows-BC1Mwjwe.mjs';
3
- export { defineStep, isStepDefinition } from './packem_shared/defineStep-DJQtLw7g.mjs';
4
- export { defineWorkflow, isWorkflowDefinition, workflowBindingName, workflowClassName, workflowDefaultName } from './packem_shared/defineWorkflow-DbUC-oCN.mjs';
5
- export { NonRetryableError, convertNonRetryableError, isNonRetryableError, toNativeNonRetryableError } from './packem_shared/NonRetryableError-Dn2dTyBS.mjs';
6
- export { MAX_BRANCHES, branch } from './packem_shared/MAX_BRANCHES-D6cQabJ1.mjs';
7
- export { WorkflowsRestError, createWorkflowsRestClient } from './packem_shared/WorkflowsRestError-zmjOxTR1.mjs';
8
- export { createWorkflowRunContext } from './packem_shared/createWorkflowRunContext-C09mSbgk.mjs';
9
- export { createRunStep, validateStepArgs } from './packem_shared/createRunStep-8jOXxP2o.mjs';
1
+ import{createWorkflowContext as e}from"./packem_shared/createWorkflowContext-zQR_9N-v.mjs";import{default as f}from"./packem_shared/createWorkflows-LvAyUyKq.mjs";import{defineWorkflowEvent as a,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 w,isWorkflowDefinition as x,workflowBindingName as k,workflowClassName as c,workflowDefaultName as E}from"./packem_shared/defineWorkflow-tKaIifbZ.mjs";import{NonRetryableError as N,convertNonRetryableError as R,isNonRetryableError as v,toNativeNonRetryableError as d}from"./packem_shared/NonRetryableError-BPu01mU8.mjs";import{MAX_BRANCHES as u,branch as C}from"./packem_shared/MAX_BRANCHES-j59ZUUSu.mjs";import{WorkflowsRestError as S,createWorkflowsRestClient as y}from"./packem_shared/WorkflowsRestError-Ccq1FUR1.mjs";import{createWorkflowRunContext as g}from"./packem_shared/createWorkflowRunContext-DhzM_oYZ.mjs";import{c as h,v as F}from"./packem_shared/run-step-IuqYPWKG.mjs";import{createWaitForEvent as I}from"./packem_shared/createWaitForEvent-D5Ohn2Pz.mjs";import{isDuplicateInstanceError as X}from"./packem_shared/isDuplicateInstanceError-CecnqNAa.mjs";export{u as MAX_BRANCHES,N as NonRetryableError,S as WorkflowsRestError,C as branch,R as convertNonRetryableError,h as createRunStep,I as createWaitForEvent,e as createWorkflowContext,g as createWorkflowRunContext,f as createWorkflows,y as createWorkflowsRestClient,p as defineStep,w as defineWorkflow,a as defineWorkflowEvent,X as isDuplicateInstanceError,v as isNonRetryableError,s as isStepDefinition,x as isWorkflowDefinition,i as isWorkflowEventDefinition,d as toNativeNonRetryableError,F as validateStepArgs,k as workflowBindingName,c as workflowClassName,E as workflowDefaultName};
@@ -0,0 +1 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{h as x,B as A,a as g}from"./branch-marker-CCpWfS5k.mjs";import{RESERVED_EVENT_TYPE_PREFIX as P}from"./defineWorkflowEvent-suERPEEV.mjs";import{NonRetryableError as f}from"./NonRetryableError-BPu01mU8.mjs";import{isDuplicateInstanceError as N}from"./isDuplicateInstanceError-CecnqNAa.mjs";const p=t=>t.toString(16).padStart(4,"0"),O=t=>{let e=8997,n=33826,a=40164,o=52210;for(let c=0;c<t.length;c+=1){e^=t.charCodeAt(c);const l=e*435,d=n*435,h=a*435+e*256,r=o*435+n*256,s=d+(l>>>16),i=h+(s>>>16),u=r+(i>>>16);e=l&65535,n=s&65535,a=i&65535,o=u&65535}return p(o)+p(a)+p(n)+p(e)},v=100,I=100,b="lunora:spawn:",k="lunora:await:",C="lunora:signal:",W="lunora:compensate:",F=17,w=(t,e="")=>t.length+e.length<=I?`${t}${e}`:`${t.slice(0,I-e.length-F)}-${O(t)}${e}`,S=`${P}branch:`,G=(t,e,n)=>({compensateWith:n?.compensateWith,id:n?.id,params:e,timeout:n?.timeout,workflow:t}),T=t=>t instanceof Error?{message:t.message,name:t.name}:{message:String(t),name:"Error"},M=t=>({status:"ok",value:t}),U=t=>({error:T(t),status:"error"}),$=1048576,X=t=>{try{return String(t instanceof Error?t.message:t).slice(0,200)}catch{return"the failure itself could not be described"}},B=t=>{let e;try{e=new TextEncoder().encode(JSON.stringify(t)).length}catch(n){return{error:{message:`branch outcome cannot be serialised to JSON (${X(n)}) — the parent can never receive it. Return a plain JSON value (no cycles, no BigInt, no class instance that fails to serialise) or a reference the parent can dereference (an R2 key, a row id)`,name:"BranchOutputUnserializable"},status:"error"}}return e<=$?t:{error:{message:`branch outcome serialises to ${String(e)} bytes, over Cloudflare's ${String($)}-byte event payload limit — the parent can never receive it. Return a reference the parent can dereference (an R2 key, a row id) instead of the payload itself`,name:"BranchOutputTooLarge"},status:"error"}},E=async(t,e)=>{try{return{attached:!1,instance:await t.create(e)}}catch(n){if(!N(n))throw n;return{attached:!0,instance:await t.get(e.id)}}},j=async t=>{const{error:e,output:n,status:a}=await t.status();if(a==="complete")return M(n);if(a==="errored"||a==="terminated")return{error:e??{message:`branch instance ${a}`,name:"Error"},status:"error"}},D=t=>{if(typeof t!="object"||t===null)return;const{status:e}=t;return e==="error"||e==="ok"?t:void 0};class m extends Error{branchError;kind;plan;constructor(e,n,a){super(n.message),this.branchError=n,this.kind=a,this.plan=e}}const H=async(t,e,n)=>{for(let a=e.length-1;a>=0;a-=1){const o=e[a],c=o?.plan.item.compensateWith;if(!(o===void 0||c===void 0))try{const l=t.resolveBinding(c);await t.step.do(`${W}${o.plan.childId}`,async()=>{const d=w(o.plan.childId,"-compensate"),h={branch:o.plan.item.workflow,error:n,index:o.plan.index,output:o.output};return await E(l,{id:d,params:h}),d})}catch(l){t.log?.error(`ctx.parallel: group-saga compensation "${c}" for branch "${o.plan.item.workflow}" (#${String(o.plan.index)}) failed`,l)}}},q=t=>async n=>{if(n.length===0)return[];if(n.length>v)throw new f(`ctx.parallel: ${String(n.length)} branches exceeds the cap of ${String(v)} — split the fan-out or raise the work into fewer child workflows`);const a=n.map((r,s)=>{const i=w(t.nextChildId(r.id));return{childId:i,eventType:`${S}${i}`,index:s,item:r}}),o=new Set;for(const r of a){if(o.has(r.childId))throw new f(`ctx.parallel: duplicate branch id "${r.childId}" — each branch in a group must resolve to a unique child instance id (check explicit \`id\` options)`);o.add(r.childId)}const c=await Promise.all(a.map(r=>t.step.do(`${b}${r.childId}`,async()=>{const s=t.resolveBinding(r.item.workflow),i={eventType:r.eventType,index:r.index,parentBinding:t.parentBinding,parentId:t.instanceId},{attached:u,instance:_}=await E(s,{id:r.childId,params:{...r.item.params,[g]:i}});if(!u)return;const y=await j(_);return y===void 0?void 0:B(y)}))),l=Array.from({length:a.length}),d=Array.from({length:a.length}),h=async(r,s)=>{let i;if(s===void 0)try{i=(await t.step.waitForEvent(`${k}${r.childId}`,{timeout:r.item.timeout,type:r.eventType})).payload}catch(u){throw new m(r,T(u),"join failed")}else i=s;if(i.status==="error")throw new m(r,i.error,"failed");d[r.index]={output:i.value,plan:r},l[r.index]=i.value};try{await Promise.all(a.map((r,s)=>h(r,D(c[s]))))}catch(r){throw r instanceof m?(await H(t,d.filter(s=>s!==void 0),r.branchError),new f(`ctx.parallel: branch "${r.plan.item.workflow}" (#${String(r.plan.index)}) ${r.kind}: ${r.branchError.message}`)):r}return l},Q=t=>async(e,n,a)=>{if(x(n))throw new R("BAD_REQUEST",`@lunora/workflow: params ${A}`);const o=w(t.nextChildId(a?.id));return await t.step.do(`${b}${o}`,async()=>{const c=t.resolveBinding(e);return await E(c,{id:o,params:n}),o}),t.resolveBinding(e).get(o)},Z=t=>{if(typeof t!="object"||t===null)return;const e=t[g];if(typeof e!="object"||e===null)return;const n=e;if(!(typeof n.eventType!="string"||typeof n.parentBinding!="string"||typeof n.parentId!="string"||typeof n.index!="number")&&!(!n.parentBinding.startsWith("WORKFLOW_")||!n.eventType.startsWith(S)))return{eventType:n.eventType,index:n.index,parentBinding:n.parentBinding,parentId:n.parentId}},tt=t=>{if(typeof t!="object"||t===null)return t;const e={...t};return Reflect.deleteProperty(e,g),e},L=async(t,e,n)=>{const a=t.env[e.parentBinding];if(!a||typeof a.get!="function")return;const o=a.get.bind(a),c=B(n);await t.step.do(`${C}${String(e.index)}`,async()=>(await(await o(e.parentId)).sendEvent({payload:c,type:e.eventType}),e.eventType))},et=async(t,e,n)=>{try{await L(t,e,n)}catch(a){t.log?.error(`@lunora/workflow: failed to signal branch parent "${e.parentId}" (event "${e.eventType}")`,a)}};export{v as MAX_BRANCHES,G as branch,q as createParallel,Q as createSpawn,U as errorOutcome,Z as extractBranchMarker,M as okOutcome,L as signalBranchParent,et as signalBranchParentSafe,tt as stripBranchMarker};
@@ -0,0 +1 @@
1
+ import{isDuplicateInstanceError as E}from"./isDuplicateInstanceError-CecnqNAa.mjs";const s="__lunoraNonRetryable";class r extends Error{constructor(e,n="NonRetryableError"){super(e),this.name=n,this[s]=!0}}const a=t=>t instanceof Error&&t[s]===!0,c=(t,e)=>{const n=new e(t.message,t.name);return t.stack!==void 0&&(n.stack=t.stack),t.cause!==void 0&&n.cause===void 0&&(n.cause=t.cause),n},i=(t,e)=>{throw e!==void 0&&a(t)?c(t,e):t},u=(t,e,n)=>{const o=new r(t);return e!==void 0&&(o.cause=e),i(o,n)};export{r as NonRetryableError,i as convertNonRetryableError,E as isDuplicateInstanceError,a as isNonRetryableError,u as raiseNonRetryable,c as toNativeNonRetryableError};
@@ -0,0 +1 @@
1
+ import{LunoraError as _}from"@lunora/errors";const m=256,A=t=>t.length>m?`${t.slice(0,m)}… (truncated)`:t,$="https://api.cloudflare.com/client/v4/accounts",b={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},S=t=>typeof t=="string"&&Object.hasOwn(b,t)?t:"unknown",u=t=>typeof t=="string"&&t!==""?t:void 0,R=(t,a)=>typeof t=="string"?t:a,O=t=>typeof t=="boolean"?t:void 0,I=t=>Array.isArray(t)?t.length:typeof t=="number"?t:void 0,f=t=>({createdOn:u(t.created_on),endedOn:u(t.ended_on),id:R(t.id,""),startedOn:u(t.started_on),status:S(t.status)}),C=t=>({attempts:I(t.attempts),end:u(t.end),error:t.error,name:R(t.name,""),output:t.output,start:u(t.start),success:O(t.success),type:u(t.type)});class g extends _{constructor(a,i){super("WORKFLOWS_REST_ERROR",`Cloudflare Workflows REST API returned ${String(a)}: ${A(i)}`,{cause:i,name:"WorkflowsRestError",status:a})}}const E=t=>{const a=t.fetch??globalThis.fetch.bind(globalThis),i=`${$}/${t.accountId}/workflows`,p=async(o,r)=>{const n=await a(`${i}${o}`,{...r,headers:{Authorization:`Bearer ${t.apiToken}`,"Content-Type":"application/json"}}),e=await n.text();let s;try{s=JSON.parse(e)}catch{throw new g(n.status,e)}if(!n.ok||s.success===!1)throw new g(n.status,e);return s};return{getInstance:async({instanceId:o,workflowName:r})=>{const e=(await p(`/${encodeURIComponent(r)}/instances/${encodeURIComponent(o)}`)).result??{},s=Array.isArray(e.steps)?e.steps:[];return{...f(e),error:e.error,output:e.output,params:e.params,steps:s.map(d=>C(d))}},listInstances:async({page:o,perPage:r,status:n,workflowName:e})=>{const s=new URLSearchParams;n!==void 0&&s.set("status",n),o!==void 0&&s.set("page",String(o)),r!==void 0&&s.set("per_page",String(r));const d=s.toString()===""?"":`?${s.toString()}`,l=await p(`/${encodeURIComponent(e)}/instances${d}`),y=Array.isArray(l.result)?l.result:[],c=l.result_info??{};return{instances:y.map(h=>f(h)),page:typeof c.page=="number"?c.page:o??1,perPage:typeof c.per_page=="number"?c.per_page:r??y.length,totalCount:typeof c.total_count=="number"?c.total_count:void 0}},setInstanceStatus:async({action:o,instanceId:r,workflowName:n})=>{const s=(await p(`/${encodeURIComponent(n)}/instances/${encodeURIComponent(r)}/status`,{body:JSON.stringify({status:o}),method:"PATCH"})).result??{};return{status:S(s.status)}}}};export{g as WorkflowsRestError,E as createWorkflowsRestClient};
@@ -0,0 +1 @@
1
+ const e="__lunoraBranch",o=n=>typeof n=="object"&&n!==null&&Object.hasOwn(n,e),a=`may not contain the reserved workflow branch-marker key ("${e}")`;export{a as B,e as a,o as h};
@@ -0,0 +1 @@
1
+ import{c as p,v as o}from"./run-step-IuqYPWKG.mjs";import"./defineWorkflowEvent-suERPEEV.mjs";import"./NonRetryableError-BPu01mU8.mjs";export{p as createRunStep,o as validateStepArgs};
@@ -0,0 +1 @@
1
+ import{eventDefinitionProblem as m,RESERVED_EVENT_TYPE_PREFIX as i}from"./defineWorkflowEvent-suERPEEV.mjs";import{raiseNonRetryable as a}from"./NonRetryableError-BPu01mU8.mjs";const c=e=>async(r,t)=>{const n=m(r);if(n!==void 0)return a(`@lunora/workflow: ctx.waitForEvent ${n}`,void 0,e.nonRetryableErrorClass);if(t?.name?.startsWith(i)===!0)return a(`@lunora/workflow: ctx.waitForEvent step name "${t.name}" is reserved — the "${i}" prefix is used by the framework's own steps`,void 0,e.nonRetryableErrorClass);const s=await e.step.waitForEvent(t?.name??`event:${r.type}`,{timeout:t?.timeout,type:r.type});try{return r.payload.parse(s.payload)}catch(o){const l=o instanceof Error?o.message:String(o);return a(`@lunora/workflow: event "${r.type}" payload validation failed: ${l}`,o,e.nonRetryableErrorClass)}};export{c as createWaitForEvent};
@@ -0,0 +1 @@
1
+ import r from"./createWorkflows-LvAyUyKq.mjs";const i=(n,c)=>{const o={};for(const e of c){const t=n[e.binding];t&&typeof t.create=="function"&&typeof t.createBatch=="function"&&typeof t.get=="function"&&(o[e.exportName]=t)}return r({bindings:o})};export{i as createWorkflowContext};
@@ -0,0 +1 @@
1
+ import{t as h,p as A,c as I}from"./run-step-IuqYPWKG.mjs";import{LunoraError as R}from"@lunora/errors";import{workflowBindingName as y}from"./defineWorkflow-tKaIifbZ.mjs";import{raiseNonRetryable as k}from"./NonRetryableError-BPu01mU8.mjs";import{createSpawn as T,createParallel as C}from"./MAX_BRANCHES-j59ZUUSu.mjs";import{createWaitForEvent as v}from"./createWaitForEvent-D5Ohn2Pz.mjs";const N=r=>({debug:(n,...t)=>{console.debug(r,n,...t)},error:(n,...t)=>{console.error(r,n,...t)},info:(n,...t)=>{console.info(r,n,...t)},warn:(n,...t)=>{console.warn(r,n,...t)}}),O=r=>{let n="";for(let c=0;c<r.length;c+=32768)n+=String.fromCharCode(...r.subarray(c,c+32768));return btoa(n)},$=r=>{const n=atob(r),t=new Uint8Array(n.length);for(let c=0;c<n.length;c+=1)t[c]=n.codePointAt(c)??0;return t},S="$lunora.wire$",w=64,b=1024,g="__proto__",p={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},E={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},s=(r,n=0)=>{if(n>w)throw new RangeError(`wire-codec: value nesting exceeds the ${w}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===S)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(e=>s(e,n+1));case"bigint":{const e=r[2];if(typeof e!="string"||e.length>b||!/^-?\d+$/.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${b} digits)`);return BigInt(e)}case"date":{const e=s(r[2],n+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],n+1),s(o[1],n+1)]}))}case"set":return new Set(r[2].map(e=>s(e,n+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 l=(Object.hasOwn(E,e)?E[e]:void 0)??Error,i=new l(o);i.name!==e&&Object.defineProperty(i,"name",{configurable:!0,value:e,writable:!0});const d=s(r[4],n+1);if(d===null||typeof d!="object"||Array.isArray(d))throw new TypeError("wire-codec: malformed error — props must be an object");for(const a of Object.keys(d))a===g?Object.defineProperty(i,a,{configurable:!0,enumerable:!0,value:d[a],writable:!0}):i[a]=d[a];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:s(r[5],n+1),writable:!0}),i}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=$(e);if(O(o)!==e)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const l=r[3]??"Uint8Array";if(l==="ArrayBuffer")return o.buffer.byteLength===o.byteLength?o.buffer:o.slice().buffer;const i=Object.hasOwn(p,l)?p[l]:void 0;return i?new i(o.slice().buffer):o}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(e=>s(e,n+1))}return r.map(f=>s(f,n+1))}const t=r,c={};for(const f of Object.keys(t)){const e=s(t[f],n+1);f===g?Object.defineProperty(c,f,{configurable:!0,enumerable:!0,value:e,writable:!0}):c[f]=e}return c},D=r=>{const n=N(`[workflow:${r.exportName}]`),t=h({env:r.env,fetchImpl:r.fetchImpl,label:"@lunora/workflow"}),c=A(t,`${r.event.instanceId}#body`),f=a=>{const u=y(a),m=r.env[u];if(!m||typeof m.create!="function"||typeof m.get!="function")throw new R("INTERNAL",`@lunora/workflow: cannot spawn child workflow "${a}" — no Workflow binding "${u}" on env (is it declared in lunora/workflows.ts?)`);return m};let e=0;const o=a=>{if(a!==void 0)return a;const u=`${r.event.instanceId}-c${String(e)}`;return e+=1,u},l={env:r.env,instanceId:r.event.instanceId,log:n,nextChildId:o,parentBinding:y(r.exportName),resolveBinding:f,step:r.step},d=(()=>{try{return s(r.event.payload)}catch(a){return k(`@lunora/workflow: workflow "${r.exportName}" params could not be decoded — ${a instanceof Error?a.message:String(a)}`,a,r.nonRetryableErrorClass)}})();return{env:r.env,event:r.event,...r.fetchImpl===void 0?{}:{fetchImpl:r.fetchImpl},log:n,parallel:C(l),params:d,run:c,runStep:I({env:r.env,instanceId:r.event.instanceId,log:n,nonRetryableErrorClass:r.nonRetryableErrorClass,run:t,step:r.step}),spawn:T(l),step:r.step,waitForEvent:v({nonRetryableErrorClass:r.nonRetryableErrorClass,step:r.step})}};export{D as createWorkflowRunContext};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{h as w,B as f}from"./branch-marker-CCpWfS5k.mjs";import{eventDefinitionProblem as l}from"./defineWorkflowEvent-suERPEEV.mjs";const c=r=>{if(w(r?.params))throw new a("BAD_REQUEST",`@lunora/workflow: params ${f}`)},i=r=>({create:async o=>(c(o),r.create(o)),createBatch:async o=>{for(const e of o)c(e);return r.createBatch(o)},get:async o=>r.get(o),sendEvent:async(o,e,t)=>{const n=l(e);if(n!==void 0)throw new a("BAD_REQUEST",`@lunora/workflow: sendEvent ${n}`);await(await r.get(o)).sendEvent({payload:e.payload.parse(t),type:e.type})}}),k=r=>{const o=r.bindings??{};return{get:e=>{const t=o[e];if(t===void 0){const n=Object.keys(o),s=n.length===0?"no workflows are declared":`known workflows: ${n.join(", ")}`;throw new a("INTERNAL",`@lunora/workflow: no workflow named "${e}" (${s})`)}return i(t)}}};export{k as default};
@@ -0,0 +1 @@
1
+ const n=(r,e)=>{if(typeof r!="string"||r.length===0)throw new TypeError("defineStep: `name` must be a non-empty string (the durable step label)");const t=e.args;if(typeof t!="object"||t===null)throw new TypeError("defineStep: `args` must be a validator map (e.g. `{ id: v.string() }`)");if(typeof e.handler!="function")throw new TypeError("defineStep: `handler` must be a function (the step body)");if(e.rollback!==void 0&&typeof e.rollback!="function")throw new TypeError("defineStep: `rollback` must be a function when provided");return{args:e.args,config:e.config,handler:e.handler,isLunoraStep:!0,name:r,returns:e.returns,rollback:e.rollback,rollbackConfig:e.rollbackConfig}},o=r=>typeof r=="object"&&r!==null&&r.isLunoraStep===!0;export{n as defineStep,o as isStepDefinition};
@@ -0,0 +1 @@
1
+ const e=o=>`${o.charAt(0).toUpperCase()}${o.slice(1)}Workflow`,r=o=>`WORKFLOW_${o.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g,"_").toUpperCase()}`,n=o=>o.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g,"-").toLowerCase(),t=o=>{if(typeof o.handler!="function")throw new TypeError("defineWorkflow: `handler` must be a function (the workflow body)");if(o.name!==void 0&&(typeof o.name!="string"||o.name.length===0))throw new TypeError("defineWorkflow: `name` must be a non-empty string when provided");return{...o,isLunoraWorkflow:!0}},l=o=>typeof o=="object"&&o!==null&&o.isLunoraWorkflow===!0;export{t as defineWorkflow,l as isWorkflowDefinition,r as workflowBindingName,e as workflowClassName,n as workflowDefaultName};
@@ -0,0 +1 @@
1
+ const o="lunora:",r=e=>{if(typeof e!="object"||e===null||e.isLunoraWorkflowEvent!==!0)return"expects a `defineWorkflowEvent` definition";const t=e;if(typeof t.type!="string"||t.type.length===0)return"event `type` must be a non-empty string";if(t.type.startsWith(o))return`event type "${t.type}" is reserved — the "${o}" prefix is used by the framework's own events`;if(typeof t.payload?.parse!="function")return"event `payload` must be a validator (e.g. `v.object({ ok: v.boolean() })`)"},i=(e,t)=>{if(typeof e!="string"||e.length===0)throw new TypeError("defineWorkflowEvent: `type` must be a non-empty string (the wire event type)");const n=r({isLunoraWorkflowEvent:!0,payload:t,type:e});if(n!==void 0)throw new TypeError(`defineWorkflowEvent: ${n}`);return{isLunoraWorkflowEvent:!0,payload:t,type:e}},f=e=>r(e)===void 0;export{o as RESERVED_EVENT_TYPE_PREFIX,i as defineWorkflowEvent,r as eventDefinitionProblem,f as isWorkflowEventDefinition};
@@ -0,0 +1 @@
1
+ const t=/already[\s_-]?exists/iu,e=s=>t.test(s instanceof Error?s.message:String(s));export{e as isDuplicateInstanceError};
@@ -0,0 +1 @@
1
+ import{LunoraError as w,isLunoraError as B}from"@lunora/errors";import{parseValidatorMap as M}from"@lunora/values";import{RESERVED_EVENT_TYPE_PREFIX as S}from"./defineWorkflowEvent-suERPEEV.mjs";import{raiseNonRetryable as T,convertNonRetryableError as J}from"./NonRetryableError-BPu01mU8.mjs";const F=(e,t,o)=>{if(t===void 0)return{dispose:()=>{},signal:e};const a=new AbortController,n=setTimeout(()=>{a.abort(o())},t);return{dispose:()=>{clearTimeout(n)},signal:a.signal}},$=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},K=e=>{const t=atob(e),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.codePointAt(a)??0;return o},b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",k=e=>{let t="",o=0;const a=e.length-2;for(;o<a;o+=3){const r=e[o]<<16|e[o+1]<<8|e[o+2];t+=b.charAt(r>>18&63)+b.charAt(r>>12&63)+b.charAt(r>>6&63)+b.charAt(r&63)}const n=e.length-o;if(n===1){const r=e[o]<<16;t+=b.charAt(r>>18&63)+b.charAt(r>>12&63)}else if(n===2){const r=e[o]<<16|e[o+1]<<8;t+=b.charAt(r>>18&63)+b.charAt(r>>12&63)+b.charAt(r>>6&63)}return t};new TextDecoder;const P=new TextEncoder,I="=",V=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},W=e=>k(P.encode(JSON.stringify(e))),H=e=>!e.startsWith(I)&&V(e)?e:`${I}${k(P.encode(e))}`,l="$lunora.wire$",O=64,j=1024,R="__proto__",_={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},L={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},G=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},g=(e,t=0)=>{if(t>O)throw new RangeError(`wire-codec: value nesting exceeds the ${O}-level limit`);if(e===void 0)return[l,"undefined"];if(e===null)return null;const o=typeof e;if(o==="bigint")return[l,"bigint",e.toString()];if(o==="number"){const r=e;return Number.isNaN(r)?[l,"nan"]:r===1/0?[l,"inf"]:r===-1/0?[l,"-inf"]:r}if(o!=="object")return e;if(e instanceof Date)return[l,"date",g(e.getTime(),t+1)];if(e instanceof Error){const r=e,s={};for(const c of Object.keys(r)){if(r[c]===void 0)continue;const f=g(r[c],t+1);c===R?Object.defineProperty(s,c,{configurable:!0,enumerable:!0,value:f,writable:!0}):s[c]=f}const i=[l,"error",String(r.name),String(r.message),s];return r.cause!==void 0&&i.push(g(r.cause,t+1)),i}if(e instanceof URL)return[l,"url",e.href];if(e instanceof Map)return[l,"map",[...e.entries()].map(([r,s])=>[g(r,t+1),g(s,t+1)])];if(e instanceof Set)return[l,"set",[...e].map(r=>g(r,t+1))];if(e instanceof ArrayBuffer)return[l,"bytes",$(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,s=r.constructor.name,i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return s==="Uint8Array"?[l,"bytes",$(i)]:[l,"bytes",$(i),s]}if(Array.isArray(e)){const r=e.map(s=>g(s,t+1));return r.length>0&&r[0]===l?[l,"arr",r]:r}if(!G(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} 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=e,n={};for(const r of Object.keys(a)){const s=a[r];if(s===void 0)continue;const i=g(s,t+1);r===R?Object.defineProperty(n,r,{configurable:!0,enumerable:!0,value:i,writable:!0}):n[r]=i}return n},y=(e,t=0)=>{if(t>O)throw new RangeError(`wire-codec: value nesting exceeds the ${O}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===l)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(n=>y(n,t+1));case"bigint":{const n=e[2];if(typeof n!="string"||n.length>j||!/^-?\d+$/.test(n))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${j} digits)`);return BigInt(n)}case"date":{const n=y(e[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=e[2];return new Map(n.map(r=>{if(!Array.isArray(r)||r.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(r[0],t+1),y(r[1],t+1)]}))}case"set":return new Set(e[2].map(n=>y(n,t+1)));case"url":{const n=e[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=e[2],r=e[3];if(typeof n!="string"||typeof r!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(L,n)?L[n]:void 0)??Error,i=new s(r);i.name!==n&&Object.defineProperty(i,"name",{configurable:!0,value:n,writable:!0});const c=y(e[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 f of Object.keys(c))f===R?Object.defineProperty(i,f,{configurable:!0,enumerable:!0,value:c[f],writable:!0}):i[f]=c[f];return e.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),i}case"bytes":{const n=e[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const r=K(n);if($(r)!==n)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const i=Object.hasOwn(_,s)?_[s]:void 0;return i?new i(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(n=>y(n,t+1))}return e.map(n=>y(n,t+1))}const o=e,a={};for(const n of Object.keys(o)){const r=y(o[n],t+1);n===R?Object.defineProperty(a,n,{configurable:!0,enumerable:!0,value:r,writable:!0}):a[n]=r}return a},z=(e,t,o)=>{try{return g(o)}catch(a){throw new TypeError(`${e}: cannot encode args for '${t}' — ${a instanceof Error?a.message:String(a)}`,a instanceof Error?{cause:a}:void 0)}},X="/_lunora/scheduler/dispatch",Y=3e4,q=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},x=Symbol("lunoraDispatchFailure"),Q=Symbol("lunoraDispatchMessageId"),D=(e,t)=>(t!==void 0&&Object.defineProperty(e,Q,{value:t}),e),Z=(e,t)=>(Object.defineProperty(e,x,{value:!0}),D(e,t)),ee=(e,t,o,a)=>{try{const n=JSON.parse(o)?.error;if(typeof n=="object"&&n!==null&&typeof n.code=="string"){const{code:r,data:s,message:i}=n;return Z(new w(r,typeof i=="string"?i:void 0,{data:s,status:t}),a)}}catch{}return D(new w("INTERNAL",`${e}: function dispatch failed (${String(t)}): ${o}`,{status:t}),a)},te=new Set([400,403,404,422]),re=new Set(["DISPATCH_UNAUTHENTICATED"]),ne=e=>B(e)&&e[x]===!0&&te.has(e.status)&&!re.has(e.code),oe=(e,t,o)=>new w("INTERNAL",`${e}: function dispatch to "${t}" timed out after ${String(o)}ms`,{status:503}),le=e=>{const{label:t}=e,o=globalThis.fetch,a=e.fetchImpl??(typeof o=="function"?o.bind(globalThis):void 0);return async(n,r,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=()=>e.argsAlreadyEncoded===!0?r??{}:z(t,n.__lunoraRef,r??{}),c=e.env.LUNORA_ORIGIN_URL;if(typeof c!="string"||c.length===0)throw new w("INTERNAL",`${t}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const f=e.env.LUNORA_ADMIN_TOKEN;if(typeof f!="string"||f.length===0)throw new w("INTERNAL",`${t}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const v=`${q(c)}${X}`,h={authorization:`Bearer ${f}`,"content-type":"application/json"};e.traceparent!==void 0&&e.traceparent.length>0&&(h.traceparent=e.traceparent),e.identity?.userId!==void 0&&(h["x-lunora-userid"]=H(e.identity.userId)),e.identity?.claims!==void 0&&(h["x-lunora-identity"]=W(e.identity.claims));const p=s.timeoutMs??Y,N=F(void 0,p,()=>new DOMException(`dispatch timed out after ${String(p)}ms`,"TimeoutError")),m=d=>{throw d instanceof Error&&d.name==="TimeoutError"?oe(t,n.__lunoraRef,p):d};let u;try{try{u=await a(v,{body:JSON.stringify({args:i(),functionPath:n.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:h,method:"POST",signal:N.signal})}catch(E){return m(E)}if(!u.ok){let E;try{E=await u.text()}catch(C){return m(C)}throw ee(t,u.status,E,s.messageId)}let d;try{d=await u.text()}catch(E){return m(E)}if(d.length===0)return;let A;try{A=JSON.parse(d)}catch{throw new w("INTERNAL",`${t}: function dispatch returned a non-JSON body (${String(u.status)}): ${d}`,{status:u.status})}if(A===null||typeof A!="object"||Array.isArray(A)||!("result"in A))throw new w("INTERNAL",`${t}: function dispatch returned a JSON body that is not a { result } envelope (${String(u.status)}): ${d}`,{status:u.status});return y(A.result)}finally{N.dispose()}}},U=(e,t)=>{let o=0;return(a,n,r)=>(o+=1,e(a,n,{...r,dedupId:r?.dedupId??`${t}.${String(o)}`}))},ae=(e,t)=>M(e,t,"step args"),fe=e=>{let t=0;return async(o,a,n)=>{const r=`${e.instanceId}#step${String(t)}`;t+=1;const s=n?.config??o.config,i=n?.name??o.name;if(i.startsWith(S))return T(`@lunora/workflow: ctx.runStep step name "${i}" is reserved — the "${S}" prefix is used by the framework's own steps`,void 0,e.nonRetryableErrorClass);const c=ae(o.args,a),f=async p=>{const N={attempt:p.attempt,config:p.config,env:e.env,log:e.log,run:U(e.run,r),step:p.step};let m;try{m=await o.handler(N,c)}catch(u){return ne(u)?T(u.message,u,e.nonRetryableErrorClass):J(u,e.nonRetryableErrorClass)}if(!o.returns)return m;try{return o.returns.parse(m)}catch(u){const d=u instanceof Error?u.message:String(u);return T(`step "${o.name}" returns validation failed: ${d}`,u,e.nonRetryableErrorClass)}},v=o.rollback,h=v?{rollback:async p=>{await v({args:c,env:e.env,error:p.error,log:e.log,output:p.output,run:U(e.run,`${r}rollback`)})},rollbackConfig:o.rollbackConfig}:void 0;return s===void 0?e.step.do(i,f,h):e.step.do(i,s,f,h)}};export{fe as c,U as p,le as t,ae as v};