@temporal-contract/worker 2.3.1 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { _ as ClientInferOutput, a as ChildWorkflowError, c as QueryOutputValidationError, d as UpdateOutputValidationError, f as WorkflowCancelledError, g as ClientInferInput, h as WorkflowScopeError, i as ChildWorkflowCancelledError, l as SignalInputValidationError, m as WorkflowOutputValidationError, n as ActivityInputValidationError, o as ChildWorkflowNotFoundError, p as WorkflowInputValidationError, r as ActivityOutputValidationError, s as QueryInputValidationError, u as UpdateInputValidationError, v as WorkerInferInput, y as WorkerInferOutput } from "./errors-BP48RaOI.mjs";
1
+ import { _ as ClientInferInput, a as ChildWorkflowError, b as WorkerInferOutput, c as QueryOutputValidationError, d as UpdateOutputValidationError, f as ValidationError, g as WorkflowScopeError, h as WorkflowOutputValidationError, i as ChildWorkflowCancelledError, l as SignalInputValidationError, m as WorkflowInputValidationError, n as ActivityInputValidationError, o as ChildWorkflowNotFoundError, p as WorkflowCancelledError, r as ActivityOutputValidationError, s as QueryInputValidationError, u as UpdateInputValidationError, v as ClientInferOutput, y as WorkerInferInput } from "./errors-CE56feY1.mjs";
2
2
  import { ActivityDefinition, AnyWorkflowDefinition, ContractDefinition, QueryDefinition, QueryNamesOf, SignalDefinition, SignalNamesOf, UpdateDefinition, UpdateNamesOf } from "@temporal-contract/contract";
3
3
  import { ActivityOptions, ChildWorkflowOptions, ContinueAsNewOptions, WorkflowInfo } from "@temporalio/workflow";
4
4
  import { ResultAsync } from "neverthrow";
@@ -106,12 +106,16 @@ type WorkflowInferWorkflowContextActivities<TContract extends ContractDefinition
106
106
  * },
107
107
  * // Optional: override `activityOptions` for specific activities. Each
108
108
  * // entry shallow-merges over the workflow default — the override wins on
109
- * // every property it specifies, including the whole `retry` block.
109
+ * // every property it specifies, including the whole `retry` block. The
110
+ * // override is Temporal's full `ActivityOptions`, so `taskQueue` works too,
111
+ * // letting you route individual activities to a dedicated worker pool.
110
112
  * activityOptionsByName: {
111
113
  * chargePayment: {
112
114
  * startToCloseTimeout: '5 minutes',
113
115
  * retry: { maximumAttempts: 5 },
114
116
  * },
117
+ * // Route this activity to a dedicated, concurrency-capped queue.
118
+ * scoreRisk: { taskQueue: 'ml-inference' },
115
119
  * },
116
120
  * implementation: async (context, args) => {
117
121
  * // context.activities: typed activities (workflow + global)
@@ -200,10 +204,17 @@ type DeclareWorkflowOptions<TContract extends ContractDefinition, TWorkflowName
200
204
  * entire nested `retry` block when present, matching Temporal's
201
205
  * single-options-per-`proxyActivities`-call semantics).
202
206
  *
207
+ * The override value is Temporal's full `ActivityOptions`, so any field is
208
+ * fair game — including `taskQueue`, which lets you route individual
209
+ * activities to dedicated worker pools (e.g. concurrency-capped queues for
210
+ * LLM calls) while the rest of the workflow's activities stay on the default
211
+ * queue. This keeps the Zod-validated typed-activities boundary intact, where
212
+ * a raw `proxyActivities({ taskQueue })` would forfeit it.
213
+ *
203
214
  * Activity names are typed against the contract; typos surface as TypeScript
204
215
  * errors rather than running silently with the default options.
205
216
  *
206
- * @example
217
+ * @example Tune timeouts and retries per activity
207
218
  * ```ts
208
219
  * activityOptions: { startToCloseTimeout: '1 minute' }, // default
209
220
  * activityOptionsByName: {
@@ -214,6 +225,16 @@ type DeclareWorkflowOptions<TContract extends ContractDefinition, TWorkflowName
214
225
  * fastValidation: { startToCloseTimeout: '5 seconds' },
215
226
  * },
216
227
  * ```
228
+ *
229
+ * @example Route specific activities to a dedicated task queue
230
+ * ```ts
231
+ * activityOptions: { startToCloseTimeout: '10 minutes' }, // default queue
232
+ * activityOptionsByName: {
233
+ * // LLM call → dedicated, concurrency-capped queue.
234
+ * extractLayoutChunk: { taskQueue: 'gemini-pro' },
235
+ * // finalizeLayout, extractImages, … fall through to the default queue.
236
+ * },
237
+ * ```
217
238
  */
218
239
  activityOptionsByName?: Partial<Record<ActivityNamesFor<TContract, TWorkflowName>, ActivityOptions>>;
219
240
  };
@@ -432,5 +453,5 @@ type WorkflowContext<TContract extends ContractDefinition, TWorkflowName extends
432
453
  };
433
454
  }; //# sourceMappingURL=workflow.d.ts.map
434
455
  //#endregion
435
- export { ActivityInputValidationError, ActivityOutputValidationError, ChildWorkflowCancelledError, ChildWorkflowError, ChildWorkflowNotFoundError, QueryInputValidationError, QueryOutputValidationError, SignalInputValidationError, UpdateInputValidationError, UpdateOutputValidationError, WorkflowCancelledError, WorkflowInputValidationError, WorkflowOutputValidationError, WorkflowScopeError, declareWorkflow };
456
+ export { ActivityInputValidationError, ActivityOutputValidationError, ChildWorkflowCancelledError, ChildWorkflowError, ChildWorkflowNotFoundError, QueryInputValidationError, QueryOutputValidationError, SignalInputValidationError, UpdateInputValidationError, UpdateOutputValidationError, ValidationError, WorkflowCancelledError, WorkflowInputValidationError, WorkflowOutputValidationError, WorkflowScopeError, declareWorkflow };
436
457
  //# sourceMappingURL=workflow.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"workflow.d.mts","names":[],"sources":["../src/handlers.ts","../src/internal.ts","../src/child-workflow.ts","../src/activities-proxy.ts","../src/workflow.ts"],"mappings":";;;;;;;;;;;;;KAkCY,2BAAA,iBAA4C,gBAAA,KACtD,IAAA,EAAM,gBAAA,CAAiB,OAAA,aACb,OAAA;;;;;;;KAQA,0BAAA,gBAA0C,eAAA,KACpD,IAAA,EAAM,gBAAA,CAAiB,MAAA,MACpB,iBAAA,CAAkB,MAAA;;;;;;;KAQX,2BAAA,iBAA4C,gBAAA,KACtD,IAAA,EAAM,gBAAA,CAAiB,OAAA,MACpB,OAAA,CAAQ,iBAAA,CAAkB,OAAA;;;;;;;;KCsFnB,yBAAA,GAA4B,IAAI,CAAC,oBAAA;;;;;;;;KChHjC,yBAAA,wBACa,kBAAA,mCACU,cAAA,0BAC/B,IAAA,CAAK,oBAAA;EACP,IAAA,EAAM,gBAAA,CAAiB,cAAA,cAA4B,kBAAA;AAAA;;;;KAMzC,wBAAA,mBAA2C,qBAAA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;;;;;;;;;;;AA8CsD;AAAA;;;;;;;;;EAmSpE,aAAA;IApRM,8EAuRF,IAAA,EAAM,gBAAA,CAAiB,SAAA,cAAuB,aAAA,IAC9C,OAAA,GAAU,yBAAA,GACT,OAAA,SAxR+C;IAAA,wBA2RzB,kBAAA,mCACU,cAAA,wBAEjC,QAAA,EAAU,cAAA,EACV,YAAA,EAAc,kBAAA,EACd,IAAA,EAAM,gBAAA,CAAiB,cAAA,cAA4B,kBAAA,IACnD,OAAA,GAAU,yBAAA,GACT,OAAA;EAAA;AAAA"}
1
+ {"version":3,"file":"workflow.d.mts","names":[],"sources":["../src/handlers.ts","../src/internal.ts","../src/child-workflow.ts","../src/activities-proxy.ts","../src/workflow.ts"],"mappings":";;;;;;;;;;;;;KAkCY,2BAAA,iBAA4C,gBAAA,KACtD,IAAA,EAAM,gBAAA,CAAiB,OAAA,aACb,OAAA;;;;;;;KAQA,0BAAA,gBAA0C,eAAA,KACpD,IAAA,EAAM,gBAAA,CAAiB,MAAA,MACpB,iBAAA,CAAkB,MAAA;;;;;;;KAQX,2BAAA,iBAA4C,gBAAA,KACtD,IAAA,EAAM,gBAAA,CAAiB,OAAA,MACpB,OAAA,CAAQ,iBAAA,CAAkB,OAAA;;;;;;;;KCsFnB,yBAAA,GAA4B,IAAI,CAAC,oBAAA;;;;;;;;KChHjC,yBAAA,wBACa,kBAAA,mCACU,cAAA,0BAC/B,IAAA,CAAK,oBAAA;EACP,IAAA,EAAM,gBAAA,CAAiB,cAAA,cAA4B,kBAAA;AAAA;;;;KAMzC,wBAAA,mBAA2C,qBAAA;EFJ3C;;AAAO;EEQjB,MAAA,QAAc,WAAA,CACZ,iBAAA,CAAkB,SAAA,GAClB,kBAAA,GAAqB,2BAAA;EFFa;;;EEQpC,UAAA;AAAA;;;AFlBF;;;;;AAAA,KGfY,qBAAA,mBAAwC,kBAAA,KAClD,IAAA,EAAM,gBAAA,CAAiB,SAAA,MACpB,OAAA,CAAQ,iBAAA,CAAkB,SAAA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,EAAc,kBAAA,EACd,IAAA,EAAM,gBAAA,CAAiB,cAAA,cAA4B,kBAAA,IACnD,OAAA,GAAU,yBAAA,GACT,OAAA;EAAA;AAAA"}
package/dist/workflow.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as UpdateOutputValidationError, a as formatChildWorkflowValidationMessage, b as WorkflowOutputValidationError, c as ActivityInputValidationError, d as ChildWorkflowError, f as ChildWorkflowNotFoundError, g as UpdateInputValidationError, h as SignalInputValidationError, i as extractHandlerInput, l as ActivityOutputValidationError, m as QueryOutputValidationError, n as classifyChildWorkflowError, o as makeResultAsync, p as QueryInputValidationError, r as createContinueAsNew, t as buildRawActivitiesProxy, u as ChildWorkflowCancelledError, v as WorkflowCancelledError, x as WorkflowScopeError, y as WorkflowInputValidationError } from "./internal-D8Dl9D43.mjs";
1
+ import { S as WorkflowScopeError, _ as UpdateOutputValidationError, a as formatChildWorkflowValidationMessage, b as WorkflowInputValidationError, c as ActivityInputValidationError, d as ChildWorkflowError, f as ChildWorkflowNotFoundError, g as UpdateInputValidationError, h as SignalInputValidationError, i as extractHandlerInput, l as ActivityOutputValidationError, m as QueryOutputValidationError, n as classifyChildWorkflowError, o as makeResultAsync, p as QueryInputValidationError, r as createContinueAsNew, t as buildRawActivitiesProxy, u as ChildWorkflowCancelledError, v as ValidationError, x as WorkflowOutputValidationError, y as WorkflowCancelledError } from "./internal-D0wfFl0y.mjs";
2
2
  import { CancellationScope, defineQuery, defineSignal, defineUpdate, executeChild, isCancellation, setHandler, startChild, workflowInfo } from "@temporalio/workflow";
3
3
  import { err, ok } from "neverthrow";
4
4
  //#region src/cancellation.ts
@@ -308,12 +308,16 @@ function createValidatedActivities(rawActivities, workflowActivitiesDefinition,
308
308
  * },
309
309
  * // Optional: override `activityOptions` for specific activities. Each
310
310
  * // entry shallow-merges over the workflow default — the override wins on
311
- * // every property it specifies, including the whole `retry` block.
311
+ * // every property it specifies, including the whole `retry` block. The
312
+ * // override is Temporal's full `ActivityOptions`, so `taskQueue` works too,
313
+ * // letting you route individual activities to a dedicated worker pool.
312
314
  * activityOptionsByName: {
313
315
  * chargePayment: {
314
316
  * startToCloseTimeout: '5 minutes',
315
317
  * retry: { maximumAttempts: 5 },
316
318
  * },
319
+ * // Route this activity to a dedicated, concurrency-capped queue.
320
+ * scoreRisk: { taskQueue: 'ml-inference' },
317
321
  * },
