@lunora/workflow 1.0.0-alpha.3 → 1.0.0-alpha.31

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 (34) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +24 -1
  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 -32
  6. package/dist/index.d.mts +177 -115
  7. package/dist/index.d.ts +177 -115
  8. package/dist/index.mjs +1 -8
  9. package/dist/packem_shared/MAX_BRANCHES-C05O5LY9.mjs +1 -0
  10. package/dist/packem_shared/NonRetryableError-9ZqDUzwT.mjs +1 -0
  11. package/dist/packem_shared/WorkflowsRestError-HhBsn3PQ.mjs +1 -0
  12. package/dist/packem_shared/branch-marker-CCpWfS5k.mjs +1 -0
  13. package/dist/packem_shared/createRunStep-DtipxEQ4.mjs +1 -0
  14. package/dist/packem_shared/createWaitForEvent-DjWsI895.mjs +1 -0
  15. package/dist/packem_shared/createWorkflowContext-zQR_9N-v.mjs +1 -0
  16. package/dist/packem_shared/createWorkflowRunContext-B3-fz0oh.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/run-step-cJ-miof9.mjs +1 -0
  22. package/dist/packem_shared/types.d-CeA8m4Iq.d.mts +497 -0
  23. package/dist/packem_shared/types.d-CeA8m4Iq.d.ts +497 -0
  24. package/package.json +3 -2
  25. package/dist/packem_shared/NonRetryableError-Dn2dTyBS.mjs +0 -27
  26. package/dist/packem_shared/WorkflowsRestError-b06i7K5j.mjs +0 -118
  27. package/dist/packem_shared/createRunStep-8jOXxP2o.mjs +0 -54
  28. package/dist/packem_shared/createWorkflowContext-D6thzmlF.mjs +0 -14
  29. package/dist/packem_shared/createWorkflowRunContext-DJj_y0fa.mjs +0 -79
  30. package/dist/packem_shared/createWorkflows-BoSYVIXg.mjs +0 -23
  31. package/dist/packem_shared/defineStep-DJQtLw7g.mjs +0 -28
  32. package/dist/packem_shared/defineWorkflow-DbUC-oCN.mjs +0 -15
  33. package/dist/packem_shared/types.d-gNYxuUwu.d.mts +0 -344
  34. package/dist/packem_shared/types.d-gNYxuUwu.d.ts +0 -344
package/dist/index.d.ts CHANGED
@@ -1,6 +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 WorkflowInstanceStatus, f as WorkflowEventLike, g as WorkflowStepLike, h as WorkflowRunContext, i as WorkflowLogger, j as WorkflowRunFunction, k as WorkflowRunStepFunction } from "./packem_shared/types.d-gNYxuUwu.js";
2
- export type { A as ArgsOf, F as FunctionReference, I as InferStepArgs, R as RunFunctionOptions, l as RunStepOptions, m as StepHandler, n as StepRollbackContext, o as StepRollbackHandler, p as StepRunContext, q as WorkflowBindingLike, r as WorkflowCreateOptions, s as WorkflowHandle, t as WorkflowHandler, u as WorkflowInstanceLike, v as WorkflowRollbackContextLike, w as WorkflowRollbackHandlerLike, x as WorkflowStatusResult, y as WorkflowStepConfigLike, z as WorkflowStepContextLike, B as WorkflowStepRollbackOptionsLike } from "./packem_shared/types.d-gNYxuUwu.js";
3
- import '@lunora/values';
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-CeA8m4Iq.js";
2
+ export type { A as ArgsOf, B as BranchCompensationParams, F as FunctionReference, I as InferStepArgs, R as RunFunctionOptions, o as RunStepOptions, p as StepHandler, q as StepRollbackContext, r as StepRollbackHandler, s as StepRunContext, t as WaitForEventOptions, u as WorkflowBindingLike, v as WorkflowBranchOutputs, w as WorkflowCreateOptions, x as WorkflowHandle, y as WorkflowHandler, z as WorkflowInstanceLike, C as WorkflowParallelFunction, D as WorkflowRollbackContextLike, E as WorkflowRollbackHandlerLike, G as WorkflowSpawnFunction, H as WorkflowSpawnOptions, J as WorkflowStatusResult, K as WorkflowStepConfigLike, M as WorkflowStepContextLike, N as WorkflowStepRollbackOptionsLike } from "./packem_shared/types.d-CeA8m4Iq.js";
3
+ import { Validator } from '@lunora/values';
4
+ import { LunoraError } from '@lunora/errors';
4
5
  /** Wiring info for one declared workflow, emitted by codegen into the generated shard. */