318
322
  * implementation: async (context, args) => {
319
323
  * // context.activities: typed activities (workflow + global)
@@ -391,6 +395,6 @@ function declareWorkflow({ workflowName, contract, implementation, activityOptio
391
395
  return workflowFn;
392
396
  }
393
397
  //#endregion
394
- export { ActivityInputValidationError, ActivityOutputValidationError, ChildWorkflowCancelledError, ChildWorkflowError, ChildWorkflowNotFoundError, QueryInputValidationError, QueryOutputValidationError, SignalInputValidationError, UpdateInputValidationError, UpdateOutputValidationError, WorkflowCancelledError, WorkflowInputValidationError, WorkflowOutputValidationError, WorkflowScopeError, declareWorkflow };
398
+ export { ActivityInputValidationError, ActivityOutputValidationError, ChildWorkflowCancelledError, ChildWorkflowError, ChildWorkflowNotFoundError, QueryInputValidationError, QueryOutputValidationError, SignalInputValidationError, UpdateInputValidationError, UpdateOutputValidationError, ValidationError, WorkflowCancelledError, WorkflowInputValidationError, WorkflowOutputValidationError, WorkflowScopeError, declareWorkflow };
395
399
 
396
400
  //# sourceMappingURL=workflow.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"workflow.mjs","names":[],"sources":["../src/cancellation.ts","../src/handlers.ts","../src/child-workflow.ts","../src/activities-proxy.ts","../src/workflow.ts"],"sourcesContent":["/**\n * Typed wrappers around Temporal's `CancellationScope` so workflows can\n * opt into cancellation control without reaching for\n * `@temporalio/workflow` directly. The wrappers fold cancellation into\n * the same `ResultAsync<...>` shape used elsewhere in the worker\n * context — callers branch on `err(WorkflowCancelledError)` instead of\n * catching `CancelledFailure`.\n *\n * Non-cancellation errors thrown inside the scope are wrapped in a\n * {@link WorkflowScopeError} (with the original error preserved on\n * `cause`) and surfaced on the same `err(...)` channel. Together with\n * `WorkflowCancelledError` this makes the failure modes exhaustive on\n * `result.match(...)` — nothing escapes as an unhandled rejection.\n */\nimport { CancellationScope, isCancellation } from \"@temporalio/workflow\";\nimport { type ResultAsync, type Result, ok, err } from \"neverthrow\";\nimport { WorkflowCancelledError, WorkflowScopeError } from \"./errors.js\";\nimport { makeResultAsync } from \"./internal.js\";\n\n/**\n * Run `fn` inside a cancellable Temporal scope. If the workflow (or an\n * ancestor scope) is cancelled while the function is in flight, the\n * resulting ResultAsync resolves to `err(WorkflowCancelledError)`,\n * letting callers handle cancellation explicitly — typically to perform\n * a graceful exit from the current step.\n *\n * Non-cancellation errors thrown by `fn` resolve to\n * `err(WorkflowScopeError)` (with the original error on `cause`) so\n * domain failures surface on the same typed error channel rather than\n * leaking as unhandled rejections.\n *\n * @example\n * ```ts\n * const result = await context.cancellableScope(async () => {\n * return await context.activities.processStep(...);\n * });\n *\n * result.match(\n * (output) => { ... },\n * (error) => {\n * if (error instanceof WorkflowCancelledError) {\n * // graceful exit\n * } else {\n * // error instanceof WorkflowScopeError — domain failure on `cause`\n * }\n * },\n * );\n * ```\n */\nexport function cancellableScope<T>(\n fn: () => T | Promise<T>,\n): ResultAsync<T, WorkflowCancelledError | WorkflowScopeError> {\n const work = async (): Promise<Result<T, WorkflowCancelledError | WorkflowScopeError>> => {\n try {\n // Wrap so synchronous returns satisfy CancellationScope.cancellable's\n // `() => Promise<T>` signature without forcing every caller to write\n // `async () => ...` for purely synchronous bodies.\n const value = await CancellationScope.cancellable(async () => fn());\n return ok(value);\n } catch (error) {\n if (isCancellation(error)) {\n return err(new WorkflowCancelledError(error));\n }\n return err(new WorkflowScopeError(error));\n }\n };\n // makeResultAsync is the shared safety net from `@temporal-contract/contract`\n // — `new ResultAsync(work())` does not catch, so a synchronous throw inside\n // `work` (e.g. a buggy refactor) would escape neverthrow's railway. The\n // catch-all here funnels that back into `err(WorkflowScopeError)` for\n // parity with the in-band path above.\n return makeResultAsync(work, (e) => new WorkflowScopeError(e));\n}\n\n/**\n * Run `fn` inside a non-cancellable Temporal scope. Cancellation requests\n * from outside the scope are ignored for its duration — the idiomatic way\n * to perform cleanup that must not be interrupted (e.g. releasing a\n * resource after a graceful shutdown).\n *\n * Mirrors `cancellableScope`'s `ResultAsync<...>` shape for symmetry; the\n * `err(WorkflowCancelledError)` branch only triggers when cancellation is\n * raised from inside the scope (rare). Non-cancellation errors surface as\n * `err(WorkflowScopeError)`.\n *\n * @example\n * ```ts\n * await context.nonCancellableScope(async () => {\n * await context.activities.releaseResources(...);\n * });\n * ```\n */\nexport function nonCancellableScope<T>(\n fn: () => T | Promise<T>,\n): ResultAsync<T, WorkflowCancelledError | WorkflowScopeError> {\n const work = async (): Promise<Result<T, WorkflowCancelledError | WorkflowScopeError>> => {\n try {\n const value = await CancellationScope.nonCancellable(async () => fn());\n return ok(value);\n } catch (error) {\n if (isCancellation(error)) {\n return err(new WorkflowCancelledError(error));\n }\n return err(new WorkflowScopeError(error));\n }\n };\n return makeResultAsync(work, (e) => new WorkflowScopeError(e));\n}\n","// Top-level helpers for binding signal / query / update handlers to a\n// running workflow. Previously nested inside `declareWorkflow`'s closure\n// (#185), they're hoisted here so the bodies aren't reallocated on each\n// workflow invocation. The typed call-site surface is preserved at the\n// context-assignment site in `workflow.ts` (the arrow that forwards into\n// these helpers carries the contract-derived generic constraints).\n//\n// Internally these are loosely typed (string names, broad `*Definition`\n// inputs); the call sites already do the cast against the typed\n// `WorkflowContext` shape, so the typed-vs-runtime split is the same as\n// it was before the hoist.\nimport type {\n AnyWorkflowDefinition,\n QueryDefinition,\n SignalDefinition,\n UpdateDefinition,\n} from \"@temporal-contract/contract\";\nimport { defineQuery, defineSignal, defineUpdate, setHandler } from \"@temporalio/workflow\";\nimport {\n QueryInputValidationError,\n QueryOutputValidationError,\n SignalInputValidationError,\n UpdateInputValidationError,\n UpdateOutputValidationError,\n} from \"./errors.js\";\nimport { extractHandlerInput } from \"./internal.js\";\nimport type { WorkerInferInput, WorkerInferOutput } from \"./types.js\";\n\n/**\n * Signal handler implementation\n *\n * Processes signal input and can optionally perform asynchronous operations.\n * Should not return a value (signals are fire-and-forget).\n */\nexport type SignalHandlerImplementation<TSignal extends SignalDefinition> = (\n args: WorkerInferInput<TSignal>,\n) => void | Promise<void>;\n\n/**\n * Query handler implementation\n *\n * Processes query input and returns a synchronous response.\n * Must be synchronous to satisfy Temporal's query constraints.\n */\nexport type QueryHandlerImplementation<TQuery extends QueryDefinition> = (\n args: WorkerInferInput<TQuery>,\n) => WorkerInferOutput<TQuery>;\n\n/**\n * Update handler implementation\n *\n * Processes update input and returns a validated response after modifying workflow state.\n * Can perform asynchronous operations.\n */\nexport type UpdateHandlerImplementation<TUpdate extends UpdateDefinition> = (\n args: WorkerInferInput<TUpdate>,\n) => Promise<WorkerInferOutput<TUpdate>>;\n\n/**\n * Bind a typed signal handler to the running workflow. Validates the\n * signal payload against the contract's input schema before invoking the\n * user-supplied handler.\n *\n * The runtime guard against a missing `signals` block — and an unknown\n * signal name within it — covers the union-typed-`workflowName` case\n * where the type system's keyset constraint collapses; without the\n * check, a caller would see `Cannot read properties of undefined`\n * instead of a controlled error.\n */\nexport function bindSignalHandler(\n workflowDefinition: AnyWorkflowDefinition,\n workflowName: string,\n signalName: string,\n handler: SignalHandlerImplementation<SignalDefinition>,\n): void {\n if (!workflowDefinition.signals) {\n throw new Error(\n `Signal \"${signalName}\" cannot be defined: workflow \"${workflowName}\" has no signals in its contract`,\n );\n }\n const signalDef = (workflowDefinition.signals as Record<string, SignalDefinition>)[signalName];\n if (!signalDef) {\n throw new Error(`Signal \"${signalName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const signal = defineSignal(signalName);\n setHandler(signal, async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = await signalDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new SignalInputValidationError(signalName, inputResult.issues);\n }\n await handler(inputResult.value);\n });\n}\n\n/**\n * Bind a typed query handler to the running workflow. Validates input\n * and output against the contract synchronously.\n *\n * Temporal's query API requires a synchronous handler — async\n * validation breaks replay determinism. The handler trips a clear error\n * if the schema library returns a Promise from `validate(...)`, instead\n * of letting the async path silently corrupt query semantics.\n */\nexport function bindQueryHandler(\n workflowDefinition: AnyWorkflowDefinition,\n workflowName: string,\n queryName: string,\n handler: QueryHandlerImplementation<QueryDefinition>,\n): void {\n if (!workflowDefinition.queries) {\n throw new Error(\n `Query \"${queryName}\" cannot be defined: workflow \"${workflowName}\" has no queries in its contract`,\n );\n }\n const queryDef = (workflowDefinition.queries as Record<string, QueryDefinition>)[queryName];\n if (!queryDef) {\n throw new Error(`Query \"${queryName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const query = defineQuery(queryName);\n setHandler(query, (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = queryDef.input[\"~standard\"].validate(input);\n\n if (inputResult instanceof Promise) {\n throw new Error(\n `Query \"${queryName}\" validation must be synchronous. Use a schema library that supports synchronous validation for queries.`,\n );\n }\n if (inputResult.issues) {\n throw new QueryInputValidationError(queryName, inputResult.issues);\n }\n\n const result = handler(inputResult.value);\n\n const outputResult = queryDef.output[\"~standard\"].validate(result);\n if (outputResult instanceof Promise) {\n throw new Error(\n `Query \"${queryName}\" output validation must be synchronous. Use a schema library that supports synchronous validation for queries.`,\n );\n }\n if (outputResult.issues) {\n throw new QueryOutputValidationError(queryName, outputResult.issues);\n }\n\n return outputResult.value;\n });\n}\n\n/**\n * Bind a typed update handler to the running workflow.\n *\n * Input validation runs in Temporal's `validator` slot — a synchronous\n * pre-admission hook. If it throws, Temporal rejects the update *before*\n * appending a workflow history event: clients see\n * `WorkflowUpdateValidationRejectedError` and the workflow's history is\n * unaffected. This is the documented contract for `setHandler`'s\n * `validator` option, and it is strictly better than running validation\n * inside the handler body — which forces Temporal to admit the update,\n * write a history event, and surface a `WorkflowUpdateFailedError` to\n * the client only after the fact.\n *\n * Because the validator slot is synchronous, the input schema must also\n * validate synchronously. Standard Schema is allowed to be async (Zod's\n * `.refine(async)` is the typical case), but we trip a clear error when\n * that happens rather than silently breaking admission semantics — same\n * approach as `bindQueryHandler`. Users who need async input checks\n * should run them inside the handler body and accept the post-admission\n * failure mode, or restructure their schema.\n *\n * Output validation continues to run inside the handler body. Update\n * outputs are *not* admission-gated — the handler must execute to\n * produce a value to validate against — so the async-allowed shape is\n * preserved.\n */\nexport function bindUpdateHandler(\n workflowDefinition: AnyWorkflowDefinition,\n workflowName: string,\n updateName: string,\n handler: UpdateHandlerImplementation<UpdateDefinition>,\n): void {\n if (!workflowDefinition.updates) {\n throw new Error(\n `Update \"${updateName}\" cannot be defined: workflow \"${workflowName}\" has no updates in its contract`,\n );\n }\n const updateDef = (workflowDefinition.updates as Record<string, UpdateDefinition>)[updateName];\n if (!updateDef) {\n throw new Error(`Update \"${updateName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const update = defineUpdate(updateName);\n setHandler(\n update,\n async (...args: unknown[]) => {\n // The validator already accepted the payload — re-parse here so the\n // handler receives the schema's transformed value (Standard Schema\n // may rewrite shapes during validation, e.g. Zod `.transform`). This\n // is sync because the validator already proved the schema is sync;\n // any async result here would mean the schema changed under us,\n // which is a programmer error worth surfacing.\n const input = extractHandlerInput(args);\n const inputResult = updateDef.input[\"~standard\"].validate(input);\n if (inputResult instanceof Promise) {\n throw new Error(\n `Update \"${updateName}\" input validation must be synchronous. Use a schema library that supports synchronous validation for update inputs (Temporal's update validator slot is synchronous).`,\n );\n }\n if (inputResult.issues) {\n // The validator should have caught this; if we reach here, the\n // schema produced different issues on a second call (non-pure\n // validator). Surface it as the same typed error class for\n // consistency.\n throw new UpdateInputValidationError(updateName, inputResult.issues);\n }\n\n const result = await handler(inputResult.value);\n\n const outputResult = await updateDef.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new UpdateOutputValidationError(updateName, outputResult.issues);\n }\n\n return outputResult.value;\n },\n {\n validator: (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = updateDef.input[\"~standard\"].validate(input);\n\n if (inputResult instanceof Promise) {\n throw new Error(\n `Update \"${updateName}\" input validation must be synchronous. Use a schema library that supports synchronous validation for update inputs (Temporal's update validator slot is synchronous).`,\n );\n }\n if (inputResult.issues) {\n throw new UpdateInputValidationError(updateName, inputResult.issues);\n }\n },\n },\n );\n}\n","/**\n * Child workflow types + helpers used by `declareWorkflow`. Split out of\n * `workflow.ts` to keep that file focused on `declareWorkflow` and its\n * `WorkflowContext` type. Not part of the worker package's public exports.\n */\nimport type { AnyWorkflowDefinition, ContractDefinition } from \"@temporal-contract/contract\";\nimport {\n ChildWorkflowHandle,\n ChildWorkflowOptions,\n executeChild,\n startChild,\n} from \"@temporalio/workflow\";\nimport { ResultAsync, type Result, ok, err } from \"neverthrow\";\nimport {\n ChildWorkflowCancelledError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n} from \"./errors.js\";\nimport {\n classifyChildWorkflowError,\n formatChildWorkflowValidationMessage,\n makeResultAsync,\n} from \"./internal.js\";\nimport type { ClientInferInput, ClientInferOutput, WorkerInferInput } from \"./types.js\";\n\n/**\n * Options for starting a child workflow. `taskQueue` and `args` come from\n * the contract; everything else is forwarded to Temporal's\n * `startChild` / `executeChild`.\n */\nexport type TypedChildWorkflowOptions<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n> = Omit<ChildWorkflowOptions, \"taskQueue\" | \"args\"> & {\n args: ClientInferInput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n};\n\n/**\n * Typed handle for a child workflow with neverthrow `ResultAsync` pattern.\n */\nexport type TypedChildWorkflowHandle<TWorkflow extends AnyWorkflowDefinition> = {\n /**\n * Get child workflow result with `ResultAsync` pattern.\n */\n result: () => ResultAsync<\n ClientInferOutput<TWorkflow>,\n ChildWorkflowError | ChildWorkflowCancelledError\n >;\n\n /**\n * Child workflow ID.\n */\n workflowId: string;\n};\n\nasync function validateChildWorkflowOutput<TChildWorkflow extends AnyWorkflowDefinition>(\n childDefinition: TChildWorkflow,\n result: unknown,\n childWorkflowName: string,\n): Promise<Result<ClientInferOutput<TChildWorkflow>, ChildWorkflowError>> {\n const outputResult = await childDefinition.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n return err(\n new ChildWorkflowError(\n formatChildWorkflowValidationMessage(childWorkflowName, \"output\", outputResult.issues),\n ),\n );\n }\n return ok(outputResult.value as ClientInferOutput<TChildWorkflow>);\n}\n\nasync function getAndValidateChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n args: unknown,\n): Promise<\n Result<\n {\n definition: TChildContract[\"workflows\"][TChildWorkflowName];\n validatedInput: WorkerInferInput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n taskQueue: string;\n },\n ChildWorkflowError\n >\n> {\n const childDefinition = childContract.workflows[childWorkflowName];\n\n if (!childDefinition) {\n return err(\n new ChildWorkflowNotFoundError(\n childWorkflowName,\n Object.keys(childContract.workflows) as string[],\n ),\n );\n }\n\n const inputResult = await childDefinition.input[\"~standard\"].validate(args);\n if (inputResult.issues) {\n return err(\n new ChildWorkflowError(\n formatChildWorkflowValidationMessage(childWorkflowName, \"input\", inputResult.issues),\n ),\n );\n }\n\n const validatedInput = inputResult.value as WorkerInferInput<\n TChildContract[\"workflows\"][TChildWorkflowName]\n >;\n\n return ok({\n definition: childDefinition as TChildContract[\"workflows\"][TChildWorkflowName],\n validatedInput,\n taskQueue: childContract.taskQueue,\n });\n}\n\nfunction createTypedChildHandle<TChildWorkflow extends AnyWorkflowDefinition>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handle: ChildWorkflowHandle<any>,\n childDefinition: TChildWorkflow,\n childWorkflowName: string,\n): TypedChildWorkflowHandle<TChildWorkflow> {\n return {\n workflowId: handle.workflowId,\n result: (): ResultAsync<\n ClientInferOutput<TChildWorkflow>,\n ChildWorkflowError | ChildWorkflowCancelledError\n > => {\n const work = async (): Promise<\n Result<ClientInferOutput<TChildWorkflow>, ChildWorkflowError | ChildWorkflowCancelledError>\n > => {\n try {\n const result = await handle.result();\n return validateChildWorkflowOutput(childDefinition, result, childWorkflowName);\n } catch (error) {\n return err(classifyChildWorkflowError(\"result\", error, childWorkflowName));\n }\n };\n return makeResultAsync(\n work,\n (error) =>\n new ChildWorkflowError(\n `Child workflow execution failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n },\n };\n}\n\nexport function createStartChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n): ResultAsync<\n TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n> {\n type Ok = TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>;\n const work = async (): Promise<\n Result<Ok, ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError>\n > => {\n const validationResult = await getAndValidateChildWorkflow(\n childContract,\n childWorkflowName,\n options.args,\n );\n\n if (validationResult.isErr()) {\n return err(validationResult.error);\n }\n\n const { definition: childDefinition, validatedInput, taskQueue } = validationResult.value;\n\n try {\n const { args: _args, ...temporalOptions } = options;\n const handle = await startChild(childWorkflowName, {\n ...temporalOptions,\n taskQueue,\n args: [validatedInput],\n });\n\n const typedHandle = createTypedChildHandle(handle, childDefinition, childWorkflowName) as Ok;\n\n return ok(typedHandle);\n } catch (error) {\n return err(classifyChildWorkflowError(\"startChild\", error, String(childWorkflowName)));\n }\n };\n return makeResultAsync(\n work,\n (error) =>\n new ChildWorkflowError(\n `Failed to start child workflow: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n}\n\nexport function createExecuteChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n): ResultAsync<\n ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n> {\n type Ok = ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n const work = async (): Promise<\n Result<Ok, ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError>\n > => {\n const validationResult = await getAndValidateChildWorkflow(\n childContract,\n childWorkflowName,\n options.args,\n );\n\n if (validationResult.isErr()) {\n return err(validationResult.error);\n }\n\n const { definition: childDefinition, validatedInput, taskQueue } = validationResult.value;\n\n try {\n const { args: _args, ...temporalOptions } = options;\n const result = await executeChild(childWorkflowName, {\n ...temporalOptions,\n taskQueue,\n args: [validatedInput],\n });\n\n const outputValidationResult = await validateChildWorkflowOutput(\n childDefinition,\n result,\n childWorkflowName,\n );\n\n if (outputValidationResult.isErr()) {\n return err(outputValidationResult.error);\n }\n\n return ok(outputValidationResult.value as Ok);\n } catch (error) {\n return err(classifyChildWorkflowError(\"executeChild\", error, String(childWorkflowName)));\n }\n };\n return makeResultAsync(\n work,\n (error) =>\n new ChildWorkflowError(\n `Failed to execute child workflow: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n}\n","/**\n * Activity inference types + the validated-activities proxy used by\n * `declareWorkflow`. Split out of `workflow.ts` to keep that file focused\n * on `declareWorkflow` and its `WorkflowContext` type. Not part of the\n * worker package's public exports.\n */\nimport type {\n ActivityDefinition,\n AnyWorkflowDefinition,\n ContractDefinition,\n} from \"@temporal-contract/contract\";\nimport { ActivityInputValidationError, ActivityOutputValidationError } from \"./errors.js\";\nimport type { ClientInferInput, ClientInferOutput } from \"./types.js\";\n\n/**\n * Activity function signature from workflow execution perspective.\n *\n * Workflows call activities with validated input (z.input parsed) and receive validated output (z.output).\n */\nexport type WorkflowInferActivity<TActivity extends ActivityDefinition> = (\n args: ClientInferInput<TActivity>,\n) => Promise<ClientInferOutput<TActivity>>;\n\n/**\n * All global activities from a contract (workflow execution perspective).\n */\nexport type WorkflowInferActivities<TContract extends ContractDefinition> =\n TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? {\n [K in keyof TContract[\"activities\"]]: WorkflowInferActivity<TContract[\"activities\"][K]>;\n }\n : {};\n\n/**\n * Workflow-specific activities (workflow execution perspective).\n */\nexport type WorkflowInferWorkflowActivities<T extends AnyWorkflowDefinition> =\n T[\"activities\"] extends Record<string, ActivityDefinition>\n ? {\n [K in keyof T[\"activities\"]]: WorkflowInferActivity<T[\"activities\"][K]>;\n }\n : {};\n\n/**\n * All activities available in a workflow context (workflow execution perspective).\n *\n * Combines workflow-specific activities with global contract activities.\n */\nexport type WorkflowInferWorkflowContextActivities<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = WorkflowInferWorkflowActivities<TContract[\"workflows\"][TWorkflowName]> &\n WorkflowInferActivities<TContract>;\n\n/**\n * Wrap the raw activities proxy with input/output validation against the\n * Standard Schema definitions on the contract. The wrapper enforces data\n * integrity at the workflow → activity boundary in addition to the\n * activity-side validation that `declareActivitiesHandler` already runs.\n */\nexport function createValidatedActivities<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n>(\n rawActivities: Record<string, (...args: unknown[]) => Promise<unknown>>,\n workflowActivitiesDefinition: Record<string, ActivityDefinition> | undefined,\n contractActivitiesDefinition: Record<string, ActivityDefinition> | undefined,\n): WorkflowInferWorkflowContextActivities<TContract, TWorkflowName> {\n const validatedActivities = {} as WorkflowInferWorkflowContextActivities<\n TContract,\n TWorkflowName\n >;\n\n // Merge workflow-specific and global contract activities. defineContract\n // guarantees there are no name collisions across scopes, so spread order\n // is just a stable iteration choice (workflow-local last).\n const allActivitiesDefinition = {\n ...contractActivitiesDefinition,\n ...workflowActivitiesDefinition,\n };\n\n for (const [activityName, activityDef] of Object.entries(allActivitiesDefinition)) {\n const rawActivity = rawActivities[activityName];\n\n if (!rawActivity) {\n throw new Error(\n `Activity implementation not found for: \"${activityName}\". ` +\n `Available activities: ${Object.keys(rawActivities).length > 0 ? Object.keys(rawActivities).join(\", \") : \"none\"}`,\n );\n }\n\n (validatedActivities as Record<string, unknown>)[activityName] = async (input: unknown) => {\n const inputResult = await activityDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new ActivityInputValidationError(activityName, inputResult.issues);\n }\n\n const result = await rawActivity(inputResult.value);\n\n const outputResult = await activityDef.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new ActivityOutputValidationError(activityName, outputResult.issues);\n }\n\n return outputResult.value;\n };\n }\n\n return validatedActivities;\n}\n","// Entry point for workflow implementations.\n//\n// Workflows run inside Temporal's deterministic sandbox, which intercepts\n// timers, randomness, and Promise scheduling for replay. neverthrow's\n// `Result`/`ResultAsync` rely only on Promise scheduling, so they replay\n// deterministically alongside Temporal's machinery. Activity code (see\n// activity.ts) uses the same neverthrow API.\nimport type {\n ActivityDefinition,\n ContractDefinition,\n QueryDefinition,\n QueryNamesOf,\n SignalDefinition,\n SignalNamesOf,\n UpdateDefinition,\n UpdateNamesOf,\n} from \"@temporal-contract/contract\";\nimport {\n ChildWorkflowCancelledError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n WorkflowCancelledError,\n WorkflowInputValidationError,\n WorkflowOutputValidationError,\n WorkflowScopeError,\n} from \"./errors.js\";\nimport { cancellableScope, nonCancellableScope } from \"./cancellation.js\";\nimport {\n bindQueryHandler,\n bindSignalHandler,\n bindUpdateHandler,\n type QueryHandlerImplementation,\n type SignalHandlerImplementation,\n type UpdateHandlerImplementation,\n} from \"./handlers.js\";\nimport {\n ClientInferInput,\n ClientInferOutput,\n WorkerInferInput,\n WorkerInferOutput,\n} from \"./types.js\";\nimport type { ResultAsync } from \"neverthrow\";\nimport {\n buildRawActivitiesProxy,\n createContinueAsNew,\n extractHandlerInput,\n type TypedContinueAsNewOptions,\n} from \"./internal.js\";\nimport {\n createStartChildWorkflow,\n createExecuteChildWorkflow,\n type TypedChildWorkflowHandle,\n type TypedChildWorkflowOptions,\n} from \"./child-workflow.js\";\nimport {\n createValidatedActivities,\n type WorkflowInferWorkflowContextActivities,\n} from \"./activities-proxy.js\";\nimport { ActivityOptions, WorkflowInfo, workflowInfo } from \"@temporalio/workflow\";\n\nexport {\n ActivityInputValidationError,\n ActivityOutputValidationError,\n ChildWorkflowCancelledError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n QueryInputValidationError,\n QueryOutputValidationError,\n SignalInputValidationError,\n UpdateInputValidationError,\n UpdateOutputValidationError,\n WorkflowCancelledError,\n WorkflowInputValidationError,\n WorkflowOutputValidationError,\n WorkflowScopeError,\n} from \"./errors.js\";\n\n/**\n * Create a typed workflow implementation with automatic validation\n *\n * This wraps a workflow implementation with:\n * - Input/output validation\n * - Typed workflow context with activities\n * - Workflow info access\n *\n * Workflows must be defined in separate files and imported by the Temporal Worker\n * via workflowsPath.\n *\n * @example\n * ```ts\n * // workflows/processOrder.ts\n * import { declareWorkflow } from '@temporal-contract/worker/workflow';\n * import myContract from '../contract';\n *\n * export const processOrder = declareWorkflow({\n * workflowName: 'processOrder',\n * contract: myContract,\n * activityOptions: {\n * startToCloseTimeout: '1 minute',\n * },\n * // Optional: override `activityOptions` for specific activities. Each\n * // entry shallow-merges over the workflow default — the override wins on\n * // every property it specifies, including the whole `retry` block.\n * activityOptionsByName: {\n * chargePayment: {\n * startToCloseTimeout: '5 minutes',\n * retry: { maximumAttempts: 5 },\n * },\n * },\n * implementation: async (context, args) => {\n * // context.activities: typed activities (workflow + global)\n * // context.info: WorkflowInfo\n *\n * const inventory = await context.activities.validateInventory({\n * orderId: args.orderId,\n * });\n *\n * if (!inventory.available) {\n * return { orderId: args.orderId, status: 'out_of_stock' };\n * }\n *\n * const payment = await context.activities.chargePayment({\n * customerId: args.customerId,\n * amount: 100,\n * });\n *\n * return {\n * orderId: args.orderId,\n * status: payment.success ? 'success' : 'failed',\n * transactionId: payment.transactionId,\n * };\n * },\n * });\n * ```\n *\n * Then in your worker setup:\n * ```ts\n * // worker.ts\n * import { createWorker } from '@temporal-contract/worker/worker';\n * import { activities } from './activities';\n * import myContract from './contract';\n *\n * const worker = await createWorker({\n * contract: myContract,\n * connection,\n * workflowsPath: workflowsPathFromURL(import.meta.url, './workflows.js'),\n * activities,\n * });\n * ```\n */\nexport function declareWorkflow<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n>({\n workflowName,\n contract,\n implementation,\n activityOptions,\n activityOptionsByName,\n}: DeclareWorkflowOptions<TContract, TWorkflowName>): (\n ...args: unknown[]\n) => Promise<WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>> {\n // Get the workflow definition from the contract\n const definition = contract.workflows[workflowName] as TContract[\"workflows\"][TWorkflowName];\n\n // Build the activities proxy *once* at declaration time, not per workflow\n // invocation. Temporal's `proxyActivities` is documented as a module-scope\n // helper — it registers stub functions and may carry bookkeeping\n // (validator pre-registration, payload-converter caching) that breaks if\n // re-invoked on every workflow run. The call depends only on contract-time\n // immutables (`definition.activities`, `contract.activities`,\n // `activityOptions`, `activityOptionsByName`), all of which are available\n // here, so hoisting is safe and deterministic.\n //\n // The validation wrapper (`createValidatedActivities`) is stateless across\n // invocations — it merely closes over the activity definitions and the raw\n // proxy, both immutable — so it is hoisted alongside the proxy. The\n // resulting `contextActivities` object is shared by every workflow run,\n // which is fine because the wrapped activity functions take their input\n // as an argument and validate it per-call (no closed-over per-invocation\n // state).\n //\n // Design note — intentional double-validation:\n // Input and output are validated here (workflow side) AND again inside\n // `declareActivitiesHandler` (activity worker side). This is deliberate:\n //\n // 1. Workflow-side validation catches bad data *before* it crosses the\n // task-queue network boundary, giving an early, descriptive error\n // instead of a confusing deserialization failure inside the activity.\n // 2. Activity-side validation is the authoritative guard, since the\n // activity may be called by other callers that do not use this library.\n //\n // The overhead is minimal relative to the network round-trip.\n let contextActivities: unknown = {};\n\n if (definition.activities || contract.activities) {\n const rawActivities = buildRawActivitiesProxy(\n definition.activities,\n contract.activities,\n activityOptions,\n activityOptionsByName,\n );\n\n contextActivities = createValidatedActivities(\n rawActivities,\n definition.activities,\n contract.activities,\n );\n\n // Shared across workflow invocations after the proxyActivities hoist\n // (PR #211); freeze so user code can't mutate one invocation's view of\n // activities and have it leak into others. The freeze is shallow, which\n // is sufficient because `createValidatedActivities` returns a flat\n // `{ [name]: (input) => Promise<output> }` map — every value is a\n // stateless validation wrapper function, not a nested object users could\n // reach into. The matching `Readonly<...>` on `WorkflowContext.activities`\n // surfaces the immutability at the type level.\n Object.freeze(contextActivities);\n }\n\n const workflowFn = async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n\n // Validate workflow input\n const inputResult = await definition.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new WorkflowInputValidationError(workflowName, inputResult.issues);\n }\n const validatedInput = inputResult.value as WorkerInferInput<\n TContract[\"workflows\"][TWorkflowName]\n >;\n\n // Create workflow context.\n //\n // The defineSignal / defineQuery / defineUpdate arrows forward to the\n // hoisted helpers in `./handlers.ts`. The arrows themselves are thin\n // closures that close over `definition` and `workflowName`; the heavy\n // logic — runtime guards, validation, Temporal `defineSignal/Query/\n // Update` + `setHandler` wiring — lives at module scope so it isn't\n // reallocated on each workflow invocation.\n //\n // The cast at each assignment preserves the typed call-site surface\n // (the `K extends keyof ...` constraints declared on\n // `WorkflowContext.defineSignal/Query/Update`), while the helpers\n // themselves take loosely-typed arguments at the runtime boundary.\n const context: WorkflowContext<TContract, TWorkflowName> = {\n activities: contextActivities as WorkflowInferWorkflowContextActivities<\n TContract,\n TWorkflowName\n >,\n info: workflowInfo(),\n startChildWorkflow: createStartChildWorkflow,\n executeChildWorkflow: createExecuteChildWorkflow,\n cancellableScope,\n nonCancellableScope,\n defineSignal: ((signalName, handler) =>\n bindSignalHandler(\n definition,\n workflowName,\n signalName,\n handler as unknown as SignalHandlerImplementation<SignalDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineSignal\"],\n defineQuery: ((queryName, handler) =>\n bindQueryHandler(\n definition,\n workflowName,\n queryName,\n handler as unknown as QueryHandlerImplementation<QueryDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineQuery\"],\n defineUpdate: ((updateName, handler) =>\n bindUpdateHandler(\n definition,\n workflowName,\n updateName,\n handler as unknown as UpdateHandlerImplementation<UpdateDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineUpdate\"],\n continueAsNew: createContinueAsNew(contract, workflowName) as WorkflowContext<\n TContract,\n TWorkflowName\n >[\"continueAsNew\"],\n };\n\n // Execute workflow (pass validated input as tuple)\n const result = await implementation(context, validatedInput);\n\n // Validate workflow output\n const outputResult = await definition.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new WorkflowOutputValidationError(workflowName, outputResult.issues);\n }\n\n return outputResult.value as WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>;\n };\n\n // Temporal's client.workflow.start(fn, ...) reads `fn.name` to derive the\n // workflow type; without this the anonymous arrow above would surface as \"\".\n Object.defineProperty(workflowFn, \"name\", { value: workflowName, configurable: true });\n\n return workflowFn;\n}\n\n/**\n * Union of all activity names available to a workflow — the workflow-local\n * activities plus the contract's global activities.\n */\ntype ActivityNamesFor<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> =\n | (TContract[\"workflows\"][TWorkflowName][\"activities\"] extends Record<string, ActivityDefinition>\n ? keyof TContract[\"workflows\"][TWorkflowName][\"activities\"] & string\n : never)\n | (TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? keyof TContract[\"activities\"] & string\n : never);\n\n/**\n * Options for declaring a workflow implementation\n */\ntype DeclareWorkflowOptions<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = {\n workflowName: TWorkflowName;\n contract: TContract;\n implementation: WorkflowImplementation<TContract, TWorkflowName>;\n /**\n * Default activity options applied to every activity reachable from this\n * workflow (workflow-local + global) unless overridden in\n * {@link activityOptionsByName}. See Temporal's `ActivityOptions` for the\n * full set of fields:\n * - `startToCloseTimeout`: Maximum time for a single attempt to run\n * - `scheduleToCloseTimeout`: End-to-end timeout including queuing and retries\n * - `scheduleToStartTimeout`: Maximum time the activity can wait in the queue\n * - `heartbeatTimeout`: Time between heartbeats before the activity is considered dead\n * - `retry`: Retry policy for failed activities\n *\n * @example\n * ```ts\n * activityOptions: {\n * startToCloseTimeout: '5m',\n * retry: { maximumAttempts: 3 },\n * }\n * ```\n */\n activityOptions: ActivityOptions;\n /**\n * Per-activity `ActivityOptions` overrides. Each entry shallow-merges over\n * {@link activityOptions} for that activity only — the override wins on\n * every property it specifies, replacing the default value (including the\n * entire nested `retry` block when present, matching Temporal's\n * single-options-per-`proxyActivities`-call semantics).\n *\n * Activity names are typed against the contract; typos surface as TypeScript\n * errors rather than running silently with the default options.\n *\n * @example\n * ```ts\n * activityOptions: { startToCloseTimeout: '1 minute' }, // default\n * activityOptionsByName: {\n * chargePayment: {\n * startToCloseTimeout: '5 minutes',\n * retry: { maximumAttempts: 5 },\n * },\n * fastValidation: { startToCloseTimeout: '5 seconds' },\n * },\n * ```\n */\n activityOptionsByName?: Partial<\n Record<ActivityNamesFor<TContract, TWorkflowName>, ActivityOptions>\n >;\n};\n\n/**\n * Workflow implementation function\n *\n * Receives a workflow context (with typed activities and utilities) and validated input arguments.\n * Returns the workflow output which will be validated against the contract schema.\n */\ntype WorkflowImplementation<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = (\n context: WorkflowContext<TContract, TWorkflowName>,\n args: WorkerInferInput<TContract[\"workflows\"][TWorkflowName]>,\n) => Promise<WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>>;\n\n/**\n * Workflow execution context providing typed activities, workflow info, and interaction handlers\n *\n * Provides access to:\n * - Typed activities (both workflow-specific and global)\n * - Workflow metadata and execution info\n * - Signal, query, and update handler registration\n * - Child workflow execution capabilities\n */\ntype WorkflowContext<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = {\n activities: Readonly<WorkflowInferWorkflowContextActivities<TContract, TWorkflowName>>;\n info: WorkflowInfo;\n\n /**\n * Define a signal handler within the workflow implementation\n * Allows the signal handler to access workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineSignal('increment', async (signalArgs) => {\n * currentValue += signalArgs.amount;\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineSignal: <K extends SignalNamesOf<TContract[\"workflows\"][TWorkflowName]>>(\n signalName: K,\n handler: SignalHandlerImplementation<\n NonNullable<TContract[\"workflows\"][TWorkflowName][\"signals\"]> extends Record<\n string,\n SignalDefinition\n >\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"signals\"]>[K] extends SignalDefinition\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"signals\"]>[K]\n : never\n : never\n >,\n ) => void;\n\n /**\n * Define a query handler within the workflow implementation\n * Allows the query handler to access workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineQuery('getCurrentValue', () => {\n * return { value: currentValue };\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineQuery: <K extends QueryNamesOf<TContract[\"workflows\"][TWorkflowName]>>(\n queryName: K,\n handler: QueryHandlerImplementation<\n NonNullable<TContract[\"workflows\"][TWorkflowName][\"queries\"]> extends Record<\n string,\n QueryDefinition\n >\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"queries\"]>[K] extends QueryDefinition\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"queries\"]>[K]\n : never\n : never\n >,\n ) => void;\n\n /**\n * Define an update handler within the workflow implementation\n * Allows the update handler to access and modify workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineUpdate('multiply', async (updateArgs) => {\n * currentValue *= updateArgs.factor;\n * return { newValue: currentValue };\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineUpdate: <K extends UpdateNamesOf<TContract[\"workflows\"][TWorkflowName]>>(\n updateName: K,\n handler: UpdateHandlerImplementation<\n NonNullable<TContract[\"workflows\"][TWorkflowName][\"updates\"]> extends Record<\n string,\n UpdateDefinition\n >\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"updates\"]>[K] extends UpdateDefinition\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"updates\"]>[K]\n : never\n : never\n >,\n ) => void;\n\n /**\n * Start a child workflow and return a typed handle with ResultAsync pattern\n *\n * Supports both same-contract and cross-contract child workflows:\n * - Same contract: Pass workflowName from current contract\n * - Cross-contract: Pass contract and workflowName to invoke workflows from other workers\n *\n * @example\n * ```ts\n * // Same contract child workflow\n * const childResult = await context.startChildWorkflow(myContract, 'processPayment', {\n * workflowId: 'payment-123',\n * args: { amount: 100 }\n * });\n *\n * // Cross-contract child workflow (from another worker)\n * const otherResult = await context.startChildWorkflow(otherContract, 'sendNotification', {\n * workflowId: 'notification-123',\n * args: { message: 'Hello' }\n * });\n *\n * childResult.match(\n * async (handle) => {\n * const result = await handle.result();\n * // ... handle result\n * },\n * (error) => console.error('Failed to start:', error),\n * );\n * ```\n */\n startChildWorkflow: <\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n >(\n contract: TChildContract,\n workflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n ) => ResultAsync<\n TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n >;\n\n /**\n * Execute a child workflow (start and wait for result) with ResultAsync pattern\n *\n * Supports both same-contract and cross-contract child workflows:\n * - Same contract: Pass workflowName from current contract\n * - Cross-contract: Pass contract and workflowName to invoke workflows from other workers\n *\n * @example\n * ```ts\n * // Same contract child workflow\n * const result = await context.executeChildWorkflow(myContract, 'processPayment', {\n * workflowId: 'payment-123',\n * args: { amount: 100 }\n * });\n *\n * // Cross-contract child workflow (from another worker)\n * const otherResult = await context.executeChildWorkflow(otherContract, 'sendNotification', {\n * workflowId: 'notification-123',\n * args: { message: 'Hello' }\n * });\n *\n * result.match(\n * (output) => console.log('Payment processed:', output),\n * (error) => console.error('Processing failed:', error),\n * );\n * ```\n */\n executeChildWorkflow: <\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n >(\n contract: TChildContract,\n workflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n ) => ResultAsync<\n ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n >;\n\n /**\n * Run `fn` inside a cancellable Temporal scope. If the workflow (or an\n * ancestor scope) is cancelled while `fn` is in flight, the resulting\n * ResultAsync resolves to `err(WorkflowCancelledError)` instead of\n * rejecting — letting callers handle cancellation explicitly, typically\n * to perform a graceful exit from the current step.\n *\n * Non-cancellation errors thrown by `fn` resolve to\n * `err(WorkflowScopeError)` (with the original error preserved on\n * `cause`). Both failure modes ride neverthrow's railway, so\n * `result.match(...)` is exhaustive — nothing escapes as an unhandled\n * rejection.\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * const result = await context.cancellableScope(async () => {\n * return context.activities.processStep(args);\n * });\n *\n * if (result.isErr()) {\n * if (result.error instanceof WorkflowCancelledError) {\n * // workflow was cancelled — perform cleanup that must not be cancelled:\n * await context.nonCancellableScope(async () => {\n * await context.activities.releaseResources(args);\n * });\n * return { status: \"cancelled\" };\n * }\n * // result.error instanceof WorkflowScopeError — domain failure\n * return { status: \"failed\" };\n * }\n *\n * return { status: \"ok\" };\n * }\n * ```\n */\n cancellableScope: <T>(\n fn: () => T | Promise<T>,\n ) => ResultAsync<T, WorkflowCancelledError | WorkflowScopeError>;\n\n /**\n * Run `fn` inside a non-cancellable Temporal scope. Cancellation requests\n * from outside the scope are ignored for its duration — the idiomatic way\n * to perform cleanup work that must not be interrupted.\n *\n * Returns the same `ResultAsync<...>` shape as\n * {@link WorkflowContext.cancellableScope} for symmetry; the\n * `err(WorkflowCancelledError)` branch only triggers when cancellation is\n * raised from *inside* the scope, which is rare. Non-cancellation errors\n * surface as `err(WorkflowScopeError)`.\n */\n nonCancellableScope: <T>(\n fn: () => T | Promise<T>,\n ) => ResultAsync<T, WorkflowCancelledError | WorkflowScopeError>;\n\n /**\n * Continue this workflow execution as a new run, optionally with a different\n * workflow type from another contract.\n *\n * Args are validated against the destination workflow's input schema before\n * Temporal's `continueAsNew` is invoked. On validation failure, throws a\n * {@link WorkflowInputValidationError}; on success, Temporal terminates the\n * current execution and starts a fresh one — which is why the function\n * never returns normally (`Promise<never>`).\n *\n * Idiomatic usage:\n *\n * @example\n * ```ts\n * // Same workflow, validated args\n * implementation: async (context, args) => {\n * if (shouldRoll(args)) {\n * return context.continueAsNew({ ...args, retryCount: args.retryCount + 1 });\n * }\n * return ...;\n * }\n *\n * // Cross-contract continueAsNew (less common — taskQueue and workflow type\n * // come from the other contract)\n * return context.continueAsNew(otherContract, \"otherWorkflow\", { ...newArgs });\n * ```\n */\n continueAsNew: {\n /** Same-workflow continuation — args typed against this workflow's input. */\n (\n args: ClientInferInput<TContract[\"workflows\"][TWorkflowName]>,\n options?: TypedContinueAsNewOptions,\n ): Promise<never>;\n /** Cross-contract continuation — args typed against the destination workflow. */\n <\n TOtherContract extends ContractDefinition,\n TOtherWorkflowName extends keyof TOtherContract[\"workflows\"] & string,\n >(\n contract: TOtherContract,\n workflowName: TOtherWorkflowName,\n args: ClientInferInput<TOtherContract[\"workflows\"][TOtherWorkflowName]>,\n options?: TypedContinueAsNewOptions,\n ): Promise<never>;\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,iBACd,IAC6D;CAC7D,MAAM,OAAO,YAA6E;EACxF,IAAI;GAKF,OAAO,GAAG,MADU,kBAAkB,YAAY,YAAY,GAAG,CAAC,CACnD;EACjB,SAAS,OAAO;GACd,IAAI,eAAe,KAAK,GACtB,OAAO,IAAI,IAAI,uBAAuB,KAAK,CAAC;GAE9C,OAAO,IAAI,IAAI,mBAAmB,KAAK,CAAC;EAC1C;CACF;CAMA,OAAO,gBAAgB,OAAO,MAAM,IAAI,mBAAmB,CAAC,CAAC;AAC/D;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,oBACd,IAC6D;CAC7D,MAAM,OAAO,YAA6E;EACxF,IAAI;GAEF,OAAO,GAAG,MADU,kBAAkB,eAAe,YAAY,GAAG,CAAC,CACtD;EACjB,SAAS,OAAO;GACd,IAAI,eAAe,KAAK,GACtB,OAAO,IAAI,IAAI,uBAAuB,KAAK,CAAC;GAE9C,OAAO,IAAI,IAAI,mBAAmB,KAAK,CAAC;EAC1C;CACF;CACA,OAAO,gBAAgB,OAAO,MAAM,IAAI,mBAAmB,CAAC,CAAC;AAC/D;;;;;;;;;;;;;;ACtCA,SAAgB,kBACd,oBACA,cACA,YACA,SACM;CACN,IAAI,CAAC,mBAAmB,SACtB,MAAM,IAAI,MACR,WAAW,WAAW,iCAAiC,aAAa,iCACtE;CAEF,MAAM,YAAa,mBAAmB,QAA6C;CACnF,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,WAAW,WAAW,2BAA2B,aAAa,WAAW;CAI3F,WADe,aAAa,UACZ,GAAG,OAAO,GAAG,SAAoB;EAC/C,MAAM,QAAQ,oBAAoB,IAAI;EACtC,MAAM,cAAc,MAAM,UAAU,MAAM,YAAY,CAAC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;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACyCA,SAAgB,gBAGd,EACA,cACA,UACA,gBACA,iBACA,yBAGqE;CAErE,MAAM,aAAa,SAAS,UAAU;CA8BtC,IAAI,oBAA6B,CAAC;CAElC,IAAI,WAAW,cAAc,SAAS,YAAY;EAQhD,oBAAoB,0BAPE,wBACpB,WAAW,YACX,SAAS,YACT,iBACA,qBAIY,GACZ,WAAW,YACX,SAAS,UACX;EAUA,OAAO,OAAO,iBAAiB;CACjC;CAEA,MAAM,aAAa,OAAO,GAAG,SAAoB;EAC/C,MAAM,QAAQ,oBAAoB,IAAI;EAGtC,MAAM,cAAc,MAAM,WAAW,MAAM,YAAY,CAAC,SAAS,KAAK;EACtE,IAAI,YAAY,QACd,MAAM,IAAI,6BAA6B,cAAc,YAAY,MAAM;EAEzE,MAAM,iBAAiB,YAAY;EAuDnC,MAAM,SAAS,MAAM,eAAe;GArClC,YAAY;GAIZ,MAAM,aAAa;GACnB,oBAAoB;GACpB,sBAAsB;GACtB;GACA;GACA,gBAAgB,YAAY,YAC1B,kBACE,YACA,cACA,YACA,OACF;GACF,eAAe,WAAW,YACxB,iBACE,YACA,cACA,WACA,OACF;GACF,gBAAgB,YAAY,YAC1B,kBACE,YACA,cACA,YACA,OACF;GACF,eAAe,oBAAoB,UAAU,YAAY;EAOjB,GAAG,cAAc;EAG3D,MAAM,eAAe,MAAM,WAAW,OAAO,YAAY,CAAC,SAAS,MAAM;EACzE,IAAI,aAAa,QACf,MAAM,IAAI,8BAA8B,cAAc,aAAa,MAAM;EAG3E,OAAO,aAAa;CACtB;CAIA,OAAO,eAAe,YAAY,QAAQ;EAAE,OAAO;EAAc,cAAc;CAAK,CAAC;CAErF,OAAO;AACT"}
1
+ {"version":3,"file":"workflow.mjs","names":[],"sources":["../src/cancellation.ts","../src/handlers.ts","../src/child-workflow.ts","../src/activities-proxy.ts","../src/workflow.ts"],"sourcesContent":["/**\n * Typed wrappers around Temporal's `CancellationScope` so workflows can\n * opt into cancellation control without reaching for\n * `@temporalio/workflow` directly. The wrappers fold cancellation into\n * the same `ResultAsync<...>` shape used elsewhere in the worker\n * context — callers branch on `err(WorkflowCancelledError)` instead of\n * catching `CancelledFailure`.\n *\n * Non-cancellation errors thrown inside the scope are wrapped in a\n * {@link WorkflowScopeError} (with the original error preserved on\n * `cause`) and surfaced on the same `err(...)` channel. Together with\n * `WorkflowCancelledError` this makes the failure modes exhaustive on\n * `result.match(...)` — nothing escapes as an unhandled rejection.\n */\nimport { CancellationScope, isCancellation } from \"@temporalio/workflow\";\nimport { type ResultAsync, type Result, ok, err } from \"neverthrow\";\nimport { WorkflowCancelledError, WorkflowScopeError } from \"./errors.js\";\nimport { makeResultAsync } from \"./internal.js\";\n\n/**\n * Run `fn` inside a cancellable Temporal scope. If the workflow (or an\n * ancestor scope) is cancelled while the function is in flight, the\n * resulting ResultAsync resolves to `err(WorkflowCancelledError)`,\n * letting callers handle cancellation explicitly — typically to perform\n * a graceful exit from the current step.\n *\n * Non-cancellation errors thrown by `fn` resolve to\n * `err(WorkflowScopeError)` (with the original error on `cause`) so\n * domain failures surface on the same typed error channel rather than\n * leaking as unhandled rejections.\n *\n * @example\n * ```ts\n * const result = await context.cancellableScope(async () => {\n * return await context.activities.processStep(...);\n * });\n *\n * result.match(\n * (output) => { ... },\n * (error) => {\n * if (error instanceof WorkflowCancelledError) {\n * // graceful exit\n * } else {\n * // error instanceof WorkflowScopeError — domain failure on `cause`\n * }\n * },\n * );\n * ```\n */\nexport function cancellableScope<T>(\n fn: () => T | Promise<T>,\n): ResultAsync<T, WorkflowCancelledError | WorkflowScopeError> {\n const work = async (): Promise<Result<T, WorkflowCancelledError | WorkflowScopeError>> => {\n try {\n // Wrap so synchronous returns satisfy CancellationScope.cancellable's\n // `() => Promise<T>` signature without forcing every caller to write\n // `async () => ...` for purely synchronous bodies.\n const value = await CancellationScope.cancellable(async () => fn());\n return ok(value);\n } catch (error) {\n if (isCancellation(error)) {\n return err(new WorkflowCancelledError(error));\n }\n return err(new WorkflowScopeError(error));\n }\n };\n // makeResultAsync is the shared safety net from `@temporal-contract/contract`\n // — `new ResultAsync(work())` does not catch, so a synchronous throw inside\n // `work` (e.g. a buggy refactor) would escape neverthrow's railway. The\n // catch-all here funnels that back into `err(WorkflowScopeError)` for\n // parity with the in-band path above.\n return makeResultAsync(work, (e) => new WorkflowScopeError(e));\n}\n\n/**\n * Run `fn` inside a non-cancellable Temporal scope. Cancellation requests\n * from outside the scope are ignored for its duration — the idiomatic way\n * to perform cleanup that must not be interrupted (e.g. releasing a\n * resource after a graceful shutdown).\n *\n * Mirrors `cancellableScope`'s `ResultAsync<...>` shape for symmetry; the\n * `err(WorkflowCancelledError)` branch only triggers when cancellation is\n * raised from inside the scope (rare). Non-cancellation errors surface as\n * `err(WorkflowScopeError)`.\n *\n * @example\n * ```ts\n * await context.nonCancellableScope(async () => {\n * await context.activities.releaseResources(...);\n * });\n * ```\n */\nexport function nonCancellableScope<T>(\n fn: () => T | Promise<T>,\n): ResultAsync<T, WorkflowCancelledError | WorkflowScopeError> {\n const work = async (): Promise<Result<T, WorkflowCancelledError | WorkflowScopeError>> => {\n try {\n const value = await CancellationScope.nonCancellable(async () => fn());\n return ok(value);\n } catch (error) {\n if (isCancellation(error)) {\n return err(new WorkflowCancelledError(error));\n }\n return err(new WorkflowScopeError(error));\n }\n };\n return makeResultAsync(work, (e) => new WorkflowScopeError(e));\n}\n","// Top-level helpers for binding signal / query / update handlers to a\n// running workflow. Previously nested inside `declareWorkflow`'s closure\n// (#185), they're hoisted here so the bodies aren't reallocated on each\n// workflow invocation. The typed call-site surface is preserved at the\n// context-assignment site in `workflow.ts` (the arrow that forwards into\n// these helpers carries the contract-derived generic constraints).\n//\n// Internally these are loosely typed (string names, broad `*Definition`\n// inputs); the call sites already do the cast against the typed\n// `WorkflowContext` shape, so the typed-vs-runtime split is the same as\n// it was before the hoist.\nimport type {\n AnyWorkflowDefinition,\n QueryDefinition,\n SignalDefinition,\n UpdateDefinition,\n} from \"@temporal-contract/contract\";\nimport { defineQuery, defineSignal, defineUpdate, setHandler } from \"@temporalio/workflow\";\nimport {\n QueryInputValidationError,\n QueryOutputValidationError,\n SignalInputValidationError,\n UpdateInputValidationError,\n UpdateOutputValidationError,\n} from \"./errors.js\";\nimport { extractHandlerInput } from \"./internal.js\";\nimport type { WorkerInferInput, WorkerInferOutput } from \"./types.js\";\n\n/**\n * Signal handler implementation\n *\n * Processes signal input and can optionally perform asynchronous operations.\n * Should not return a value (signals are fire-and-forget).\n */\nexport type SignalHandlerImplementation<TSignal extends SignalDefinition> = (\n args: WorkerInferInput<TSignal>,\n) => void | Promise<void>;\n\n/**\n * Query handler implementation\n *\n * Processes query input and returns a synchronous response.\n * Must be synchronous to satisfy Temporal's query constraints.\n */\nexport type QueryHandlerImplementation<TQuery extends QueryDefinition> = (\n args: WorkerInferInput<TQuery>,\n) => WorkerInferOutput<TQuery>;\n\n/**\n * Update handler implementation\n *\n * Processes update input and returns a validated response after modifying workflow state.\n * Can perform asynchronous operations.\n */\nexport type UpdateHandlerImplementation<TUpdate extends UpdateDefinition> = (\n args: WorkerInferInput<TUpdate>,\n) => Promise<WorkerInferOutput<TUpdate>>;\n\n/**\n * Bind a typed signal handler to the running workflow. Validates the\n * signal payload against the contract's input schema before invoking the\n * user-supplied handler.\n *\n * The runtime guard against a missing `signals` block — and an unknown\n * signal name within it — covers the union-typed-`workflowName` case\n * where the type system's keyset constraint collapses; without the\n * check, a caller would see `Cannot read properties of undefined`\n * instead of a controlled error.\n */\nexport function bindSignalHandler(\n workflowDefinition: AnyWorkflowDefinition,\n workflowName: string,\n signalName: string,\n handler: SignalHandlerImplementation<SignalDefinition>,\n): void {\n if (!workflowDefinition.signals) {\n throw new Error(\n `Signal \"${signalName}\" cannot be defined: workflow \"${workflowName}\" has no signals in its contract`,\n );\n }\n const signalDef = (workflowDefinition.signals as Record<string, SignalDefinition>)[signalName];\n if (!signalDef) {\n throw new Error(`Signal \"${signalName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const signal = defineSignal(signalName);\n setHandler(signal, async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = await signalDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new SignalInputValidationError(signalName, inputResult.issues);\n }\n await handler(inputResult.value);\n });\n}\n\n/**\n * Bind a typed query handler to the running workflow. Validates input\n * and output against the contract synchronously.\n *\n * Temporal's query API requires a synchronous handler — async\n * validation breaks replay determinism. The handler trips a clear error\n * if the schema library returns a Promise from `validate(...)`, instead\n * of letting the async path silently corrupt query semantics.\n */\nexport function bindQueryHandler(\n workflowDefinition: AnyWorkflowDefinition,\n workflowName: string,\n queryName: string,\n handler: QueryHandlerImplementation<QueryDefinition>,\n): void {\n if (!workflowDefinition.queries) {\n throw new Error(\n `Query \"${queryName}\" cannot be defined: workflow \"${workflowName}\" has no queries in its contract`,\n );\n }\n const queryDef = (workflowDefinition.queries as Record<string, QueryDefinition>)[queryName];\n if (!queryDef) {\n throw new Error(`Query \"${queryName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const query = defineQuery(queryName);\n setHandler(query, (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = queryDef.input[\"~standard\"].validate(input);\n\n if (inputResult instanceof Promise) {\n throw new Error(\n `Query \"${queryName}\" validation must be synchronous. Use a schema library that supports synchronous validation for queries.`,\n );\n }\n if (inputResult.issues) {\n throw new QueryInputValidationError(queryName, inputResult.issues);\n }\n\n const result = handler(inputResult.value);\n\n const outputResult = queryDef.output[\"~standard\"].validate(result);\n if (outputResult instanceof Promise) {\n throw new Error(\n `Query \"${queryName}\" output validation must be synchronous. Use a schema library that supports synchronous validation for queries.`,\n );\n }\n if (outputResult.issues) {\n throw new QueryOutputValidationError(queryName, outputResult.issues);\n }\n\n return outputResult.value;\n });\n}\n\n/**\n * Bind a typed update handler to the running workflow.\n *\n * Input validation runs in Temporal's `validator` slot — a synchronous\n * pre-admission hook. If it throws, Temporal rejects the update *before*\n * appending a workflow history event: clients see\n * `WorkflowUpdateValidationRejectedError` and the workflow's history is\n * unaffected. This is the documented contract for `setHandler`'s\n * `validator` option, and it is strictly better than running validation\n * inside the handler body — which forces Temporal to admit the update,\n * write a history event, and surface a `WorkflowUpdateFailedError` to\n * the client only after the fact.\n *\n * Because the validator slot is synchronous, the input schema must also\n * validate synchronously. Standard Schema is allowed to be async (Zod's\n * `.refine(async)` is the typical case), but we trip a clear error when\n * that happens rather than silently breaking admission semantics — same\n * approach as `bindQueryHandler`. Users who need async input checks\n * should run them inside the handler body and accept the post-admission\n * failure mode, or restructure their schema.\n *\n * Output validation continues to run inside the handler body. Update\n * outputs are *not* admission-gated — the handler must execute to\n * produce a value to validate against — so the async-allowed shape is\n * preserved.\n */\nexport function bindUpdateHandler(\n workflowDefinition: AnyWorkflowDefinition,\n workflowName: string,\n updateName: string,\n handler: UpdateHandlerImplementation<UpdateDefinition>,\n): void {\n if (!workflowDefinition.updates) {\n throw new Error(\n `Update \"${updateName}\" cannot be defined: workflow \"${workflowName}\" has no updates in its contract`,\n );\n }\n const updateDef = (workflowDefinition.updates as Record<string, UpdateDefinition>)[updateName];\n if (!updateDef) {\n throw new Error(`Update \"${updateName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const update = defineUpdate(updateName);\n setHandler(\n update,\n async (...args: unknown[]) => {\n // The validator already accepted the payload — re-parse here so the\n // handler receives the schema's transformed value (Standard Schema\n // may rewrite shapes during validation, e.g. Zod `.transform`). This\n // is sync because the validator already proved the schema is sync;\n // any async result here would mean the schema changed under us,\n // which is a programmer error worth surfacing.\n const input = extractHandlerInput(args);\n const inputResult = updateDef.input[\"~standard\"].validate(input);\n if (inputResult instanceof Promise) {\n throw new Error(\n `Update \"${updateName}\" input validation must be synchronous. Use a schema library that supports synchronous validation for update inputs (Temporal's update validator slot is synchronous).`,\n );\n }\n if (inputResult.issues) {\n // The validator should have caught this; if we reach here, the\n // schema produced different issues on a second call (non-pure\n // validator). Surface it as the same typed error class for\n // consistency.\n throw new UpdateInputValidationError(updateName, inputResult.issues);\n }\n\n const result = await handler(inputResult.value);\n\n const outputResult = await updateDef.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new UpdateOutputValidationError(updateName, outputResult.issues);\n }\n\n return outputResult.value;\n },\n {\n validator: (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = updateDef.input[\"~standard\"].validate(input);\n\n if (inputResult instanceof Promise) {\n throw new Error(\n `Update \"${updateName}\" input validation must be synchronous. Use a schema library that supports synchronous validation for update inputs (Temporal's update validator slot is synchronous).`,\n );\n }\n if (inputResult.issues) {\n throw new UpdateInputValidationError(updateName, inputResult.issues);\n }\n },\n },\n );\n}\n","/**\n * Child workflow types + helpers used by `declareWorkflow`. Split out of\n * `workflow.ts` to keep that file focused on `declareWorkflow` and its\n * `WorkflowContext` type. Not part of the worker package's public exports.\n */\nimport type { AnyWorkflowDefinition, ContractDefinition } from \"@temporal-contract/contract\";\nimport {\n ChildWorkflowHandle,\n ChildWorkflowOptions,\n executeChild,\n startChild,\n} from \"@temporalio/workflow\";\nimport { ResultAsync, type Result, ok, err } from \"neverthrow\";\nimport {\n ChildWorkflowCancelledError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n} from \"./errors.js\";\nimport {\n classifyChildWorkflowError,\n formatChildWorkflowValidationMessage,\n makeResultAsync,\n} from \"./internal.js\";\nimport type { ClientInferInput, ClientInferOutput, WorkerInferInput } from \"./types.js\";\n\n/**\n * Options for starting a child workflow. `taskQueue` and `args` come from\n * the contract; everything else is forwarded to Temporal's\n * `startChild` / `executeChild`.\n */\nexport type TypedChildWorkflowOptions<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n> = Omit<ChildWorkflowOptions, \"taskQueue\" | \"args\"> & {\n args: ClientInferInput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n};\n\n/**\n * Typed handle for a child workflow with neverthrow `ResultAsync` pattern.\n */\nexport type TypedChildWorkflowHandle<TWorkflow extends AnyWorkflowDefinition> = {\n /**\n * Get child workflow result with `ResultAsync` pattern.\n */\n result: () => ResultAsync<\n ClientInferOutput<TWorkflow>,\n ChildWorkflowError | ChildWorkflowCancelledError\n >;\n\n /**\n * Child workflow ID.\n */\n workflowId: string;\n};\n\nasync function validateChildWorkflowOutput<TChildWorkflow extends AnyWorkflowDefinition>(\n childDefinition: TChildWorkflow,\n result: unknown,\n childWorkflowName: string,\n): Promise<Result<ClientInferOutput<TChildWorkflow>, ChildWorkflowError>> {\n const outputResult = await childDefinition.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n return err(\n new ChildWorkflowError(\n formatChildWorkflowValidationMessage(childWorkflowName, \"output\", outputResult.issues),\n ),\n );\n }\n return ok(outputResult.value as ClientInferOutput<TChildWorkflow>);\n}\n\nasync function getAndValidateChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n args: unknown,\n): Promise<\n Result<\n {\n definition: TChildContract[\"workflows\"][TChildWorkflowName];\n validatedInput: WorkerInferInput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n taskQueue: string;\n },\n ChildWorkflowError\n >\n> {\n const childDefinition = childContract.workflows[childWorkflowName];\n\n if (!childDefinition) {\n return err(\n new ChildWorkflowNotFoundError(\n childWorkflowName,\n Object.keys(childContract.workflows) as string[],\n ),\n );\n }\n\n const inputResult = await childDefinition.input[\"~standard\"].validate(args);\n if (inputResult.issues) {\n return err(\n new ChildWorkflowError(\n formatChildWorkflowValidationMessage(childWorkflowName, \"input\", inputResult.issues),\n ),\n );\n }\n\n const validatedInput = inputResult.value as WorkerInferInput<\n TChildContract[\"workflows\"][TChildWorkflowName]\n >;\n\n return ok({\n definition: childDefinition as TChildContract[\"workflows\"][TChildWorkflowName],\n validatedInput,\n taskQueue: childContract.taskQueue,\n });\n}\n\nfunction createTypedChildHandle<TChildWorkflow extends AnyWorkflowDefinition>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handle: ChildWorkflowHandle<any>,\n childDefinition: TChildWorkflow,\n childWorkflowName: string,\n): TypedChildWorkflowHandle<TChildWorkflow> {\n return {\n workflowId: handle.workflowId,\n result: (): ResultAsync<\n ClientInferOutput<TChildWorkflow>,\n ChildWorkflowError | ChildWorkflowCancelledError\n > => {\n const work = async (): Promise<\n Result<ClientInferOutput<TChildWorkflow>, ChildWorkflowError | ChildWorkflowCancelledError>\n > => {\n try {\n const result = await handle.result();\n return validateChildWorkflowOutput(childDefinition, result, childWorkflowName);\n } catch (error) {\n return err(classifyChildWorkflowError(\"result\", error, childWorkflowName));\n }\n };\n return makeResultAsync(\n work,\n (error) =>\n new ChildWorkflowError(\n `Child workflow execution failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n },\n };\n}\n\nexport function createStartChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n): ResultAsync<\n TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n> {\n type Ok = TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>;\n const work = async (): Promise<\n Result<Ok, ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError>\n > => {\n const validationResult = await getAndValidateChildWorkflow(\n childContract,\n childWorkflowName,\n options.args,\n );\n\n if (validationResult.isErr()) {\n return err(validationResult.error);\n }\n\n const { definition: childDefinition, validatedInput, taskQueue } = validationResult.value;\n\n try {\n const { args: _args, ...temporalOptions } = options;\n const handle = await startChild(childWorkflowName, {\n ...temporalOptions,\n taskQueue,\n args: [validatedInput],\n });\n\n const typedHandle = createTypedChildHandle(handle, childDefinition, childWorkflowName) as Ok;\n\n return ok(typedHandle);\n } catch (error) {\n return err(classifyChildWorkflowError(\"startChild\", error, String(childWorkflowName)));\n }\n };\n return makeResultAsync(\n work,\n (error) =>\n new ChildWorkflowError(\n `Failed to start child workflow: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n}\n\nexport function createExecuteChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n): ResultAsync<\n ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n> {\n type Ok = ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n const work = async (): Promise<\n Result<Ok, ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError>\n > => {\n const validationResult = await getAndValidateChildWorkflow(\n childContract,\n childWorkflowName,\n options.args,\n );\n\n if (validationResult.isErr()) {\n return err(validationResult.error);\n }\n\n const { definition: childDefinition, validatedInput, taskQueue } = validationResult.value;\n\n try {\n const { args: _args, ...temporalOptions } = options;\n const result = await executeChild(childWorkflowName, {\n ...temporalOptions,\n taskQueue,\n args: [validatedInput],\n });\n\n const outputValidationResult = await validateChildWorkflowOutput(\n childDefinition,\n result,\n childWorkflowName,\n );\n\n if (outputValidationResult.isErr()) {\n return err(outputValidationResult.error);\n }\n\n return ok(outputValidationResult.value as Ok);\n } catch (error) {\n return err(classifyChildWorkflowError(\"executeChild\", error, String(childWorkflowName)));\n }\n };\n return makeResultAsync(\n work,\n (error) =>\n new ChildWorkflowError(\n `Failed to execute child workflow: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n}\n","/**\n * Activity inference types + the validated-activities proxy used by\n * `declareWorkflow`. Split out of `workflow.ts` to keep that file focused\n * on `declareWorkflow` and its `WorkflowContext` type. Not part of the\n * worker package's public exports.\n */\nimport type {\n ActivityDefinition,\n AnyWorkflowDefinition,\n ContractDefinition,\n} from \"@temporal-contract/contract\";\nimport { ActivityInputValidationError, ActivityOutputValidationError } from \"./errors.js\";\nimport type { ClientInferInput, ClientInferOutput } from \"./types.js\";\n\n/**\n * Activity function signature from workflow execution perspective.\n *\n * Workflows call activities with validated input (z.input parsed) and receive validated output (z.output).\n */\nexport type WorkflowInferActivity<TActivity extends ActivityDefinition> = (\n args: ClientInferInput<TActivity>,\n) => Promise<ClientInferOutput<TActivity>>;\n\n/**\n * All global activities from a contract (workflow execution perspective).\n */\nexport type WorkflowInferActivities<TContract extends ContractDefinition> =\n TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? {\n [K in keyof TContract[\"activities\"]]: WorkflowInferActivity<TContract[\"activities\"][K]>;\n }\n : {};\n\n/**\n * Workflow-specific activities (workflow execution perspective).\n */\nexport type WorkflowInferWorkflowActivities<T extends AnyWorkflowDefinition> =\n T[\"activities\"] extends Record<string, ActivityDefinition>\n ? {\n [K in keyof T[\"activities\"]]: WorkflowInferActivity<T[\"activities\"][K]>;\n }\n : {};\n\n/**\n * All activities available in a workflow context (workflow execution perspective).\n *\n * Combines workflow-specific activities with global contract activities.\n */\nexport type WorkflowInferWorkflowContextActivities<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = WorkflowInferWorkflowActivities<TContract[\"workflows\"][TWorkflowName]> &\n WorkflowInferActivities<TContract>;\n\n/**\n * Wrap the raw activities proxy with input/output validation against the\n * Standard Schema definitions on the contract. The wrapper enforces data\n * integrity at the workflow → activity boundary in addition to the\n * activity-side validation that `declareActivitiesHandler` already runs.\n */\nexport function createValidatedActivities<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n>(\n rawActivities: Record<string, (...args: unknown[]) => Promise<unknown>>,\n workflowActivitiesDefinition: Record<string, ActivityDefinition> | undefined,\n contractActivitiesDefinition: Record<string, ActivityDefinition> | undefined,\n): WorkflowInferWorkflowContextActivities<TContract, TWorkflowName> {\n const validatedActivities = {} as WorkflowInferWorkflowContextActivities<\n TContract,\n TWorkflowName\n >;\n\n // Merge workflow-specific and global contract activities. defineContract\n // guarantees there are no name collisions across scopes, so spread order\n // is just a stable iteration choice (workflow-local last).\n const allActivitiesDefinition = {\n ...contractActivitiesDefinition,\n ...workflowActivitiesDefinition,\n };\n\n for (const [activityName, activityDef] of Object.entries(allActivitiesDefinition)) {\n const rawActivity = rawActivities[activityName];\n\n if (!rawActivity) {\n throw new Error(\n `Activity implementation not found for: \"${activityName}\". ` +\n `Available activities: ${Object.keys(rawActivities).length > 0 ? Object.keys(rawActivities).join(\", \") : \"none\"}`,\n );\n }\n\n (validatedActivities as Record<string, unknown>)[activityName] = async (input: unknown) => {\n const inputResult = await activityDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new ActivityInputValidationError(activityName, inputResult.issues);\n }\n\n const result = await rawActivity(inputResult.value);\n\n const outputResult = await activityDef.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new ActivityOutputValidationError(activityName, outputResult.issues);\n }\n\n return outputResult.value;\n };\n }\n\n return validatedActivities;\n}\n","// Entry point for workflow implementations.\n//\n// Workflows run inside Temporal's deterministic sandbox, which intercepts\n// timers, randomness, and Promise scheduling for replay. neverthrow's\n// `Result`/`ResultAsync` rely only on Promise scheduling, so they replay\n// deterministically alongside Temporal's machinery. Activity code (see\n// activity.ts) uses the same neverthrow API.\nimport type {\n ActivityDefinition,\n ContractDefinition,\n QueryDefinition,\n QueryNamesOf,\n SignalDefinition,\n SignalNamesOf,\n UpdateDefinition,\n UpdateNamesOf,\n} from \"@temporal-contract/contract\";\nimport {\n ChildWorkflowCancelledError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n WorkflowCancelledError,\n WorkflowInputValidationError,\n WorkflowOutputValidationError,\n WorkflowScopeError,\n} from \"./errors.js\";\nimport { cancellableScope, nonCancellableScope } from \"./cancellation.js\";\nimport {\n bindQueryHandler,\n bindSignalHandler,\n bindUpdateHandler,\n type QueryHandlerImplementation,\n type SignalHandlerImplementation,\n type UpdateHandlerImplementation,\n} from \"./handlers.js\";\nimport {\n ClientInferInput,\n ClientInferOutput,\n WorkerInferInput,\n WorkerInferOutput,\n} from \"./types.js\";\nimport type { ResultAsync } from \"neverthrow\";\nimport {\n buildRawActivitiesProxy,\n createContinueAsNew,\n extractHandlerInput,\n type TypedContinueAsNewOptions,\n} from \"./internal.js\";\nimport {\n createStartChildWorkflow,\n createExecuteChildWorkflow,\n type TypedChildWorkflowHandle,\n type TypedChildWorkflowOptions,\n} from \"./child-workflow.js\";\nimport {\n createValidatedActivities,\n type WorkflowInferWorkflowContextActivities,\n} from \"./activities-proxy.js\";\nimport { ActivityOptions, WorkflowInfo, workflowInfo } from \"@temporalio/workflow\";\n\nexport {\n ActivityInputValidationError,\n ActivityOutputValidationError,\n ChildWorkflowCancelledError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n QueryInputValidationError,\n QueryOutputValidationError,\n SignalInputValidationError,\n UpdateInputValidationError,\n UpdateOutputValidationError,\n ValidationError,\n WorkflowCancelledError,\n WorkflowInputValidationError,\n WorkflowOutputValidationError,\n WorkflowScopeError,\n} from \"./errors.js\";\n\n/**\n * Create a typed workflow implementation with automatic validation\n *\n * This wraps a workflow implementation with:\n * - Input/output validation\n * - Typed workflow context with activities\n * - Workflow info access\n *\n * Workflows must be defined in separate files and imported by the Temporal Worker\n * via workflowsPath.\n *\n * @example\n * ```ts\n * // workflows/processOrder.ts\n * import { declareWorkflow } from '@temporal-contract/worker/workflow';\n * import myContract from '../contract';\n *\n * export const processOrder = declareWorkflow({\n * workflowName: 'processOrder',\n * contract: myContract,\n * activityOptions: {\n * startToCloseTimeout: '1 minute',\n * },\n * // Optional: override `activityOptions` for specific activities. Each\n * // entry shallow-merges over the workflow default — the override wins on\n * // every property it specifies, including the whole `retry` block. The\n * // override is Temporal's full `ActivityOptions`, so `taskQueue` works too,\n * // letting you route individual activities to a dedicated worker pool.\n * activityOptionsByName: {\n * chargePayment: {\n * startToCloseTimeout: '5 minutes',\n * retry: { maximumAttempts: 5 },\n * },\n * // Route this activity to a dedicated, concurrency-capped queue.\n * scoreRisk: { taskQueue: 'ml-inference' },\n * },\n * implementation: async (context, args) => {\n * // context.activities: typed activities (workflow + global)\n * // context.info: WorkflowInfo\n *\n * const inventory = await context.activities.validateInventory({\n * orderId: args.orderId,\n * });\n *\n * if (!inventory.available) {\n * return { orderId: args.orderId, status: 'out_of_stock' };\n * }\n *\n * const payment = await context.activities.chargePayment({\n * customerId: args.customerId,\n * amount: 100,\n * });\n *\n * return {\n * orderId: args.orderId,\n * status: payment.success ? 'success' : 'failed',\n * transactionId: payment.transactionId,\n * };\n * },\n * });\n * ```\n *\n * Then in your worker setup:\n * ```ts\n * // worker.ts\n * import { createWorker } from '@temporal-contract/worker/worker';\n * import { activities } from './activities';\n * import myContract from './contract';\n *\n * const worker = await createWorker({\n * contract: myContract,\n * connection,\n * workflowsPath: workflowsPathFromURL(import.meta.url, './workflows.js'),\n * activities,\n * });\n * ```\n */\nexport function declareWorkflow<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n>({\n workflowName,\n contract,\n implementation,\n activityOptions,\n activityOptionsByName,\n}: DeclareWorkflowOptions<TContract, TWorkflowName>): (\n ...args: unknown[]\n) => Promise<WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>> {\n // Get the workflow definition from the contract\n const definition = contract.workflows[workflowName] as TContract[\"workflows\"][TWorkflowName];\n\n // Build the activities proxy *once* at declaration time, not per workflow\n // invocation. Temporal's `proxyActivities` is documented as a module-scope\n // helper — it registers stub functions and may carry bookkeeping\n // (validator pre-registration, payload-converter caching) that breaks if\n // re-invoked on every workflow run. The call depends only on contract-time\n // immutables (`definition.activities`, `contract.activities`,\n // `activityOptions`, `activityOptionsByName`), all of which are available\n // here, so hoisting is safe and deterministic.\n //\n // The validation wrapper (`createValidatedActivities`) is stateless across\n // invocations — it merely closes over the activity definitions and the raw\n // proxy, both immutable — so it is hoisted alongside the proxy. The\n // resulting `contextActivities` object is shared by every workflow run,\n // which is fine because the wrapped activity functions take their input\n // as an argument and validate it per-call (no closed-over per-invocation\n // state).\n //\n // Design note — intentional double-validation:\n // Input and output are validated here (workflow side) AND again inside\n // `declareActivitiesHandler` (activity worker side). This is deliberate:\n //\n // 1. Workflow-side validation catches bad data *before* it crosses the\n // task-queue network boundary, giving an early, descriptive error\n // instead of a confusing deserialization failure inside the activity.\n // 2. Activity-side validation is the authoritative guard, since the\n // activity may be called by other callers that do not use this library.\n //\n // The overhead is minimal relative to the network round-trip.\n let contextActivities: unknown = {};\n\n if (definition.activities || contract.activities) {\n const rawActivities = buildRawActivitiesProxy(\n definition.activities,\n contract.activities,\n activityOptions,\n activityOptionsByName,\n );\n\n contextActivities = createValidatedActivities(\n rawActivities,\n definition.activities,\n contract.activities,\n );\n\n // Shared across workflow invocations after the proxyActivities hoist\n // (PR #211); freeze so user code can't mutate one invocation's view of\n // activities and have it leak into others. The freeze is shallow, which\n // is sufficient because `createValidatedActivities` returns a flat\n // `{ [name]: (input) => Promise<output> }` map — every value is a\n // stateless validation wrapper function, not a nested object users could\n // reach into. The matching `Readonly<...>` on `WorkflowContext.activities`\n // surfaces the immutability at the type level.\n Object.freeze(contextActivities);\n }\n\n const workflowFn = async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n\n // Validate workflow input\n const inputResult = await definition.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new WorkflowInputValidationError(workflowName, inputResult.issues);\n }\n const validatedInput = inputResult.value as WorkerInferInput<\n TContract[\"workflows\"][TWorkflowName]\n >;\n\n // Create workflow context.\n //\n // The defineSignal / defineQuery / defineUpdate arrows forward to the\n // hoisted helpers in `./handlers.ts`. The arrows themselves are thin\n // closures that close over `definition` and `workflowName`; the heavy\n // logic — runtime guards, validation, Temporal `defineSignal/Query/\n // Update` + `setHandler` wiring — lives at module scope so it isn't\n // reallocated on each workflow invocation.\n //\n // The cast at each assignment preserves the typed call-site surface\n // (the `K extends keyof ...` constraints declared on\n // `WorkflowContext.defineSignal/Query/Update`), while the helpers\n // themselves take loosely-typed arguments at the runtime boundary.\n const context: WorkflowContext<TContract, TWorkflowName> = {\n activities: contextActivities as WorkflowInferWorkflowContextActivities<\n TContract,\n TWorkflowName\n >,\n info: workflowInfo(),\n startChildWorkflow: createStartChildWorkflow,\n executeChildWorkflow: createExecuteChildWorkflow,\n cancellableScope,\n nonCancellableScope,\n defineSignal: ((signalName, handler) =>\n bindSignalHandler(\n definition,\n workflowName,\n signalName,\n handler as unknown as SignalHandlerImplementation<SignalDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineSignal\"],\n defineQuery: ((queryName, handler) =>\n bindQueryHandler(\n definition,\n workflowName,\n queryName,\n handler as unknown as QueryHandlerImplementation<QueryDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineQuery\"],\n defineUpdate: ((updateName, handler) =>\n bindUpdateHandler(\n definition,\n workflowName,\n updateName,\n handler as unknown as UpdateHandlerImplementation<UpdateDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineUpdate\"],\n continueAsNew: createContinueAsNew(contract, workflowName) as WorkflowContext<\n TContract,\n TWorkflowName\n >[\"continueAsNew\"],\n };\n\n // Execute workflow (pass validated input as tuple)\n const result = await implementation(context, validatedInput);\n\n // Validate workflow output\n const outputResult = await definition.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new WorkflowOutputValidationError(workflowName, outputResult.issues);\n }\n\n return outputResult.value as WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>;\n };\n\n // Temporal's client.workflow.start(fn, ...) reads `fn.name` to derive the\n // workflow type; without this the anonymous arrow above would surface as \"\".\n Object.defineProperty(workflowFn, \"name\", { value: workflowName, configurable: true });\n\n return workflowFn;\n}\n\n/**\n * Union of all activity names available to a workflow — the workflow-local\n * activities plus the contract's global activities.\n */\ntype ActivityNamesFor<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> =\n | (TContract[\"workflows\"][TWorkflowName][\"activities\"] extends Record<string, ActivityDefinition>\n ? keyof TContract[\"workflows\"][TWorkflowName][\"activities\"] & string\n : never)\n | (TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? keyof TContract[\"activities\"] & string\n : never);\n\n/**\n * Options for declaring a workflow implementation\n */\ntype DeclareWorkflowOptions<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = {\n workflowName: TWorkflowName;\n contract: TContract;\n implementation: WorkflowImplementation<TContract, TWorkflowName>;\n /**\n * Default activity options applied to every activity reachable from this\n * workflow (workflow-local + global) unless overridden in\n * {@link activityOptionsByName}. See Temporal's `ActivityOptions` for the\n * full set of fields:\n * - `startToCloseTimeout`: Maximum time for a single attempt to run\n * - `scheduleToCloseTimeout`: End-to-end timeout including queuing and retries\n * - `scheduleToStartTimeout`: Maximum time the activity can wait in the queue\n * - `heartbeatTimeout`: Time between heartbeats before the activity is considered dead\n * - `retry`: Retry policy for failed activities\n *\n * @example\n * ```ts\n * activityOptions: {\n * startToCloseTimeout: '5m',\n * retry: { maximumAttempts: 3 },\n * }\n * ```\n */\n activityOptions: ActivityOptions;\n /**\n * Per-activity `ActivityOptions` overrides. Each entry shallow-merges over\n * {@link activityOptions} for that activity only — the override wins on\n * every property it specifies, replacing the default value (including the\n * entire nested `retry` block when present, matching Temporal's\n * single-options-per-`proxyActivities`-call semantics).\n *\n * The override value is Temporal's full `ActivityOptions`, so any field is\n * fair game — including `taskQueue`, which lets you route individual\n * activities to dedicated worker pools (e.g. concurrency-capped queues for\n * LLM calls) while the rest of the workflow's activities stay on the default\n * queue. This keeps the Zod-validated typed-activities boundary intact, where\n * a raw `proxyActivities({ taskQueue })` would forfeit it.\n *\n * Activity names are typed against the contract; typos surface as TypeScript\n * errors rather than running silently with the default options.\n *\n * @example Tune timeouts and retries per activity\n * ```ts\n * activityOptions: { startToCloseTimeout: '1 minute' }, // default\n * activityOptionsByName: {\n * chargePayment: {\n * startToCloseTimeout: '5 minutes',\n * retry: { maximumAttempts: 5 },\n * },\n * fastValidation: { startToCloseTimeout: '5 seconds' },\n * },\n * ```\n *\n * @example Route specific activities to a dedicated task queue\n * ```ts\n * activityOptions: { startToCloseTimeout: '10 minutes' }, // default queue\n * activityOptionsByName: {\n * // LLM call → dedicated, concurrency-capped queue.\n * extractLayoutChunk: { taskQueue: 'gemini-pro' },\n * // finalizeLayout, extractImages, … fall through to the default queue.\n * },\n * ```\n */\n activityOptionsByName?: Partial<\n Record<ActivityNamesFor<TContract, TWorkflowName>, ActivityOptions>\n >;\n};\n\n/**\n * Workflow implementation function\n *\n * Receives a workflow context (with typed activities and utilities) and validated input arguments.\n * Returns the workflow output which will be validated against the contract schema.\n */\ntype WorkflowImplementation<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = (\n context: WorkflowContext<TContract, TWorkflowName>,\n args: WorkerInferInput<TContract[\"workflows\"][TWorkflowName]>,\n) => Promise<WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>>;\n\n/**\n * Workflow execution context providing typed activities, workflow info, and interaction handlers\n *\n * Provides access to:\n * - Typed activities (both workflow-specific and global)\n * - Workflow metadata and execution info\n * - Signal, query, and update handler registration\n * - Child workflow execution capabilities\n */\ntype WorkflowContext<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = {\n activities: Readonly<WorkflowInferWorkflowContextActivities<TContract, TWorkflowName>>;\n info: WorkflowInfo;\n\n /**\n * Define a signal handler within the workflow implementation\n * Allows the signal handler to access workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineSignal('increment', async (signalArgs) => {\n * currentValue += signalArgs.amount;\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineSignal: <K extends SignalNamesOf<TContract[\"workflows\"][TWorkflowName]>>(\n signalName: K,\n handler: SignalHandlerImplementation<\n NonNullable<TContract[\"workflows\"][TWorkflowName][\"signals\"]> extends Record<\n string,\n SignalDefinition\n >\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"signals\"]>[K] extends SignalDefinition\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"signals\"]>[K]\n : never\n : never\n >,\n ) => void;\n\n /**\n * Define a query handler within the workflow implementation\n * Allows the query handler to access workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineQuery('getCurrentValue', () => {\n * return { value: currentValue };\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineQuery: <K extends QueryNamesOf<TContract[\"workflows\"][TWorkflowName]>>(\n queryName: K,\n handler: QueryHandlerImplementation<\n NonNullable<TContract[\"workflows\"][TWorkflowName][\"queries\"]> extends Record<\n string,\n QueryDefinition\n >\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"queries\"]>[K] extends QueryDefinition\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"queries\"]>[K]\n : never\n : never\n >,\n ) => void;\n\n /**\n * Define an update handler within the workflow implementation\n * Allows the update handler to access and modify workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineUpdate('multiply', async (updateArgs) => {\n * currentValue *= updateArgs.factor;\n * return { newValue: currentValue };\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineUpdate: <K extends UpdateNamesOf<TContract[\"workflows\"][TWorkflowName]>>(\n updateName: K,\n handler: UpdateHandlerImplementation<\n NonNullable<TContract[\"workflows\"][TWorkflowName][\"updates\"]> extends Record<\n string,\n UpdateDefinition\n >\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"updates\"]>[K] extends UpdateDefinition\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"updates\"]>[K]\n : never\n : never\n >,\n ) => void;\n\n /**\n * Start a child workflow and return a typed handle with ResultAsync pattern\n *\n * Supports both same-contract and cross-contract child workflows:\n * - Same contract: Pass workflowName from current contract\n * - Cross-contract: Pass contract and workflowName to invoke workflows from other workers\n *\n * @example\n * ```ts\n * // Same contract child workflow\n * const childResult = await context.startChildWorkflow(myContract, 'processPayment', {\n * workflowId: 'payment-123',\n * args: { amount: 100 }\n * });\n *\n * // Cross-contract child workflow (from another worker)\n * const otherResult = await context.startChildWorkflow(otherContract, 'sendNotification', {\n * workflowId: 'notification-123',\n * args: { message: 'Hello' }\n * });\n *\n * childResult.match(\n * async (handle) => {\n * const result = await handle.result();\n * // ... handle result\n * },\n * (error) => console.error('Failed to start:', error),\n * );\n * ```\n */\n startChildWorkflow: <\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n >(\n contract: TChildContract,\n workflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n ) => ResultAsync<\n TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n >;\n\n /**\n * Execute a child workflow (start and wait for result) with ResultAsync pattern\n *\n * Supports both same-contract and cross-contract child workflows:\n * - Same contract: Pass workflowName from current contract\n * - Cross-contract: Pass contract and workflowName to invoke workflows from other workers\n *\n * @example\n * ```ts\n * // Same contract child workflow\n * const result = await context.executeChildWorkflow(myContract, 'processPayment', {\n * workflowId: 'payment-123',\n * args: { amount: 100 }\n * });\n *\n * // Cross-contract child workflow (from another worker)\n * const otherResult = await context.executeChildWorkflow(otherContract, 'sendNotification', {\n * workflowId: 'notification-123',\n * args: { message: 'Hello' }\n * });\n *\n * result.match(\n * (output) => console.log('Payment processed:', output),\n * (error) => console.error('Processing failed:', error),\n * );\n * ```\n */\n executeChildWorkflow: <\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n >(\n contract: TChildContract,\n workflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n ) => ResultAsync<\n ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n >;\n\n /**\n * Run `fn` inside a cancellable Temporal scope. If the workflow (or an\n * ancestor scope) is cancelled while `fn` is in flight, the resulting\n * ResultAsync resolves to `err(WorkflowCancelledError)` instead of\n * rejecting — letting callers handle cancellation explicitly, typically\n * to perform a graceful exit from the current step.\n *\n * Non-cancellation errors thrown by `fn` resolve to\n * `err(WorkflowScopeError)` (with the original error preserved on\n * `cause`). Both failure modes ride neverthrow's railway, so\n * `result.match(...)` is exhaustive — nothing escapes as an unhandled\n * rejection.\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * const result = await context.cancellableScope(async () => {\n * return context.activities.processStep(args);\n * });\n *\n * if (result.isErr()) {\n * if (result.error instanceof WorkflowCancelledError) {\n * // workflow was cancelled — perform cleanup that must not be cancelled:\n * await context.nonCancellableScope(async () => {\n * await context.activities.releaseResources(args);\n * });\n * return { status: \"cancelled\" };\n * }\n * // result.error instanceof WorkflowScopeError — domain failure\n * return { status: \"failed\" };\n * }\n *\n * return { status: \"ok\" };\n * }\n * ```\n */\n cancellableScope: <T>(\n fn: () => T | Promise<T>,\n ) => ResultAsync<T, WorkflowCancelledError | WorkflowScopeError>;\n\n /**\n * Run `fn` inside a non-cancellable Temporal scope. Cancellation requests\n * from outside the scope are ignored for its duration — the idiomatic way\n * to perform cleanup work that must not be interrupted.\n *\n * Returns the same `ResultAsync<...>` shape as\n * {@link WorkflowContext.cancellableScope} for symmetry; the\n * `err(WorkflowCancelledError)` branch only triggers when cancellation is\n * raised from *inside* the scope, which is rare. Non-cancellation errors\n * surface as `err(WorkflowScopeError)`.\n */\n nonCancellableScope: <T>(\n fn: () => T | Promise<T>,\n ) => ResultAsync<T, WorkflowCancelledError | WorkflowScopeError>;\n\n /**\n * Continue this workflow execution as a new run, optionally with a different\n * workflow type from another contract.\n *\n * Args are validated against the destination workflow's input schema before\n * Temporal's `continueAsNew` is invoked. On validation failure, throws a\n * {@link WorkflowInputValidationError}; on success, Temporal terminates the\n * current execution and starts a fresh one — which is why the function\n * never returns normally (`Promise<never>`).\n *\n * Idiomatic usage:\n *\n * @example\n * ```ts\n * // Same workflow, validated args\n * implementation: async (context, args) => {\n * if (shouldRoll(args)) {\n * return context.continueAsNew({ ...args, retryCount: args.retryCount + 1 });\n * }\n * return ...;\n * }\n *\n * // Cross-contract continueAsNew (less common — taskQueue and workflow type\n * // come from the other contract)\n * return context.continueAsNew(otherContract, \"otherWorkflow\", { ...newArgs });\n * ```\n */\n continueAsNew: {\n /** Same-workflow continuation — args typed against this workflow's input. */\n (\n args: ClientInferInput<TContract[\"workflows\"][TWorkflowName]>,\n options?: TypedContinueAsNewOptions,\n ): Promise<never>;\n /** Cross-contract continuation — args typed against the destination workflow. */\n <\n TOtherContract extends ContractDefinition,\n TOtherWorkflowName extends keyof TOtherContract[\"workflows\"] & string,\n >(\n contract: TOtherContract,\n workflowName: TOtherWorkflowName,\n args: ClientInferInput<TOtherContract[\"workflows\"][TOtherWorkflowName]>,\n options?: TypedContinueAsNewOptions,\n ): Promise<never>;\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,iBACd,IAC6D;CAC7D,MAAM,OAAO,YAA6E;EACxF,IAAI;GAKF,OAAO,GAAG,MADU,kBAAkB,YAAY,YAAY,GAAG,CAAC,CACnD;EACjB,SAAS,OAAO;GACd,IAAI,eAAe,KAAK,GACtB,OAAO,IAAI,IAAI,uBAAuB,KAAK,CAAC;GAE9C,O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;CACjC;CAEA,MAAM,aAAa,OAAO,GAAG,SAAoB;EAC/C,MAAM,QAAQ,oBAAoB,IAAI;EAGtC,MAAM,cAAc,MAAM,WAAW,MAAM,YAAY,CAAC,SAAS,KAAK;EACtE,IAAI,YAAY,QACd,MAAM,IAAI,6BAA6B,cAAc,YAAY,MAAM;EAEzE,MAAM,iBAAiB,YAAY;EAuDnC,MAAM,SAAS,MAAM,eAAe;GArClC,YAAY;GAIZ,MAAM,aAAa;GACnB,oBAAoB;GACpB,sBAAsB;GACtB;GACA;GACA,gBAAgB,YAAY,YAC1B,kBACE,YACA,cACA,YACA,OACF;GACF,eAAe,WAAW,YACxB,iBACE,YACA,cACA,WACA,OACF;GACF,gBAAgB,YAAY,YAC1B,kBACE,YACA,cACA,YACA,OACF;GACF,eAAe,oBAAoB,UAAU,YAAY;EAOjB,GAAG,cAAc;EAG3D,MAAM,eAAe,MAAM,WAAW,OAAO,YAAY,CAAC,SAAS,MAAM;EACzE,IAAI,aAAa,QACf,MAAM,IAAI,8BAA8B,cAAc,aAAa,MAAM;EAG3E,OAAO,aAAa;CACtB;CAIA,OAAO,eAAe,YAAY,QAAQ;EAAE,OAAO;EAAc,cAAc;CAAK,CAAC;CAErF,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@temporal-contract/worker",
3
- "version": "2.3.1",
3
+ "version": "2.4.0",
4
4
  "description": "Worker utilities with neverthrow Result/ResultAsync for implementing temporal-contract workflows and activities",
5
5
  "keywords": [
6
6
  "contract",
@@ -60,14 +60,14 @@
60
60
  },
61
61
  "dependencies": {
62
62
  "@standard-schema/spec": "1.1.0",
63
- "@temporal-contract/contract": "2.3.1"
63
+ "@temporal-contract/contract": "2.4.0"
64
64
  },
65
65
  "devDependencies": {
66
- "@temporalio/client": "1.18.0",
67
- "@temporalio/common": "1.18.0",
68
- "@temporalio/worker": "1.18.0",
69
- "@temporalio/workflow": "1.18.0",
70
- "@types/node": "24.13.1",
66
+ "@temporalio/client": "1.18.1",
67
+ "@temporalio/common": "1.18.1",
68
+ "@temporalio/worker": "1.18.1",
69
+ "@temporalio/workflow": "1.18.1",
70
+ "@types/node": "24.13.2",
71
71
  "@vitest/coverage-v8": "4.1.8",
72
72
  "neverthrow": "8.2.0",
73
73
  "tsdown": "0.22.2",
@@ -76,8 +76,8 @@
76
76
  "typescript": "6.0.3",
77
77
  "vitest": "4.1.8",
78
78
  "zod": "4.4.3",
79
- "@temporal-contract/client": "2.3.1",
80
- "@temporal-contract/testing": "2.3.1",
79
+ "@temporal-contract/testing": "2.4.0",
80
+ "@temporal-contract/client": "2.4.0",
81
81
  "@temporal-contract/tsconfig": "1.0.0",
82
82
  "@temporal-contract/typedoc": "0.1.0"
83
83
  },
@@ -87,6 +87,9 @@
87
87
  "@temporalio/workflow": "^1",
88
88
  "neverthrow": "^8"
89
89
  },
90
+ "engines": {
91
+ "node": ">=22.19.0"
92
+ },
90
93
  "scripts": {
91
94
  "build": "tsdown src/activity.ts src/worker.ts src/workflow.ts --format cjs,esm --dts --clean",
92
95
  "build:docs": "typedoc",
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors-BP48RaOI.d.cts","names":[],"sources":["../src/types.ts","../src/errors.ts"],"mappings":";;;;;;AAOA;;KAAY,gBAAA;EAA6B,KAAA,EAAO,SAAA;AAAA,KAAe,gBAAA,CAAiB,WAAA,CAC9E,CAAA;;;;;KAOU,iBAAA;EAA8B,MAAA,EAAQ,SAAA;AAAA,KAAe,gBAAA,CAAiB,UAAA,CAChF,CAAA;;;;AARC;KAeS,gBAAA;EAA6B,KAAA,EAAO,SAAA;AAAA,KAAe,gBAAA,CAAiB,UAAA,CAC9E,CAAA;;;;;KAOU,iBAAA;EAA8B,MAAA,EAAQ,SAAA;AAAA,KAAe,gBAAA,CAAiB,WAAA,CAChF,CAAA;;;;;;uBC1Ba,WAAA,SAAoB,KAAK;EAAA,UAC7B,WAAA,CAAa,OAAA,UAAiB,KAAA;AAAA;;;;cA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src/internal.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { summarizeIssues } from \"@temporal-contract/contract\";\n\n/**\n * Base error class for worker errors\n */\nabstract class WorkerError extends Error {\n protected constructor(message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"WorkerError\";\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error thrown when an activity definition is not found in the contract\n */\nexport class ActivityDefinitionNotFoundError extends WorkerError {\n constructor(\n public readonly activityName: string,\n public readonly availableDefinitions: readonly string[] = [],\n ) {\n const available = availableDefinitions.length > 0 ? availableDefinitions.join(\", \") : \"none\";\n super(\n `Activity definition not found for: \"${activityName}\". Available activities: ${available}`,\n );\n this.name = \"ActivityDefinitionNotFoundError\";\n }\n}\n\n/**\n * Error thrown when activity input validation fails\n */\nexport class ActivityInputValidationError extends WorkerError {\n constructor(\n public readonly activityName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Activity \"${activityName}\" input validation failed: ${message}`);\n this.name = \"ActivityInputValidationError\";\n }\n}\n\n/**\n * Error thrown when activity output validation fails\n */\nexport class ActivityOutputValidationError extends WorkerError {\n constructor(\n public readonly activityName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Activity \"${activityName}\" output validation failed: ${message}`);\n this.name = \"ActivityOutputValidationError\";\n }\n}\n\n/**\n * Error thrown when workflow input validation fails\n */\nexport class WorkflowInputValidationError extends WorkerError {\n constructor(\n public readonly workflowName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Workflow \"${workflowName}\" input validation failed: ${message}`);\n this.name = \"WorkflowInputValidationError\";\n }\n}\n\n/**\n * Error thrown when workflow output validation fails\n */\nexport class WorkflowOutputValidationError extends WorkerError {\n constructor(\n public readonly workflowName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Workflow \"${workflowName}\" output validation failed: ${message}`);\n this.name = \"WorkflowOutputValidationError\";\n }\n}\n\n/**\n * Error thrown when signal input validation fails\n */\nexport class SignalInputValidationError extends WorkerError {\n constructor(\n public readonly signalName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Signal \"${signalName}\" input validation failed: ${message}`);\n this.name = \"SignalInputValidationError\";\n }\n}\n\n/**\n * Error thrown when query input validation fails\n */\nexport class QueryInputValidationError extends WorkerError {\n constructor(\n public readonly queryName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Query \"${queryName}\" input validation failed: ${message}`);\n this.name = \"QueryInputValidationError\";\n }\n}\n\n/**\n * Error thrown when query output validation fails\n */\nexport class QueryOutputValidationError extends WorkerError {\n constructor(\n public readonly queryName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Query \"${queryName}\" output validation failed: ${message}`);\n this.name = \"QueryOutputValidationError\";\n }\n}\n\n/**\n * Error thrown when update input validation fails\n */\nexport class UpdateInputValidationError extends WorkerError {\n constructor(\n public readonly updateName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Update \"${updateName}\" input validation failed: ${message}`);\n this.name = \"UpdateInputValidationError\";\n }\n}\n\n/**\n * Error thrown when update output validation fails\n */\nexport class UpdateOutputValidationError extends WorkerError {\n constructor(\n public readonly updateName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Update \"${updateName}\" output validation failed: ${message}`);\n this.name = \"UpdateOutputValidationError\";\n }\n}\n\n/**\n * Error thrown when a child workflow is not found in the contract\n */\nexport class ChildWorkflowNotFoundError extends WorkerError {\n constructor(\n public readonly workflowName: string,\n public readonly availableWorkflows: readonly string[] = [],\n ) {\n const available = availableWorkflows.length > 0 ? availableWorkflows.join(\", \") : \"none\";\n super(`Child workflow not found: \"${workflowName}\". Available workflows: ${available}`);\n this.name = \"ChildWorkflowNotFoundError\";\n }\n}\n\n/**\n * Generic error for child workflow operations.\n *\n * When the child execution itself fails (Temporal's `ChildWorkflowFailure`),\n * `cause` is set to the *unwrapped* underlying failure (`ApplicationFailure`,\n * `TimeoutFailure`, `TerminatedFailure`, etc.) lifted from Temporal's wrapper —\n * mirroring the client-side `WorkflowFailedError.cause` behavior, so callers\n * can branch on the failure category in one step instead of unwrapping twice.\n */\nexport class ChildWorkflowError extends WorkerError {\n constructor(message: string, cause?: unknown) {\n super(message, cause);\n this.name = \"ChildWorkflowError\";\n }\n}\n\n/**\n * Discriminated variant of {@link ChildWorkflowError} surfaced when a child\n * workflow operation (start, execute, or wait-for-result) was cancelled —\n * either because the parent workflow itself was cancelled, the child was\n * explicitly cancelled, or its enclosing cancellation scope was. Detected via\n * `@temporalio/workflow`'s `isCancellation(...)`, which sees through nested\n * `ChildWorkflowFailure` / `CancelledFailure` chains.\n *\n * Extends {@link ChildWorkflowError} so existing `instanceof ChildWorkflowError`\n * checks still match cancellation, while `instanceof ChildWorkflowCancelledError`\n * lets call sites narrow further when they need to branch on cancellation\n * explicitly without inspecting `error.cause` against a Temporal SDK class —\n * the worker-side analogue of the client-side cause-forwarding pattern.\n */\nexport class ChildWorkflowCancelledError extends ChildWorkflowError {\n constructor(\n public readonly workflowName: string,\n cause?: unknown,\n ) {\n super(`Child workflow \"${workflowName}\" was cancelled`, cause);\n this.name = \"ChildWorkflowCancelledError\";\n }\n}\n\n/**\n * Error surfaced in the `err(...)` branch of a `ResultAsync` when a typed\n * cancellation scope is cancelled via Temporal's cancellation propagation.\n * Returned by both `context.cancellableScope` (when the workflow or an\n * ancestor scope cancels) and `context.nonCancellableScope` (when\n * cancellation is raised from inside the scope). Distinct from arbitrary\n * thrown errors so call sites can branch on cancellation explicitly.\n *\n * Non-cancellation errors thrown inside a scope surface as a sibling\n * {@link WorkflowScopeError} on the same `err(...)` channel, so callers can\n * use `instanceof` to discriminate without falling back to `try/catch`.\n */\nexport class WorkflowCancelledError extends WorkerError {\n constructor(cause?: unknown) {\n super(\"Workflow cancellation scope was cancelled\", cause);\n this.name = \"WorkflowCancelledError\";\n }\n}\n\n/**\n * Error surfaced in the `err(...)` branch of a `ResultAsync` when the\n * function passed to `cancellableScope` / `nonCancellableScope` throws a\n * non-cancellation error.\n *\n * The original error is preserved on `cause` so call sites can introspect\n * it without losing identity:\n *\n * @example\n * ```ts\n * const result = await context.cancellableScope(async () => {\n * return await context.activities.processStep(args);\n * });\n *\n * if (result.isErr()) {\n * if (result.error instanceof WorkflowCancelledError) {\n * // graceful cancellation\n * } else if (result.error instanceof WorkflowScopeError) {\n * // domain error — `result.error.cause` is the original throwable\n * }\n * }\n * ```\n *\n * Introduced so the scope helpers route every failure through neverthrow's\n * railway. Previously, non-cancellation errors were re-thrown out of the\n * helper, which became a `ResultAsync` rejection (`new ResultAsync(promise)`\n * does not catch) — they leaked as unhandled rejections rather than\n * surfacing on the typed error channel callers actually inspect.\n */\nexport class WorkflowScopeError extends WorkerError {\n constructor(cause: unknown) {\n const message =\n cause instanceof Error\n ? `Workflow cancellation scope caught a non-cancellation error: ${cause.message}`\n : \"Workflow cancellation scope caught a non-cancellation error\";\n super(message, cause);\n this.name = \"WorkflowScopeError\";\n }\n}\n","/**\n * Internal helpers shared across the worker package's entry points.\n *\n * Not part of the public API — this module is not listed in the package's\n * `exports` map, so consumers can't import from `@temporal-contract/worker/internal`.\n * In-package tests import it directly via relative path.\n */\nimport { isCancellation, makeContinueAsNewFunc, proxyActivities } from \"@temporalio/workflow\";\nimport type { ActivityOptions, ContinueAsNewOptions } from \"@temporalio/workflow\";\nimport { ChildWorkflowFailure } from \"@temporalio/common\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport {\n type ActivityDefinition,\n type ContractDefinition,\n summarizeIssues,\n} from \"@temporal-contract/contract\";\nimport {\n ChildWorkflowCancelledError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n WorkflowInputValidationError,\n} from \"./errors.js\";\n\n/**\n * Build the message attached to a `ChildWorkflowError` for input/output\n * validation failures. Centralized so the worker formats child-workflow\n * validation diagnostics identically across call sites. Composes the shared\n * `summarizeIssues` from `@temporal-contract/contract`.\n */\nexport function formatChildWorkflowValidationMessage(\n workflowName: string,\n direction: \"input\" | \"output\",\n issues: ReadonlyArray<StandardSchemaV1.Issue>,\n): string {\n return `Child workflow \"${workflowName}\" ${direction} validation failed: ${summarizeIssues(issues)}`;\n}\n\n// Re-export the shared `_internal_makeResultAsync` helper from the contract\n// package so worker call sites can wrap their `() => Promise<Result<T, E>>`\n// work functions identically to the client side. This closes the\n// `new ResultAsync(work())` gap — the bare constructor doesn't catch\n// rejections, so a synchronous throw or a rejected promise from `work()`\n// would otherwise escape neverthrow's railway as an unhandled rejection.\nexport { _internal_makeResultAsync as makeResultAsync } from \"@temporal-contract/contract/result-async\";\n\n/**\n * Extract the single payload from a Temporal handler's `...args` array.\n *\n * Temporal invokes handlers with whatever was passed via `args: [...]` at the\n * call site. The typed-contract layer always sends `args: [validatedInput]`,\n * so the common case is a one-element array containing the wrapped input.\n *\n * If a non-typed-contract caller passes multiple positional arguments\n * (`args: [a, b, c]`), we surface the whole array as the input — the schema\n * will then reject it unless the contract specifically modeled a tuple.\n */\nexport function extractHandlerInput(args: unknown[]): unknown {\n return args.length === 1 ? args[0] : args;\n}\n\ntype ActivityFn = (...args: unknown[]) => Promise<unknown>;\n\n/**\n * Build the raw `Record<name, fn>` proxy of activities for a workflow,\n * applying per-activity `ActivityOptions` overrides where requested.\n *\n * **Fast path (no overrides):** a single `proxyActivities(defaultOptions)`\n * call is made and returned directly. The proxy synthesizes a function for\n * any property access by name, so downstream code that looks up\n * `proxy[activityName]` works identically to before.\n *\n * **Override path:** one extra `proxyActivities(merged)` call is made *only*\n * for each activity that has an override. Activities without an entry keep\n * using the single default proxy. The result is a `Proxy` that returns the\n * override-bound function for named keys and falls back to the default proxy\n * for everything else — so the per-execution overhead scales with the number\n * of overrides, not the number of activities.\n *\n * Per-override merge is shallow: the override's properties replace the\n * default's, including the entire nested `retry` block. This matches\n * Temporal's \"one ActivityOptions per `proxyActivities` call\" semantics.\n */\nexport function buildRawActivitiesProxy(\n workflowActivities: Record<string, ActivityDefinition> | undefined,\n contractActivities: Record<string, ActivityDefinition> | undefined,\n defaultOptions: ActivityOptions,\n overrides: Partial<Record<string, ActivityOptions>> | undefined,\n): Record<string, ActivityFn> {\n const defaultProxy = proxyActivities<Record<string, ActivityFn>>(defaultOptions);\n\n // Fast path: no overrides → use the single default proxy directly.\n // (`createValidatedActivities` accesses by name, so the Proxy's get-trap\n // suffices; we don't need an enumerable map.)\n const overrideEntries = overrides\n ? Object.entries(overrides).filter(\n (entry): entry is [string, ActivityOptions] => entry[1] !== undefined,\n )\n : [];\n if (overrideEntries.length === 0) {\n return defaultProxy;\n }\n\n // Validate every override key corresponds to a declared activity.\n // Without this, a typo at runtime (or a stale options bag from a renamed\n // activity) silently builds a proxy for a non-existent activity.\n const declared = new Set<string>([\n ...Object.keys(workflowActivities ?? {}),\n ...Object.keys(contractActivities ?? {}),\n ]);\n for (const [name] of overrideEntries) {\n if (!declared.has(name)) {\n throw new Error(\n `activityOptionsByName entry \"${name}\" does not match any declared activity. Available: ${[...declared].join(\", \") || \"none\"}.`,\n );\n }\n }\n\n // Override path: build one proxy per override; combine with the default\n // proxy via a get-trap so unmatched keys still get the default options.\n const overriddenFns: Record<string, ActivityFn> = {};\n for (const [name, override] of overrideEntries) {\n const mergedOptions: ActivityOptions = { ...defaultOptions, ...override };\n const overrideProxy = proxyActivities<Record<string, ActivityFn>>(mergedOptions);\n const fn = overrideProxy[name];\n if (fn !== undefined) {\n overriddenFns[name] = fn;\n }\n }\n\n return new Proxy(overriddenFns, {\n get(target, prop) {\n if (typeof prop !== \"string\") return undefined;\n return target[prop] ?? defaultProxy[prop];\n },\n });\n}\n\n/**\n * Continue-as-new options the typed wrapper does not own. `workflowType` and\n * `taskQueue` are derived from the contract; everything else is forwarded to\n * Temporal's `makeContinueAsNewFunc`.\n */\nexport type TypedContinueAsNewOptions = Omit<ContinueAsNewOptions, \"workflowType\" | \"taskQueue\">;\n\n/**\n * Build the typed `continueAsNew` function bound to the running workflow's\n * contract. Two overloads — same-workflow and cross-contract — share one\n * implementation; the public type signature lives on `WorkflowContext` so\n * call sites are type-safe.\n *\n * Validation runs *before* Temporal's `makeContinueAsNewFunc(...)` is invoked.\n * On failure, throws a `WorkflowInputValidationError` (matching the behaviour\n * of `declareWorkflow`'s incoming-input validation), which surfaces back to\n * Temporal as a workflow failure rather than silently proceeding with an\n * invalid run.\n *\n * Temporal's `continueAsNew` never returns — it throws a `ContinueAsNew`\n * exception that the runtime intercepts. The returned function preserves\n * `Promise<never>` to encode that.\n *\n * @internal\n */\nexport function createContinueAsNew(\n currentContract: ContractDefinition,\n currentWorkflowName: string | number | symbol,\n) {\n return async function continueAsNew(\n arg1: unknown,\n arg2?: unknown,\n arg3?: unknown,\n arg4?: TypedContinueAsNewOptions,\n ): Promise<never> {\n // Cross-contract dispatch is only triggered when the call signature\n // unambiguously matches `(contract, workflowName, args, options?)`:\n //\n // 1. `arg1` is a non-null object that *looks like* a contract — it has a\n // string `taskQueue` and a non-null `workflows` object.\n // 2. `arg2` is a string — the destination workflow name.\n // 3. `arg2` resolves to a workflow definition on `arg1.workflows` with a\n // Standard Schema `input.~standard.validate` function.\n //\n // Without (2)+(3), a same-workflow input that happens to have `taskQueue`\n // and `workflows` keys (or `workflows = null`, where `typeof === \"object\"`)\n // would be silently misclassified. The full triple of structural checks\n // makes the false-positive surface vanishingly small.\n const isCrossContract = looksLikeCrossContractCall(arg1, arg2);\n\n let targetContract: ContractDefinition;\n let targetName: string;\n let rawArgs: unknown;\n let options: TypedContinueAsNewOptions | undefined;\n\n if (isCrossContract) {\n targetContract = arg1 as ContractDefinition;\n targetName = arg2 as string;\n rawArgs = arg3;\n options = arg4;\n } else {\n targetContract = currentContract;\n targetName = String(currentWorkflowName);\n rawArgs = arg1;\n options = arg2 as TypedContinueAsNewOptions | undefined;\n }\n\n const targetDef = targetContract.workflows[targetName];\n if (!targetDef) {\n throw new WorkflowInputValidationError(targetName, [\n {\n message: `continueAsNew target workflow \"${targetName}\" is not declared on the supplied contract.`,\n },\n ]);\n }\n\n const inputResult = await targetDef.input[\"~standard\"].validate(rawArgs);\n if (inputResult.issues) {\n throw new WorkflowInputValidationError(targetName, inputResult.issues);\n }\n\n // workflowType/taskQueue come from the destination contract; user\n // options are spread last so power users can override (e.g. retry,\n // memo). The public TypedContinueAsNewOptions type Omits workflowType\n // and taskQueue so this isn't a footgun on the typed call path.\n const fn = makeContinueAsNewFunc({\n workflowType: targetName,\n taskQueue: targetContract.taskQueue,\n ...options,\n });\n\n await fn(inputResult.value);\n // Unreachable — Temporal's continueAsNew throws to terminate the run.\n /* c8 ignore next */\n return undefined as never;\n };\n}\n\n/**\n * Structural check: does `(arg1, arg2)` look like the\n * `(contract, workflowName, ...)` cross-contract overload of `continueAsNew`?\n *\n * Returns `true` only when:\n * 1. `arg1` is a non-null object with a string `taskQueue` and a non-null\n * object `workflows` (handles `workflows: null`, where\n * `typeof null === \"object\"`).\n * 2. `arg2` is a string.\n *\n * Both halves matter. A same-workflow input that happens to contain\n * `taskQueue` and `workflows` keys would otherwise be misclassified — but\n * none of the same-workflow signatures (`continueAsNew(args)`,\n * `continueAsNew(args, options)`) accept a string as `arg2`, so the\n * second check makes the false-positive surface vanishingly small.\n *\n * We deliberately do *not* check that `arg1.workflows[arg2]` is a valid\n * workflow definition. If it isn't, the dispatcher falls through to the\n * `targetContract.workflows[targetName]` lookup which throws a clear\n * \"target workflow X is not declared\" error — better than silently\n * misrouting a typo back to the current workflow.\n */\nfunction looksLikeCrossContractCall(arg1: unknown, arg2: unknown): boolean {\n if (typeof arg1 !== \"object\" || arg1 === null) return false;\n if (typeof arg2 !== \"string\") return false;\n const candidate = arg1 as Record<string, unknown>;\n if (typeof candidate[\"taskQueue\"] !== \"string\") return false;\n const workflows = candidate[\"workflows\"];\n return typeof workflows === \"object\" && workflows !== null;\n}\n\n/**\n * Map a thrown error from `startChild` / `executeChild` / `handle.result()`\n * (the worker-side child-workflow API) into the discriminated union surfaced\n * by the typed worker. Mirrors the client's `classifyResultError`:\n *\n * - Cancellation (detected via `@temporalio/workflow`'s `isCancellation`,\n * which sees through nested `ChildWorkflowFailure → CancelledFailure`\n * chains) → {@link ChildWorkflowCancelledError}, with the original error\n * carried as `cause`.\n * - Temporal's `ChildWorkflowFailure` (a wrapper whose actionable failure —\n * `ApplicationFailure`, `TimeoutFailure`, `TerminatedFailure`, etc. — lives\n * on its `cause` field) → {@link ChildWorkflowError}, with that *inner*\n * cause forwarded so consumers can match `err.cause instanceof\n * ApplicationFailure` without unwrapping twice. (If the wrapper's `cause`\n * is `undefined`, the wrapper itself is forwarded so identity is\n * preserved.)\n * - Anything else → {@link ChildWorkflowError} carrying the raw thrown value\n * as `cause`.\n *\n * The `operation` discriminator drives the human-readable error message so\n * call sites don't have to format their own.\n *\n * Note: `ChildWorkflowNotFoundError` is *not* produced here — it's only\n * thrown from the input-validation path when the workflow definition is\n * missing on the contract, before any Temporal call happens.\n */\nexport function classifyChildWorkflowError(\n operation: \"startChild\" | \"executeChild\" | \"result\",\n error: unknown,\n childWorkflowName: string,\n): ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError {\n // Cancellation takes priority: a cancelled child surfaces as a\n // `ChildWorkflowFailure` whose cause is a `CancelledFailure`, and we want\n // the cancellation discriminant rather than the generic wrapper.\n if (isCancellation(error)) {\n return new ChildWorkflowCancelledError(childWorkflowName, error);\n }\n\n // Temporal wraps the actionable failure (ApplicationFailure, TimeoutFailure,\n // TerminatedFailure, etc.) inside a ChildWorkflowFailure. Forward the\n // inner cause so consumers can branch on the failure category without\n // unwrapping twice. Fall back to the wrapper itself if `cause` is missing\n // so callers don't lose the error identity.\n if (error instanceof ChildWorkflowFailure) {\n const inner = error.cause ?? error;\n const innerMessage = inner instanceof Error ? inner.message : String(inner);\n return new ChildWorkflowError(\n `${describeChildWorkflowOperation(operation, childWorkflowName)}: ${innerMessage}`,\n inner,\n );\n }\n\n const message = error instanceof Error ? error.message : String(error);\n return new ChildWorkflowError(\n `${describeChildWorkflowOperation(operation, childWorkflowName)}: ${message}`,\n error,\n );\n}\n\nfunction describeChildWorkflowOperation(\n operation: \"startChild\" | \"executeChild\" | \"result\",\n childWorkflowName: string,\n): string {\n switch (operation) {\n case \"startChild\":\n return `Failed to start child workflow \"${childWorkflowName}\"`;\n case \"executeChild\":\n return `Failed to execute child workflow \"${childWorkflowName}\"`;\n case \"result\":\n return `Child workflow \"${childWorkflowName}\" execution failed`;\n }\n}\n"],"mappings":";;;;;;;;AAMA,IAAe,cAAf,cAAmC,MAAM;CACvC,YAAsB,SAAiB,OAAiB;EACtD,MAAM,SAAS,EAAE,MAAM,CAAC;EACxB,KAAK,OAAO;EAEZ,IAAI,MAAM,mBACR,MAAM,kBAAkB,MAAM,KAAK,WAAW;CAElD;AACF;;;;AAKA,IAAa,kCAAb,cAAqD,YAAY;CAE7C;CACA;CAFlB,YACE,cACA,uBAA0D,CAAC,GAC3D;EACA,MAAM,YAAY,qBAAqB,SAAS,IAAI,qBAAqB,KAAK,IAAI,IAAI;EACtF,MACE,uCAAuC,aAAa,2BAA2B,WACjF;EANgB,KAAA,eAAA;EACA,KAAA,uBAAA;EAMhB,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAa,+BAAb,cAAkD,YAAY;CAE1C;CACA;CAFlB,YACE,cACA,QACA;EACA,MAAM,UAAU,gBAAgB,MAAM;EACtC,MAAM,aAAa,aAAa,6BAA6B,SAAS;EAJtD,KAAA,eAAA;EACA,KAAA,S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