5
6
  interface WorkflowBindingSpec {
6
7
  /** The Cloudflare `Workflow` binding name, e.g. `WORKFLOW_ORDER_PIPELINE`. */
@@ -9,108 +10,138 @@ interface WorkflowBindingSpec {
9
10
  exportName: string;
10
11
  }
11
12
  /**
12
- * Build the `ctx.workflows` handle for a request: resolve every spec's
13
- * `env[binding]` into the `exportName → Workflow binding` map and wrap it in
14
- * {@link createWorkflows}. A spec whose binding is absent from `env` is skipped
15
- * here — the helpful "no workflow named …" error is raised lazily by
16
- * `workflows.get(name)` when the missing workflow is actually used.
17
- */
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
+ */
18
19
  declare const createWorkflowContext: (env: Record<string, unknown>, specs: ReadonlyArray<WorkflowBindingSpec>) => Workflows;
19
20
  /**
20
- * Build the `ctx.workflows` handle from a map of `lunora/workflows.ts` export
21
- * name → Cloudflare `Workflow` binding. `get(name)` resolves the typed handle;
22
- * an unknown name throws with the list of declared workflows.
23
- */
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
+ */
24
25
  declare const createWorkflows: (options: LunoraWorkflowsOptions) => Workflows;
25
26
  /**
26
- * Declare a reusable durable step. Same `args` map shape a Lunora `query` /
27
- * `mutation` / `action` uses, so a step reads like a function:
28
- *
29
- * ```ts
30
- * // lunora/steps.ts
31
- * import { defineStep } from "@lunora/workflow";
32
- * import { v } from "@lunora/values";
33
- *
34
- * export const fetchImage = defineStep("fetch image", {
35
- * args: { imageKey: v.string() },
36
- * returns: v.object({ data: v.bytes() }),
37
- * handler: async (ctx, { imageKey }) => {
38
- * const object = await (ctx.env.BUCKET as R2Bucket).get(imageKey);
39
- * return { data: new Uint8Array(await object!.arrayBuffer()) };
40
- * },
41
- * rollback: async (ctx) => {
42
- * await (ctx.env.BUCKET as R2Bucket).delete(`tmp/${ctx.args.imageKey}`);
43
- * },
44
- * });
45
- * ```
46
- *
47
- * Then, inside a `defineWorkflow` handler:
48
- *
49
- * ```ts
50
- * const { data } = await ctx.runStep(fetchImage, { imageKey: ctx.params.imageKey });
51
- * ```
52
- */
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
+ */
53
84
  declare const defineStep: <A extends StepArgsValidator, Result>(name: string, config: StepConfig<A, Result>) => StepDefinition<A, Result>;
54
85
  /** True when a value is a `defineStep` result (the runtime brand check). */
55
86
  declare const isStepDefinition: (value: unknown) => value is StepDefinition;
56
87
  /**
57
- * The generated `WorkflowEntrypoint` class name for a `lunora/workflows.ts`
58
- * export: `orderPipeline` → `OrderPipelineWorkflow`. wrangler's
59
- * `workflows[].class_name` references it, so codegen and the config layer MUST
60
- * derive it identically — always via this helper.
61
- */
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
+ */
62
93
  declare const workflowClassName: (exportName: string) => string;
63
94
  /**
64
- * The wrangler binding name for a workflow export: `orderPipeline` →
65
- * `WORKFLOW_ORDER_PIPELINE`, `etl` → `WORKFLOW_ETL`. The `WORKFLOW_` prefix
66
- * namespaces these away from `SHARD`/`SESSION`/`SCHEDULER`/`CONTAINER_*` so a
67
- * workflow export can never collide with the built-in bindings.
68
- */
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
+ */
69
100
  declare const workflowBindingName: (exportName: string) => string;
70
101
  /**
71
- * The stable workflow name wrangler registers (`workflows[].name`):
72
- * `orderPipeline` → `order-pipeline`. Used as the deployed workflow's
73
- * identifier when no explicit `name` override is given.
74
- */
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
+ */
75
106
  declare const workflowDefaultName: (exportName: string) => string;
76
107
  /**
77
- * Declare a durable workflow deployed alongside the app. Pure validation +
78
- * branding: codegen discovers the export, emits the `WorkflowEntrypoint`
79
- * subclass (`_generated/workflows.ts`), and wires the typed `ctx.workflows`
80
- * handle; the config layer reconciles the wrangler `workflows[]` entry from the
81
- * same definition.
82
- *
83
- * ```ts
84
- * // lunora/workflows.ts
85
- * import { defineWorkflow } from "@lunora/workflow";
86
- * import { api } from "./_generated/api";
87
- *
88
- * export const orderPipeline = defineWorkflow&lt;{ orderId: string }>({
89
- * handler: async (ctx) => {
90
- * const order = await ctx.step.do("load", () => ctx.run(api.orders.get, { id: ctx.params.orderId }));
91
- * await ctx.step.sleep("cool-off", "1 minute");
92
- * await ctx.step.do("charge", () => ctx.run(api.payments.charge, { orderId: ctx.params.orderId }));
93
- * return order;
94
- * },
95
- * });
96
- * ```
97
- */
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
+ * await ctx.step.do("charge", () => ctx.run(api.payments.charge, { orderId: ctx.params.orderId }));
124
+ * return order;
125
+ * },
126
+ * });
127
+ * ```
128
+ */
98
129
  declare const defineWorkflow: <Params = Record<string, unknown>, Output = unknown>(config: WorkflowConfig<Params, Output>) => WorkflowDefinition<Params, Output>;
99
130
  /** True when a value is a `defineWorkflow` result (the runtime brand check). */
100
131
  declare const isWorkflowDefinition: (value: unknown) => value is WorkflowDefinition;
101
132
  /**
102
- * Throw from a workflow step (or handler) to fail the instance immediately
103
- * **without** retrying — the portable mirror of `cloudflare:workflows`'
104
- * `NonRetryableError`. Importable from Node, so workflow code stays unit-testable.
105
- *
106
- * ```ts
107
- * import { NonRetryableError } from "@lunora/workflow";
108
- *
109
- * if (order.status === "cancelled") {
110
- * throw new NonRetryableError("order already cancelled — no point retrying");
111
- * }
112
- * ```
113
- */
133
+ * Throw from a workflow step (or handler) to fail the instance immediately
134
+ * **without** retrying — the portable mirror of `cloudflare:workflows`'
135
+ * `NonRetryableError`. Importable from Node, so workflow code stays unit-testable.
136
+ *
137
+ * ```ts
138
+ * import { NonRetryableError } from "@lunora/workflow";
139
+ *
140
+ * if (order.status === "cancelled") {
141
+ * throw new NonRetryableError("order already cancelled — no point retrying");
142
+ * }
143
+ * ```
144
+ */
114
145
  declare class NonRetryableError extends Error {
115
146
  constructor(message: string, name?: string);
116
147
  }
@@ -119,18 +150,31 @@ declare const isNonRetryableError: (value: unknown) => value is NonRetryableErro
119
150
  /** Constructor shape of `cloudflare:workflows`' native `NonRetryableError`. */
120
151
  type NativeNonRetryableErrorConstructor = new (message: string, name?: string) => Error;
121
152
  /**
122
- * Rebuild a portable {@link NonRetryableError} as the native Cloudflare one,
123
- * preserving its `name`, `message`, `cause`, and `stack`. Used at the `src/do`
124
- * boundary where the native constructor is available; everywhere else the
125
- * portable error is thrown unchanged (and still honored by name).
126
- */
153
+ * Rebuild a portable {@link NonRetryableError} as the native Cloudflare one,
154
+ * preserving its `name`, `message`, `cause`, and `stack`. Used at the `src/do`
155
+ * boundary where the native constructor is available; everywhere else the
156
+ * portable error is thrown unchanged (and still honored by name).
157
+ */
127
158
  declare const toNativeNonRetryableError: (error: NonRetryableError, NativeNonRetryableError: NativeNonRetryableErrorConstructor) => Error;
128
159
  /**
129
- * If `error` is a portable {@link NonRetryableError} and a native constructor is
130
- * available, rethrow it as the native error; otherwise rethrow `error` as-is.
131
- * Always throws — the `never` return lets callers `return convertNonRetryableError(...)`.
132
- */
160
+ * If `error` is a portable {@link NonRetryableError} and a native constructor is
161
+ * available, rethrow it as the native error; otherwise rethrow `error` as-is.
162
+ * Always throws — the `never` return lets callers `return convertNonRetryableError(...)`.
163
+ */
133
164
  declare const convertNonRetryableError: (error: unknown, NativeNonRetryableError: NativeNonRetryableErrorConstructor | undefined) => never;
165
+ /** Hard cap on branches per `ctx.parallel` call — auto-scale, never silently spawn unbounded DOs. */
166
+ declare const MAX_BRANCHES = 100;
167
+ /**
168
+ * Build a single fan-out branch: a declared child workflow referenced by its
169
+ * `lunora/workflows.ts` export name, plus the params it is created with. Pass the
170
+ * output type as the generic argument so `ctx.parallel(...)` infers the result
171
+ * tuple — e.g. `branch("imageTag", { key })` typed as `branch` of `{ tags }`.
172
+ */
173
+ declare const branch: <Output = unknown>(workflow: string, params?: Record<string, unknown>, options?: {
174
+ compensateWith?: string;
175
+ id?: string;
176
+ timeout?: number | string;
177
+ }) => WorkflowBranch<Output>;
134
178
  /** The lifecycle mutations the REST API exposes via `PATCH .../instances/{id}`. */
135
179
  type WorkflowInstanceAction = "pause" | "resume" | "terminate";
136
180
  /** Configuration for a {@link WorkflowsRestClient}. */
@@ -178,8 +222,7 @@ interface WorkflowInstancePage {
178
222
  totalCount?: number;
179
223
  }
180
224
  /** Thrown when the REST API responds non-2xx or `success: false`; carries the status plus body for the caller to surface. */
181
- declare class WorkflowsRestError extends Error {
182
- readonly status: number;
225
+ declare class WorkflowsRestError extends LunoraError {
183
226
  constructor(status: number, body: string);
184
227
  }
185
228
  /** The observe client: list instances, read one instance's steps, and (with Edit scope) mutate its status. */
@@ -203,11 +246,11 @@ interface WorkflowsRestClient {
203
246
  }>;
204
247
  }
205
248
  /**
206
- * Build a {@link WorkflowsRestClient}. Each call hits the account-scoped REST
207
- * endpoint with the bearer token, unwraps Cloudflare's
208
- * `{ success, errors, result, result_info }` envelope, and normalizes the
209
- * snake_case payload into the camelCase shapes the studio renders.
210
- */
249
+ * Build a {@link WorkflowsRestClient}. Each call hits the account-scoped REST
250
+ * endpoint with the bearer token, unwraps Cloudflare's
251
+ * `{ success, errors, result, result_info }` envelope, and normalizes the
252
+ * snake_case payload into the camelCase shapes the studio renders.
253
+ */
211
254
  declare const createWorkflowsRestClient: (config: WorkflowsRestConfig) => WorkflowsRestClient;
212
255
  interface RunContextOptions<Params> {
213
256
  env: Record<string, unknown>;
@@ -221,12 +264,12 @@ interface RunContextOptions<Params> {
221
264
  /** Assemble the {@link WorkflowRunContext} passed to a `defineWorkflow` handler. */
222
265
  declare const createWorkflowRunContext: <Params = Record<string, unknown>>(options: RunContextOptions<Params>) => WorkflowRunContext<Params>;
223
266
  /**
224
- * Validate a step's args through its validator map, prefixing any
225
- * `ValidationError` with `step args.&lt;key>` so the failure points at the
226
- * offending field. Delegates to `@lunora/values`' shared {@link parseValidatorMap}
227
- * — the same parser the procedure builder and HTTP routes use — so the
228
- * optional-skip and error-prefix semantics stay in lockstep across the framework.
229
- */
267
+ * Validate a step's args through its validator map, prefixing any
268
+ * `ValidationError` with `step args.<key>` so the failure points at the
269
+ * offending field. Delegates to `@lunora/values`' shared {@link parseValidatorMap}
270
+ * — the same parser the procedure builder and HTTP routes use — so the
271
+ * optional-skip and error-prefix semantics stay in lockstep across the framework.
272
+ */
230
273
  declare const validateStepArgs: (validators: StepArgsValidator, source: Record<string, unknown>) => Record<string, unknown>;
231
274
  /** Dependencies needed to run a step: the native step API plus the workflow's env / runner / logger. */
232
275
  interface RunStepDeps {
@@ -242,10 +285,29 @@ interface RunStepDeps {
242
285
  step: WorkflowStepLike;
243
286
  }
244
287
  /**
245
- * Build the `ctx.runStep` function bound to one workflow invocation. Each call
246
- * runs the step through `step.do(...)`: validate args → run body → validate
247
- * result (when `returns` is declared), with any portable `NonRetryableError`
248
- * converted to the native one and any declared rollback forwarded to Cloudflare.
249
- */
288
+ * Build the `ctx.runStep` function bound to one workflow invocation. Each call
289
+ * runs the step through `step.do(...)`: validate args → run body → validate
290
+ * result (when `returns` is declared), with any portable `NonRetryableError`
291
+ * converted to the native one and any declared rollback forwarded to Cloudflare.
292
+ */
250
293
  declare const createRunStep: (deps: RunStepDeps) => WorkflowRunStepFunction;
251
- export { type LunoraWorkflowsOptions, type NativeNonRetryableErrorConstructor, NonRetryableError, type StepArgsValidator, type StepConfig, type StepDefinition, type WorkflowBindingSpec, 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, convertNonRetryableError, createRunStep, createWorkflowContext, createWorkflowRunContext, createWorkflows, createWorkflowsRestClient, defineStep, defineWorkflow, isNonRetryableError, isStepDefinition, isWorkflowDefinition, toNativeNonRetryableError, validateStepArgs, workflowBindingName, workflowClassName, workflowDefaultName };
294
+ /** Dependencies one workflow invocation's `ctx.waitForEvent` closes over. */
295
+ interface WaitForEventDeps {
296
+ /** Native `cloudflare:workflows` `NonRetryableError` constructor — injected by `src/do`; absent in Node tests. */
297
+ nonRetryableErrorClass?: NativeNonRetryableErrorConstructor;
298
+ /** The native Cloudflare durable-step API. */
299
+ step: WorkflowStepLike;
300
+ }
301
+ /**
302
+ * Build `ctx.waitForEvent` for one workflow invocation.
303
+ *
304
+ * Every failure here is **non-retryable**. A malformed definition or a reserved
305
+ * step name is a deterministic programmer error, and a payload that fails the
306
+ * validator has already consumed the event — replaying the wait cannot produce a
307
+ * different value, it can only hibernate the instance until its timeout. Each is
308
+ * raised through the shared {@link raiseNonRetryable}, the same classification path
309
+ * `ctx.runStep` uses, so the native error reaches Cloudflare and the instance fails
310
+ * fast.
311
+ */
312
+ declare const createWaitForEvent: (deps: WaitForEventDeps) => WorkflowWaitForEventFunction;
313
+ 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, isNonRetryableError, isStepDefinition, isWorkflowDefinition, isWorkflowEventDefinition, toNativeNonRetryableError, validateStepArgs, workflowBindingName, workflowClassName, workflowDefaultName };
package/dist/index.mjs CHANGED
@@ -1,8 +1 @@
1
- export { createWorkflowContext } from './packem_shared/createWorkflowContext-D6thzmlF.mjs';
2
- export { default as createWorkflows } from './packem_shared/createWorkflows-BoSYVIXg.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 { WorkflowsRestError, createWorkflowsRestClient } from './packem_shared/WorkflowsRestError-b06i7K5j.mjs';
7
- export { createWorkflowRunContext } from './packem_shared/createWorkflowRunContext-DJj_y0fa.mjs';
8
- 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 m,isWorkflowDefinition as x,workflowBindingName as k,workflowClassName as W,workflowDefaultName as c}from"./packem_shared/defineWorkflow-tKaIifbZ.mjs";import{NonRetryableError as N,convertNonRetryableError as R,isNonRetryableError as v,toNativeNonRetryableError as d}from"./packem_shared/NonRetryableError-9ZqDUzwT.mjs";import{MAX_BRANCHES as C,branch as S}from"./packem_shared/MAX_BRANCHES-C05O5LY9.mjs";import{WorkflowsRestError as y,createWorkflowsRestClient as D}from"./packem_shared/WorkflowsRestError-HhBsn3PQ.mjs";import{createWorkflowRunContext as g}from"./packem_shared/createWorkflowRunContext-B3-fz0oh.mjs";import{c as h,v as F}from"./packem_shared/run-step-cJ-miof9.mjs";import{createWaitForEvent as M}from"./packem_shared/createWaitForEvent-DjWsI895.mjs";export{C as MAX_BRANCHES,N as NonRetryableError,y as WorkflowsRestError,S as branch,R as convertNonRetryableError,h as createRunStep,M as createWaitForEvent,e as createWorkflowContext,g as createWorkflowRunContext,f as createWorkflows,D as createWorkflowsRestClient,p as defineStep,m as defineWorkflow,a as defineWorkflowEvent,v as isNonRetryableError,s as isStepDefinition,x as isWorkflowDefinition,i as isWorkflowEventDefinition,d as toNativeNonRetryableError,F as validateStepArgs,k as workflowBindingName,W as workflowClassName,c as workflowDefaultName};
@@ -0,0 +1 @@
1
+ import{LunoraError as E}from"@lunora/errors";import{h as y,B as I,a as p}from"./branch-marker-CCpWfS5k.mjs";import{RESERVED_EVENT_TYPE_PREFIX as v}from"./defineWorkflowEvent-suERPEEV.mjs";import{NonRetryableError as d}from"./NonRetryableError-9ZqDUzwT.mjs";const h=100,g="lunora:spawn:",$="lunora:await:",x="lunora:signal:",B="lunora:compensate:",m=`${v}branch:`,b=(t,r,n)=>({compensateWith:n?.compensateWith,id:n?.id,params:r,timeout:n?.timeout,workflow:t}),w=t=>t instanceof Error?{message:t.message,name:t.name}:{message:String(t),name:"Error"},A=t=>({status:"ok",value:t}),N=t=>({error:w(t),status:"error"}),f=async(t,r,n)=>{for(let a=r.length-1;a>=0;a-=1){const o=r[a],c=o?.plan.item.compensateWith;if(!(o===void 0||c===void 0))try{const s=t.resolveBinding(c);await t.step.do(`${B}${o.plan.childId}`,async()=>{const e=`${o.plan.childId}:compensate`,i={branch:o.plan.item.workflow,error:n,index:o.plan.index,output:o.output};return await s.create({id:e,params:i}),e})}catch(s){t.log?.error(`ctx.parallel: group-saga compensation "${c}" for branch "${o.plan.item.workflow}" (#${String(o.plan.index)}) failed`,s)}}},k=t=>async n=>{if(n.length===0)return[];if(n.length>h)throw new d(`ctx.parallel: ${String(n.length)} branches exceeds the cap of ${String(h)} — split the fan-out or raise the work into fewer child workflows`);const a=n.map((e,i)=>{const l=t.nextChildId(e.id);return{childId:l,eventType:`${m}${l}`,index:i,item:e}}),o=new Set;for(const e of a){if(o.has(e.childId))throw new d(`ctx.parallel: duplicate branch id "${e.childId}" — each branch in a group must resolve to a unique child instance id (check explicit \`id\` options)`);o.add(e.childId)}await Promise.all(a.map(e=>t.step.do(`${g}${e.childId}`,async()=>{const i=t.resolveBinding(e.item.workflow),l={eventType:e.eventType,index:e.index,parentBinding:t.parentBinding,parentId:t.instanceId};return await i.create({id:e.childId,params:{...e.item.params,[p]:l}}),e.childId})));const c=[],s=[];for(const e of a){let i;try{i=(await t.step.waitForEvent(`${$}${e.childId}`,{timeout:e.item.timeout,type:e.eventType})).payload}catch(l){const u=w(l);throw await f(t,s,u),new d(`ctx.parallel: branch "${e.item.workflow}" (#${String(e.index)}) join failed: ${u.message}`)}if(i.status==="error")throw await f(t,s,i.error),new d(`ctx.parallel: branch "${e.item.workflow}" (#${String(e.index)}) failed: ${i.error.message}`);s.push({output:i.value,plan:e}),c.push(i.value)}return c},W=t=>async(r,n,a)=>{if(y(n))throw new E("BAD_REQUEST",`@lunora/workflow: params ${I}`);const o=t.nextChildId(a?.id);return await t.step.do(`${g}${o}`,async()=>(await t.resolveBinding(r).create({id:o,params:n}),o)),t.resolveBinding(r).get(o)},C=t=>{if(typeof t!="object"||t===null)return;const r=t[p];if(typeof r!="object"||r===null)return;const n=r;if(!(typeof n.eventType!="string"||typeof n.parentBinding!="string"||typeof n.parentId!="string"||typeof n.index!="number")&&!(!n.parentBinding.startsWith("WORKFLOW_")||!n.eventType.startsWith(m)))return{eventType:n.eventType,index:n.index,parentBinding:n.parentBinding,parentId:n.parentId}},F=t=>{if(typeof t!="object"||t===null)return t;const r={...t};return Reflect.deleteProperty(r,p),r},T=async(t,r,n)=>{const a=t.env[r.parentBinding];if(!a||typeof a.get!="function")return;const o=a.get.bind(a);await t.step.do(`${x}${String(r.index)}`,async()=>(await(await o(r.parentId)).sendEvent({payload:n,type:r.eventType}),r.eventType))},M=async(t,r,n)=>{try{await T(t,r,n)}catch(a){t.log?.error(`@lunora/workflow: failed to signal branch parent "${r.parentId}" (event "${r.eventType}")`,a)}};export{h as MAX_BRANCHES,b as branch,k as createParallel,W as createSpawn,N as errorOutcome,C as extractBranchMarker,A as okOutcome,T as signalBranchParent,M as signalBranchParentSafe,F as stripBranchMarker};
@@ -0,0 +1 @@
1
+ const s="__lunoraNonRetryable";class a extends Error{constructor(e,n="NonRetryableError"){super(e),this.name=n,this[s]=!0}}const c=t=>t instanceof Error&&t[s]===!0,r=(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&&c(t)?r(t,e):t},u=(t,e,n)=>{const o=new a(t);return e!==void 0&&(o.cause=e),i(o,n)};export{a as NonRetryableError,i as convertNonRetryableError,c as isNonRetryableError,u as raiseNonRetryable,r as toNativeNonRetryableError};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";const R="https://api.cloudflare.com/client/v4/accounts",$={complete:!0,errored:!0,paused:!0,queued:!0,running:!0,terminated:!0,unknown:!0,waiting:!0,waitingForPause:!0},g=t=>typeof t=="string"&&Object.hasOwn($,t)?t:"unknown",u=t=>typeof t=="string"&&t!==""?t:void 0,S=(t,a)=>typeof t=="string"?t:a,A=t=>typeof t=="boolean"?t:void 0,_=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:S(t.id,""),startedOn:u(t.started_on),status:g(t.status)}),I=t=>({attempts:_(t.attempts),end:u(t.end),error:t.error,name:S(t.name,""),output:t.output,start:u(t.start),success:A(t.success),type:u(t.type)});class l extends h{constructor(a,i){super("WORKFLOWS_REST_ERROR",`Cloudflare Workflows REST API returned ${String(a)}: ${i}`,{name:"WorkflowsRestError",status:a})}}const w=t=>{const a=t.fetch??globalThis.fetch.bind(globalThis),i=`${R}/${t.accountId}/workflows`,p=async(o,r)=>{const s=await a(`${i}${o}`,{...r,headers:{Authorization:`Bearer ${t.apiToken}`,"Content-Type":"application/json"}}),e=await s.text();let n;try{n=JSON.parse(e)}catch{throw new l(s.status,e)}if(!s.ok||n.success===!1)throw new l(s.status,e);return n};return{getInstance:async({instanceId:o,workflowName:r})=>{const e=(await p(`/${encodeURIComponent(r)}/instances/${encodeURIComponent(o)}`)).result??{},n=Array.isArray(e.steps)?e.steps:[];return{...f(e),error:e.error,output:e.output,params:e.params,steps:n.map(d=>I(d))}},listInstances:async({page:o,perPage:r,status:s,workflowName:e})=>{const n=new URLSearchParams;s!==void 0&&n.set("status",s),o!==void 0&&n.set("page",String(o)),r!==void 0&&n.set("per_page",String(r));const d=n.toString()===""?"":`?${n.toString()}`,y=await p(`/${encodeURIComponent(e)}/instances${d}`),m=Array.isArray(y.result)?y.result:[],c=y.result_info??{};return{instances:m.map(b=>f(b)),page:typeof c.page=="number"?c.page:o??1,perPage:typeof c.per_page=="number"?c.per_page:r??m.length,totalCount:typeof c.total_count=="number"?c.total_count:void 0}},setInstanceStatus:async({action:o,instanceId:r,workflowName:s})=>{const n=(await p(`/${encodeURIComponent(s)}/instances/${encodeURIComponent(r)}`,{body:JSON.stringify({status:o}),method:"PATCH"})).result??{};return{status:g(n.status)}}}};export{l as WorkflowsRestError,w 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-cJ-miof9.mjs";import"./defineWorkflowEvent-suERPEEV.mjs";import"./NonRetryableError-9ZqDUzwT.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-9ZqDUzwT.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{F as w,c as v}from"./run-step-cJ-miof9.mjs";import{LunoraError as i}from"@lunora/errors";import{workflowBindingName as s}from"./defineWorkflow-tKaIifbZ.mjs";import{createSpawn as u,createParallel as m}from"./MAX_BRANCHES-C05O5LY9.mjs";import{createWaitForEvent as p}from"./createWaitForEvent-DjWsI895.mjs";const g=e=>({debug:(r,...n)=>{console.debug(e,r,...n)},error:(r,...n)=>{console.error(e,r,...n)},info:(r,...n)=>{console.info(e,r,...n)},warn:(r,...n)=>{console.warn(e,r,...n)}}),I=e=>{const r=g(`[workflow:${e.exportName}]`),n=w({env:e.env,fetchImpl:e.fetchImpl,label:"@lunora/workflow"}),f=t=>{const a=s(t),o=e.env[a];if(!o||typeof o.create!="function"||typeof o.get!="function")throw new i("INTERNAL",`@lunora/workflow: cannot spawn child workflow "${t}" — no Workflow binding "${a}" on env (is it declared in lunora/workflows.ts?)`);return o};let l=0;const d=t=>{if(t!==void 0)return t;const a=`${e.event.instanceId}-c${String(l)}`;return l+=1,a},c={env:e.env,instanceId:e.event.instanceId,log:r,nextChildId:d,parentBinding:s(e.exportName),resolveBinding:f,step:e.step};return{env:e.env,event:e.event,log:r,parallel:m(c),params:e.event.payload,run:n,runStep:v({env:e.env,log:r,nonRetryableErrorClass:e.nonRetryableErrorClass,run:n,step:e.step}),spawn:u(c),step:e.step,waitForEvent:p({nonRetryableErrorClass:e.nonRetryableErrorClass,step:e.step})}};export{I 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
+ import{LunoraError as y,isLunoraError as S}from"@lunora/errors";import{parseValidatorMap as T}from"@lunora/values";import{RESERVED_EVENT_TYPE_PREFIX as N}from"./defineWorkflowEvent-suERPEEV.mjs";import{raiseNonRetryable as b,convertNonRetryableError as O}from"./NonRetryableError-9ZqDUzwT.mjs";const A=(t,r,e)=>{if(r===void 0)return{dispose:()=>{},signal:t};const a=new AbortController,o=setTimeout(()=>{a.abort(e())},r);return{dispose:()=>{clearTimeout(o)},signal:a.signal}},_=t=>{let r="";for(let e=0;e<t.length;e+=32768)r+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(r)},v=t=>_(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");new TextDecoder;const R=new TextEncoder,w="=",L=t=>{for(let r=0;r<t.length;r+=1)if(t.charCodeAt(r)>255)return!1;return!0},k=t=>v(R.encode(JSON.stringify(t))),x=t=>!t.startsWith(w)&&L(t)?t:`${w}${v(R.encode(t))}`,C="/_lunora/scheduler/dispatch",D=3e4,P=t=>{let r=t.length;for(;r>0&&t[r-1]==="/";)r-=1;return t.slice(0,r)},$=Symbol("lunoraDispatchFailure"),U=Symbol("lunoraDispatchMessageId"),E=(t,r)=>(Object.defineProperty(t,$,{value:!0}),r!==void 0&&Object.defineProperty(t,U,{value:r}),t),M=(t,r,e,a)=>{try{const o=JSON.parse(e)?.error;if(typeof o=="object"&&o!==null&&typeof o.code=="string"){const{code:u,data:i,message:c}=o;return E(new y(u,typeof c=="string"?c:void 0,{data:i,status:r}),a)}}catch{}return E(new y("INTERNAL",`${t}: function dispatch failed (${String(r)}): ${e}`,{status:r}),a)},J=new Set([400,403,404,422]),j=t=>S(t)&&t[$]===!0&&J.has(t.status),K=(t,r,e)=>new y("INTERNAL",`${t}: function dispatch to "${r}" timed out after ${String(e)}ms`,{status:503}),z=t=>{const{label:r}=t,e=globalThis.fetch,a=t.fetchImpl??(typeof e=="function"?e.bind(globalThis):void 0);return async(o,u,i={})=>{if(typeof a!="function")throw new TypeError(`${r}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const c=t.env.LUNORA_ORIGIN_URL;if(typeof c!="string"||c.length===0)throw new y("INTERNAL",`${r}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const d=t.env.LUNORA_ADMIN_TOKEN;if(typeof d!="string"||d.length===0)throw new y("INTERNAL",`${r}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const p=`${P(c)}${C}`,s={authorization:`Bearer ${d}`,"content-type":"application/json"};t.identity?.userId!==void 0&&(s["x-lunora-userid"]=x(t.identity.userId)),t.identity?.claims!==void 0&&(s["x-lunora-identity"]=k(t.identity.claims));const m=i.timeoutMs??D,h=A(void 0,m,()=>new DOMException(`dispatch timed out after ${String(m)}ms`,"TimeoutError")),n=f=>{throw f instanceof Error&&f.name==="TimeoutError"?K(r,o.__lunoraRef,m):f};let l;try{try{l=await a(p,{body:JSON.stringify({args:u??{},functionPath:o.__lunoraRef,id:i.dedupId,shardKey:i.shardKey}),headers:s,method:"POST",signal:h.signal})}catch(g){return n(g)}if(!l.ok){let g;try{g=await l.text()}catch(I){return n(I)}throw M(r,l.status,g,i.messageId)}let f;try{f=await l.text()}catch(g){return n(g)}if(f.length===0)return;try{return JSON.parse(f)}catch{throw new y("INTERNAL",`${r}: function dispatch returned a non-JSON body (${String(l.status)}): ${f}`,{status:l.status})}}finally{h.dispose()}}},W=(t,r)=>T(t,r,"step args"),B=t=>async(r,e,a)=>{const o=a?.config??r.config,u=a?.name??r.name;if(u.startsWith(N))return b(`@lunora/workflow: ctx.runStep step name "${u}" is reserved — the "${N}" prefix is used by the framework's own steps`,void 0,t.nonRetryableErrorClass);const i=W(r.args,e),c=async s=>{const m={attempt:s.attempt,config:s.config,env:t.env,log:t.log,run:t.run,step:s.step};let h;try{h=await r.handler(m,i)}catch(n){return j(n)?b(n.message,n,t.nonRetryableErrorClass):O(n,t.nonRetryableErrorClass)}if(!r.returns)return h;try{return r.returns.parse(h)}catch(n){const l=n instanceof Error?n.message:String(n);return b(`step "${r.name}" returns validation failed: ${l}`,n,t.nonRetryableErrorClass)}},d=r.rollback,p=d?{rollback:async s=>{await d({args:i,env:t.env,error:s.error,log:t.log,output:s.output,run:t.run})},rollbackConfig:r.rollbackConfig}:void 0;return o===void 0?t.step.do(u,c,p):t.step.do(u,o,c,p)};export{z as F,B as c,W as v};