@yolk-sdk/vercel-workflows 0.1.0-canary.136 → 0.1.0-canary.138

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -61,6 +61,11 @@ const program = Effect.gen(function* () {
61
61
  }).pipe(Effect.provide(VercelWorkflows.layer))
62
62
  ```
63
63
 
64
+ `start` takes optional `{ attributes }`: plaintext, searchable run metadata seeded at creation
65
+ (Workflow run attributes). The platform validates them before the run exists and an invalid one
66
+ fails the start, so use identifiers, never secrets or content. A run started from inside a workflow
67
+ or step also gets the reserved `$parentRunId` and `$rootRunId` automatically.
68
+
64
69
  The API wrapper keeps Vercel's SDK underneath. It does not reimplement Vercel backend HTTP,
65
70
  queues, hooks, or stream storage.
66
71
 
@@ -76,8 +81,11 @@ FatalError (named `FatalError`, or with `fatal: true`; an `AbortError` is promot
76
81
  retried, an exhausted step fails with the platform's FatalError wrapping the last error, and a
77
82
  thrown value the platform cannot store (a class instance anywhere in its `cause` chain) is
78
83
  redelivered like the platform does until the step exceeds its retries;
79
- `world.inspect(runId).unstorableStepErrors` lists those values. Executing a step loads the workflow
80
- runtime, so it needs the Node test environment. Ambient module mocks do not apply retry policy by
84
+ `world.inspect(runId).unstorableStepErrors` lists those values. `world.sdk.start` checks start
85
+ `attributes` with the installed runtime's validator (an invalid one rejects with a FatalError and
86
+ creates no run) and `world.inspect(runId).attributes` shows them (`{}` without any; the emulator
87
+ adds no `$parentRunId`/`$rootRunId`). Executing a step loads the workflow runtime, so it needs the
88
+ Node test environment. Ambient module mocks do not apply retry policy by
81
89
  themselves: wrap host step callbacks with `world.step(...)` or call `world.runStep(...)` explicitly
82
90
  when the test must exercise platform retry attempts and `getStepMetadata().attempt`.
83
91
 
package/dist/effect.d.mts CHANGED
@@ -13,6 +13,15 @@ export type VercelWorkflowFunction<TArgs extends unknown[], TResult> = (...args:
13
13
  export type VercelWorkflowReadableOptions = WorkflowReadableStreamOptions;
14
14
  export type VercelWorkflowReadableStream<Chunk> = WorkflowReadableStream<Chunk>;
15
15
  export type VercelWorkflowRunStatus = WorkflowRun['status'];
16
+ /**
17
+ * Options for starting a run. `attributes` seeds the run's plaintext, searchable metadata at
18
+ * creation (no extra event). The platform validates them before creating the run and the start
19
+ * fails on an invalid one: keys of 1-256 characters not starting with `$` (reserved), values of at
20
+ * most 256 UTF-8 bytes, at most 64 per run. Never put secrets or content in them.
21
+ */
22
+ export type VercelWorkflowStartOptions = {
23
+ readonly attributes?: Readonly<Record<string, string>>;
24
+ };
16
25
  export type VercelWorkflowsSdkRun<TResult> = {
17
26
  readonly runId: string;
18
27
  readonly getReadable: <Chunk>(options?: VercelWorkflowReadableOptions) => VercelWorkflowReadableStream<Chunk>;
@@ -21,7 +30,7 @@ export type VercelWorkflowsSdkRun<TResult> = {
21
30
  readonly returnValue: Promise<TResult>;
22
31
  };
23
32
  export type VercelWorkflowsSdkClient = {
24
- readonly start: <TArgs extends unknown[], TResult>(workflow: VercelWorkflowFunction<TArgs, TResult>, args: TArgs) => Promise<VercelWorkflowsSdkRun<TResult>>;
33
+ readonly start: <TArgs extends unknown[], TResult>(workflow: VercelWorkflowFunction<TArgs, TResult>, args: TArgs, options?: VercelWorkflowStartOptions) => Promise<VercelWorkflowsSdkRun<TResult>>;
25
34
  readonly getRun: <TResult>(runId: string) => VercelWorkflowsSdkRun<TResult>;
26
35
  readonly resumeHook: (token: string, payload: unknown) => Promise<void>;
27
36
  };
@@ -33,7 +42,7 @@ export type VercelWorkflowRun<TResult> = {
33
42
  readonly returnValue: Effect.Effect<TResult, VercelWorkflowsError>;
34
43
  };
35
44
  export type VercelWorkflowsClient = {
36
- readonly start: <TArgs extends unknown[], TResult>(workflow: VercelWorkflowFunction<TArgs, TResult>, args: TArgs) => Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError>;
45
+ readonly start: <TArgs extends unknown[], TResult>(workflow: VercelWorkflowFunction<TArgs, TResult>, args: TArgs, options?: VercelWorkflowStartOptions) => Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError>;
37
46
  readonly getRun: <TResult>(runId: string) => Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError>;
38
47
  readonly getReadable: <Chunk>(runId: string, options?: VercelWorkflowReadableOptions) => Effect.Effect<VercelWorkflowReadableStream<Chunk>, VercelWorkflowsError>;
39
48
  readonly tailIndex: (runId: string) => Effect.Effect<number, VercelWorkflowsError>;
@@ -1 +1 @@
1
- {"version":3,"file":"effect.d.mts","names":[],"sources":["../src/effect.ts"],"mappings":";;YAUY;;;;qBAUC,6BAA6B;WAC/B,WAAW;WACX;WACA;;YAGC,uBAAuB,yBAAyB,eACvD,MAAM,UACN,QAAQ;YAED,gCAAgC;YAEhC,6BAA6B,SAAS,uBAAuB;YAE7D,0BAA0B;YAE1B,sBAAsB;WACvB;WACA,cAAc,OACrB,UAAU,kCACP,6BAA6B;WACzB,cAAc;WACd,QAAQ,QAAQ;WAChB,aAAa,QAAQ;;YAGpB;WACD,QAAQ,yBAAyB,SACxC,UAAU,uBAAuB,OAAO,UACxC,MAAM,UACH,QAAQ,sBAAsB;WAC1B,SAAS,SAAS,kBAAkB,sBAAsB;WAC1D,aAAa,eAAe,qBAAqB;;YAGhD,kBAAkB;WACnB;WACA,cAAc,OACrB,UAAU,kCACP,OAAO,OAAO,6BAA6B,QAAQ;WAC/C,QAAQ,OAAO,aAAa;WAC5B,QAAQ,OAAO,OAAO,yBAAyB;WAC/C,aAAa,OAAO,OAAO,SAAS;;YAGnC;WACD,QAAQ,yBAAyB,SACxC,UAAU,uBAAuB,OAAO,UACxC,MAAM,UACH,OAAO,OAAO,kBAAkB,UAAU;WACtC,SAAS,SAChB,kBACG,OAAO,OAAO,kBAAkB,UAAU;WACtC,cAAc,OACrB,eACA,UAAU,kCACP,OAAO,OAAO,6BAA6B,QAAQ;WAC/C,YAAY,kBAAkB,OAAO,eAAe;WACpD,aACP,eACA,qBACG,OAAO,aAAa;WAChB,SAAS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A"}
package/dist/effect.mjs CHANGED
@@ -24,7 +24,7 @@ const makeWorkflowRun = (run) => ({
24
24
  returnValue: trySdkPromise("returnValue", () => run.returnValue).pipe(Effect.withSpan("VercelWorkflows.run.returnValue", { attributes: spanAttributes(run.runId) }))
25
25
  });
26
26
  const VercelWorkflowsSdkLive = Layer.succeed(VercelWorkflowsSdk, {
27
- start: (workflow, args) => start(workflow, args),
27
+ start: (workflow, args, options) => options?.attributes === void 0 ? start(workflow, args) : start(workflow, args, { attributes: { ...options.attributes } }),
28
28
  getRun: (runId) => getRun(runId),
29
29
  resumeHook: async (token, payload) => {
30
30
  await resumeHook(token, payload);
@@ -37,7 +37,7 @@ var VercelWorkflows = class extends Context.Service()("@yolk-sdk/vercel-workflow
37
37
  catch: (cause) => workflowsError("getRun", cause)
38
38
  }).pipe(Effect.map(makeWorkflowRun), Effect.withSpan("VercelWorkflows.getRun", { attributes: spanAttributes(runId) }));
39
39
  return {
40
- start: (workflow, args) => trySdkPromise("start", () => sdk.start(workflow, args)).pipe(Effect.map(makeWorkflowRun), Effect.withSpan("VercelWorkflows.start")),
40
+ start: (workflow, args, options) => trySdkPromise("start", () => sdk.start(workflow, args, options)).pipe(Effect.map(makeWorkflowRun), Effect.withSpan("VercelWorkflows.start")),
41
41
  getRun,
42
42
  getReadable: (runId, options) => getRun(runId).pipe(Effect.flatMap((run) => run.getReadable(options)), Effect.withSpan("VercelWorkflows.getReadable", { attributes: spanAttributes(runId) })),
43
43
  tailIndex: (runId) => getRun(runId).pipe(Effect.flatMap((run) => run.getReadable({ startIndex: -1 })), Effect.flatMap((readable) => Effect.tryPromise({
@@ -1 +1 @@
1
- {"version":3,"file":"effect.mjs","names":["workflowStart","workflowGetRun","workflowResumeHook"],"sources":["../src/effect.ts"],"sourcesContent":["import { Context, Data, Effect, Layer } from 'effect'\nimport {\n getRun as workflowGetRun,\n resumeHook as workflowResumeHook,\n start as workflowStart,\n type WorkflowReadableStream,\n type WorkflowReadableStreamOptions,\n type WorkflowRun\n} from 'workflow/api'\n\nexport type VercelWorkflowsOperation =\n | 'start'\n | 'getRun'\n | 'getReadable'\n | 'tailIndex'\n | 'resumeHook'\n | 'cancel'\n | 'status'\n | 'returnValue'\n\nexport class VercelWorkflowsError extends Data.TaggedError('VercelWorkflowsError')<{\n readonly operation: VercelWorkflowsOperation\n readonly message: string\n readonly cause: unknown\n}> {}\n\nexport type VercelWorkflowFunction<TArgs extends unknown[], TResult> = (\n ...args: TArgs\n) => Promise<TResult>\n\nexport type VercelWorkflowReadableOptions = WorkflowReadableStreamOptions\n\nexport type VercelWorkflowReadableStream<Chunk> = WorkflowReadableStream<Chunk>\n\nexport type VercelWorkflowRunStatus = WorkflowRun['status']\n\nexport type VercelWorkflowsSdkRun<TResult> = {\n readonly runId: string\n readonly getReadable: <Chunk>(\n options?: VercelWorkflowReadableOptions\n ) => VercelWorkflowReadableStream<Chunk>\n readonly cancel: () => Promise<void>\n readonly status: Promise<VercelWorkflowRunStatus>\n readonly returnValue: Promise<TResult>\n}\n\nexport type VercelWorkflowsSdkClient = {\n readonly start: <TArgs extends unknown[], TResult>(\n workflow: VercelWorkflowFunction<TArgs, TResult>,\n args: TArgs\n ) => Promise<VercelWorkflowsSdkRun<TResult>>\n readonly getRun: <TResult>(runId: string) => VercelWorkflowsSdkRun<TResult>\n readonly resumeHook: (token: string, payload: unknown) => Promise<void>\n}\n\nexport type VercelWorkflowRun<TResult> = {\n readonly runId: string\n readonly getReadable: <Chunk>(\n options?: VercelWorkflowReadableOptions\n ) => Effect.Effect<VercelWorkflowReadableStream<Chunk>, VercelWorkflowsError>\n readonly cancel: Effect.Effect<void, VercelWorkflowsError>\n readonly status: Effect.Effect<VercelWorkflowRunStatus, VercelWorkflowsError>\n readonly returnValue: Effect.Effect<TResult, VercelWorkflowsError>\n}\n\nexport type VercelWorkflowsClient = {\n readonly start: <TArgs extends unknown[], TResult>(\n workflow: VercelWorkflowFunction<TArgs, TResult>,\n args: TArgs\n ) => Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError>\n readonly getRun: <TResult>(\n runId: string\n ) => Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError>\n readonly getReadable: <Chunk>(\n runId: string,\n options?: VercelWorkflowReadableOptions\n ) => Effect.Effect<VercelWorkflowReadableStream<Chunk>, VercelWorkflowsError>\n readonly tailIndex: (runId: string) => Effect.Effect<number, VercelWorkflowsError>\n readonly resumeHook: (\n token: string,\n payload: unknown\n ) => Effect.Effect<void, VercelWorkflowsError>\n readonly cancel: (runId: string) => Effect.Effect<void, VercelWorkflowsError>\n}\n\nexport class VercelWorkflowsSdk extends Context.Service<\n VercelWorkflowsSdk,\n VercelWorkflowsSdkClient\n>()('@yolk-sdk/vercel-workflows/VercelWorkflowsSdk') {}\n\nconst workflowsError = (operation: VercelWorkflowsOperation, cause: unknown) =>\n new VercelWorkflowsError({\n operation,\n message: `Vercel Workflow ${operation} failed`,\n cause\n })\n\nconst spanAttributes = (runId: string) => ({ 'workflow.run.id': runId })\n\nconst trySdkPromise = <A>(operation: VercelWorkflowsOperation, body: () => Promise<A>) =>\n Effect.tryPromise({\n try: body,\n catch: cause => workflowsError(operation, cause)\n })\n\nconst makeWorkflowRun = <TResult>(\n run: VercelWorkflowsSdkRun<TResult>\n): VercelWorkflowRun<TResult> => ({\n runId: run.runId,\n getReadable: <Chunk>(options?: VercelWorkflowReadableOptions) =>\n Effect.try({\n try: () => run.getReadable<Chunk>(options),\n catch: cause => workflowsError('getReadable', cause)\n }).pipe(\n Effect.withSpan('VercelWorkflows.run.getReadable', {\n attributes: spanAttributes(run.runId)\n })\n ),\n cancel: trySdkPromise('cancel', () => run.cancel()).pipe(\n Effect.withSpan('VercelWorkflows.run.cancel', {\n attributes: spanAttributes(run.runId)\n })\n ),\n status: trySdkPromise('status', () => run.status).pipe(\n Effect.withSpan('VercelWorkflows.run.status', {\n attributes: spanAttributes(run.runId)\n })\n ),\n returnValue: trySdkPromise('returnValue', () => run.returnValue).pipe(\n Effect.withSpan('VercelWorkflows.run.returnValue', {\n attributes: spanAttributes(run.runId)\n })\n )\n})\n\nconst VercelWorkflowsSdkLive = Layer.succeed(VercelWorkflowsSdk, {\n start: <TArgs extends unknown[], TResult>(\n workflow: VercelWorkflowFunction<TArgs, TResult>,\n args: TArgs\n ) => workflowStart(workflow, args),\n getRun: <TResult>(runId: string) => workflowGetRun<TResult>(runId),\n resumeHook: async (token: string, payload: unknown) => {\n await workflowResumeHook<unknown>(token, payload)\n }\n})\n\nexport class VercelWorkflows extends Context.Service<VercelWorkflows, VercelWorkflowsClient>()(\n '@yolk-sdk/vercel-workflows/VercelWorkflows',\n {\n make: Effect.gen(function* () {\n const sdk = yield* VercelWorkflowsSdk\n\n const getRun = <TResult>(\n runId: string\n ): Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError> =>\n Effect.try({\n try: () => sdk.getRun<TResult>(runId),\n catch: cause => workflowsError('getRun', cause)\n }).pipe(\n Effect.map(makeWorkflowRun),\n Effect.withSpan('VercelWorkflows.getRun', {\n attributes: spanAttributes(runId)\n })\n )\n\n return {\n start: <TArgs extends unknown[], TResult>(\n workflow: VercelWorkflowFunction<TArgs, TResult>,\n args: TArgs\n ): Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError> =>\n trySdkPromise('start', () => sdk.start(workflow, args)).pipe(\n Effect.map(makeWorkflowRun),\n Effect.withSpan('VercelWorkflows.start')\n ),\n\n getRun,\n\n getReadable: <Chunk>(\n runId: string,\n options?: VercelWorkflowReadableOptions\n ): Effect.Effect<VercelWorkflowReadableStream<Chunk>, VercelWorkflowsError> =>\n getRun<unknown>(runId).pipe(\n Effect.flatMap(run => run.getReadable<Chunk>(options)),\n Effect.withSpan('VercelWorkflows.getReadable', {\n attributes: spanAttributes(runId)\n })\n ),\n\n tailIndex: (runId: string): Effect.Effect<number, VercelWorkflowsError> =>\n getRun<unknown>(runId).pipe(\n Effect.flatMap(run => run.getReadable<unknown>({ startIndex: -1 })),\n Effect.flatMap(readable =>\n Effect.tryPromise({\n try: () => readable.getTailIndex(),\n catch: cause => workflowsError('tailIndex', cause)\n })\n ),\n Effect.withSpan('VercelWorkflows.tailIndex', {\n attributes: spanAttributes(runId)\n })\n ),\n\n resumeHook: (token: string, payload: unknown): Effect.Effect<void, VercelWorkflowsError> =>\n trySdkPromise('resumeHook', () => sdk.resumeHook(token, payload)).pipe(\n Effect.withSpan('VercelWorkflows.resumeHook')\n ),\n\n cancel: (runId: string): Effect.Effect<void, VercelWorkflowsError> =>\n getRun<unknown>(runId).pipe(\n Effect.flatMap(run => run.cancel),\n Effect.withSpan('VercelWorkflows.cancel', {\n attributes: spanAttributes(runId)\n })\n )\n }\n })\n }\n) {\n static layer = Layer.effect(this, this.make).pipe(Layer.provide(VercelWorkflowsSdkLive))\n static layerFromSdk = Layer.effect(this, this.make)\n}\n"],"mappings":";;;AAoBA,IAAa,uBAAb,cAA0C,KAAK,YAAY,sBAAsB,CAAC,CAI/E,CAAC;AA6DJ,IAAa,qBAAb,cAAwC,QAAQ,QAG9C,CAAC,CAAC,+CAA+C,CAAC,CAAC,CAAC;AAEtD,MAAM,kBAAkB,WAAqC,UAC3D,IAAI,qBAAqB;CACvB;CACA,SAAS,mBAAmB,UAAU;CACtC;AACF,CAAC;AAEH,MAAM,kBAAkB,WAAmB,EAAE,mBAAmB,MAAM;AAEtE,MAAM,iBAAoB,WAAqC,SAC7D,OAAO,WAAW;CAChB,KAAK;CACL,QAAO,UAAS,eAAe,WAAW,KAAK;AACjD,CAAC;AAEH,MAAM,mBACJ,SACgC;CAChC,OAAO,IAAI;CACX,cAAqB,YACnB,OAAO,IAAI;EACT,WAAW,IAAI,YAAmB,OAAO;EACzC,QAAO,UAAS,eAAe,eAAe,KAAK;CACrD,CAAC,CAAC,CAAC,KACD,OAAO,SAAS,mCAAmC,EACjD,YAAY,eAAe,IAAI,KAAK,EACtC,CAAC,CACH;CACF,QAAQ,cAAc,gBAAgB,IAAI,OAAO,CAAC,CAAC,CAA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SAAQ,QAAO,IAAI,YAAqB,EAAE,YAAY,GAAG,CAAC,CAAC,GAClE,OAAO,SAAQ,aACb,OAAO,WAAW;GAChB,WAAW,SAAS,aAAa;GACjC,QAAO,UAAS,eAAe,aAAa,KAAK;EACnD,CAAC,CACH,GACA,OAAO,SAAS,6BAA6B,EAC3C,YAAY,eAAe,KAAK,EAClC,CAAC,CACH;EAEF,aAAa,OAAe,YAC1B,cAAc,oBAAoB,IAAI,WAAW,OAAO,OAAO,CAAC,CAAC,CAAC,KAChE,OAAO,SAAS,4BAA4B,CAC9C;EAEF,SAAS,UACP,OAAgB,KAAK,CAAC,CAAC,KACrB,OAAO,SAAQ,QAAO,IAAI,MAAM,GAChC,OAAO,SAAS,0BAA0B,EACxC,YAAY,eAAe,KAAK,EAClC,CAAC,CACH;CACJ;AACF,CAAC,EACH,CACF,CAAC,CAAC;CACA,OAAO,QAAQ,MAAM,OAAO,MAAM,KAAK,IAAI,CAAC,CAAC,KAAK,MAAM,QAAQ,sBAAsB,CAAC;CACvF,OAAO,eAAe,MAAM,OAAO,MAAM,KAAK,IAAI;AACpD"}
1
+ {"version":3,"file":"effect.mjs","names":["workflowStart","workflowGetRun","workflowResumeHook"],"sources":["../src/effect.ts"],"sourcesContent":["import { Context, Data, Effect, Layer } from 'effect'\nimport {\n getRun as workflowGetRun,\n resumeHook as workflowResumeHook,\n start as workflowStart,\n type WorkflowReadableStream,\n type WorkflowReadableStreamOptions,\n type WorkflowRun\n} from 'workflow/api'\n\nexport type VercelWorkflowsOperation =\n | 'start'\n | 'getRun'\n | 'getReadable'\n | 'tailIndex'\n | 'resumeHook'\n | 'cancel'\n | 'status'\n | 'returnValue'\n\nexport class VercelWorkflowsError extends Data.TaggedError('VercelWorkflowsError')<{\n readonly operation: VercelWorkflowsOperation\n readonly message: string\n readonly cause: unknown\n}> {}\n\nexport type VercelWorkflowFunction<TArgs extends unknown[], TResult> = (\n ...args: TArgs\n) => Promise<TResult>\n\nexport type VercelWorkflowReadableOptions = WorkflowReadableStreamOptions\n\nexport type VercelWorkflowReadableStream<Chunk> = WorkflowReadableStream<Chunk>\n\nexport type VercelWorkflowRunStatus = WorkflowRun['status']\n\n/**\n * Options for starting a run. `attributes` seeds the run's plaintext, searchable metadata at\n * creation (no extra event). The platform validates them before creating the run and the start\n * fails on an invalid one: keys of 1-256 characters not starting with `$` (reserved), values of at\n * most 256 UTF-8 bytes, at most 64 per run. Never put secrets or content in them.\n */\nexport type VercelWorkflowStartOptions = {\n readonly attributes?: Readonly<Record<string, string>>\n}\n\nexport type VercelWorkflowsSdkRun<TResult> = {\n readonly runId: string\n readonly getReadable: <Chunk>(\n options?: VercelWorkflowReadableOptions\n ) => VercelWorkflowReadableStream<Chunk>\n readonly cancel: () => Promise<void>\n readonly status: Promise<VercelWorkflowRunStatus>\n readonly returnValue: Promise<TResult>\n}\n\nexport type VercelWorkflowsSdkClient = {\n readonly start: <TArgs extends unknown[], TResult>(\n workflow: VercelWorkflowFunction<TArgs, TResult>,\n args: TArgs,\n options?: VercelWorkflowStartOptions\n ) => Promise<VercelWorkflowsSdkRun<TResult>>\n readonly getRun: <TResult>(runId: string) => VercelWorkflowsSdkRun<TResult>\n readonly resumeHook: (token: string, payload: unknown) => Promise<void>\n}\n\nexport type VercelWorkflowRun<TResult> = {\n readonly runId: string\n readonly getReadable: <Chunk>(\n options?: VercelWorkflowReadableOptions\n ) => Effect.Effect<VercelWorkflowReadableStream<Chunk>, VercelWorkflowsError>\n readonly cancel: Effect.Effect<void, VercelWorkflowsError>\n readonly status: Effect.Effect<VercelWorkflowRunStatus, VercelWorkflowsError>\n readonly returnValue: Effect.Effect<TResult, VercelWorkflowsError>\n}\n\nexport type VercelWorkflowsClient = {\n readonly start: <TArgs extends unknown[], TResult>(\n workflow: VercelWorkflowFunction<TArgs, TResult>,\n args: TArgs,\n options?: VercelWorkflowStartOptions\n ) => Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError>\n readonly getRun: <TResult>(\n runId: string\n ) => Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError>\n readonly getReadable: <Chunk>(\n runId: string,\n options?: VercelWorkflowReadableOptions\n ) => Effect.Effect<VercelWorkflowReadableStream<Chunk>, VercelWorkflowsError>\n readonly tailIndex: (runId: string) => Effect.Effect<number, VercelWorkflowsError>\n readonly resumeHook: (\n token: string,\n payload: unknown\n ) => Effect.Effect<void, VercelWorkflowsError>\n readonly cancel: (runId: string) => Effect.Effect<void, VercelWorkflowsError>\n}\n\nexport class VercelWorkflowsSdk extends Context.Service<\n VercelWorkflowsSdk,\n VercelWorkflowsSdkClient\n>()('@yolk-sdk/vercel-workflows/VercelWorkflowsSdk') {}\n\nconst workflowsError = (operation: VercelWorkflowsOperation, cause: unknown) =>\n new VercelWorkflowsError({\n operation,\n message: `Vercel Workflow ${operation} failed`,\n cause\n })\n\nconst spanAttributes = (runId: string) => ({ 'workflow.run.id': runId })\n\nconst trySdkPromise = <A>(operation: VercelWorkflowsOperation, body: () => Promise<A>) =>\n Effect.tryPromise({\n try: body,\n catch: cause => workflowsError(operation, cause)\n })\n\nconst makeWorkflowRun = <TResult>(\n run: VercelWorkflowsSdkRun<TResult>\n): VercelWorkflowRun<TResult> => ({\n runId: run.runId,\n getReadable: <Chunk>(options?: VercelWorkflowReadableOptions) =>\n Effect.try({\n try: () => run.getReadable<Chunk>(options),\n catch: cause => workflowsError('getReadable', cause)\n }).pipe(\n Effect.withSpan('VercelWorkflows.run.getReadable', {\n attributes: spanAttributes(run.runId)\n })\n ),\n cancel: trySdkPromise('cancel', () => run.cancel()).pipe(\n Effect.withSpan('VercelWorkflows.run.cancel', {\n attributes: spanAttributes(run.runId)\n })\n ),\n status: trySdkPromise('status', () => run.status).pipe(\n Effect.withSpan('VercelWorkflows.run.status', {\n attributes: spanAttributes(run.runId)\n })\n ),\n returnValue: trySdkPromise('returnValue', () => run.returnValue).pipe(\n Effect.withSpan('VercelWorkflows.run.returnValue', {\n attributes: spanAttributes(run.runId)\n })\n )\n})\n\nconst VercelWorkflowsSdkLive = Layer.succeed(VercelWorkflowsSdk, {\n start: <TArgs extends unknown[], TResult>(\n workflow: VercelWorkflowFunction<TArgs, TResult>,\n args: TArgs,\n options?: VercelWorkflowStartOptions\n ) =>\n options?.attributes === undefined\n ? workflowStart(workflow, args)\n : workflowStart(workflow, args, { attributes: { ...options.attributes } }),\n getRun: <TResult>(runId: string) => workflowGetRun<TResult>(runId),\n resumeHook: async (token: string, payload: unknown) => {\n await workflowResumeHook<unknown>(token, payload)\n }\n})\n\nexport class VercelWorkflows extends Context.Service<VercelWorkflows, VercelWorkflowsClient>()(\n '@yolk-sdk/vercel-workflows/VercelWorkflows',\n {\n make: Effect.gen(function* () {\n const sdk = yield* VercelWorkflowsSdk\n\n const getRun = <TResult>(\n runId: string\n ): Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError> =>\n Effect.try({\n try: () => sdk.getRun<TResult>(runId),\n catch: cause => workflowsError('getRun', cause)\n }).pipe(\n Effect.map(makeWorkflowRun),\n Effect.withSpan('VercelWorkflows.getRun', {\n attributes: spanAttributes(runId)\n })\n )\n\n return {\n start: <TArgs extends unknown[], TResult>(\n workflow: VercelWorkflowFunction<TArgs, TResult>,\n args: TArgs,\n options?: VercelWorkflowStartOptions\n ): Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError> =>\n trySdkPromise('start', () => sdk.start(workflow, args, options)).pipe(\n Effect.map(makeWorkflowRun),\n Effect.withSpan('VercelWorkflows.start')\n ),\n\n getRun,\n\n getReadable: <Chunk>(\n runId: string,\n options?: VercelWorkflowReadableOptions\n ): Effect.Effect<VercelWorkflowReadableStream<Chunk>, VercelWorkflowsError> =>\n getRun<unknown>(runId).pipe(\n Effect.flatMap(run => run.getReadable<Chunk>(options)),\n Effect.withSpan('VercelWorkflows.getReadable', {\n attributes: spanAttributes(runId)\n })\n ),\n\n tailIndex: (runId: string): Effect.Effect<number, VercelWorkflowsError> =>\n getRun<unknown>(runId).pipe(\n Effect.flatMap(run => run.getReadable<unknown>({ startIndex: -1 })),\n Effect.flatMap(readable =>\n Effect.tryPromise({\n try: () => readable.getTailIndex(),\n catch: cause => workflowsError('tailIndex', cause)\n })\n ),\n Effect.withSpan('VercelWorkflows.tailIndex', {\n attributes: spanAttributes(runId)\n })\n ),\n\n resumeHook: (token: string, payload: unknown): Effect.Effect<void, VercelWorkflowsError> =>\n trySdkPromise('resumeHook', () => sdk.resumeHook(token, payload)).pipe(\n Effect.withSpan('VercelWorkflows.resumeHook')\n ),\n\n cancel: (runId: string): Effect.Effect<void, VercelWorkflowsError> =>\n getRun<unknown>(runId).pipe(\n Effect.flatMap(run => run.cancel),\n Effect.withSpan('VercelWorkflows.cancel', {\n attributes: spanAttributes(runId)\n })\n )\n }\n })\n }\n) {\n static layer = Layer.effect(this, this.make).pipe(Layer.provide(VercelWorkflowsSdkLive))\n static layerFromSdk = Layer.effect(this, this.make)\n}\n"],"mappings":";;;AAoBA,IAAa,uBAAb,cAA0C,KAAK,YAAY,sBAAsB,CAAC,CAI/E,CAAC;AAyEJ,IAAa,qBAAb,cAAwC,QAAQ,QAG9C,CAAC,CAAC,+CAA+C,CAAC,CAAC,CAAC;AAEtD,MAAM,kBAAkB,WAAqC,UAC3D,IAAI,qBAAqB;CACvB;CACA,SAAS,mBAAmB,UAAU;CACtC;AACF,CAAC;AAEH,MAAM,kBAAkB,WAAmB,EAAE,mBAAmB,MAAM;AAEtE,MAAM,iBAAoB,WAAqC,SAC7D,OAAO,WAAW;CAChB,KAAK;CACL,QAAO,UAAS,eAAe,WAAW,KAAK;AACjD,CAAC;AAEH,MAAM,mBACJ,SACgC;CAChC,OAAO,IAAI;CACX,cAAqB,YACnB,OAAO,IAAI;EACT,WAAW,IAAI,YAAmB,OAAO;EACzC,QAAO,UAAS,eAAe,eAAe,KAAK;CACrD,CAAC,CAAC,CAAC,KACD,OAAO,SAAS,mCAAmC,EACjD,YAAY,eAAe,IAAI,KAAK,EACtC,CAAC,CACH;CACF,QA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AAO,SAAQ,QAAO,IAAI,YAAmB,OAAO,CAAC,GACrD,OAAO,SAAS,+BAA+B,EAC7C,YAAY,eAAe,KAAK,EAClC,CAAC,CACH;EAEF,YAAY,UACV,OAAgB,KAAK,CAAC,CAAC,KACrB,OAAO,SAAQ,QAAO,IAAI,YAAqB,EAAE,YAAY,GAAG,CAAC,CAAC,GAClE,OAAO,SAAQ,aACb,OAAO,WAAW;GAChB,WAAW,SAAS,aAAa;GACjC,QAAO,UAAS,eAAe,aAAa,KAAK;EACnD,CAAC,CACH,GACA,OAAO,SAAS,6BAA6B,EAC3C,YAAY,eAAe,KAAK,EAClC,CAAC,CACH;EAEF,aAAa,OAAe,YAC1B,cAAc,oBAAoB,IAAI,WAAW,OAAO,OAAO,CAAC,CAAC,CAAC,KAChE,OAAO,SAAS,4BAA4B,CAC9C;EAEF,SAAS,UACP,OAAgB,KAAK,CAAC,CAAC,KACrB,OAAO,SAAQ,QAAO,IAAI,MAAM,GAChC,OAAO,SAAS,0BAA0B,EACxC,YAAY,eAAe,KAAK,EAClC,CAAC,CACH;CACJ;AACF,CAAC,EACH,CACF,CAAC,CAAC;CACA,OAAO,QAAQ,MAAM,OAAO,MAAM,KAAK,IAAI,CAAC,CAAC,KAAK,MAAM,QAAQ,sBAAsB,CAAC;CACvF,OAAO,eAAe,MAAM,OAAO,MAAM,KAAK,IAAI;AACpD"}
@@ -46,6 +46,8 @@ export type TestWorkflowStepFunction<TArgs extends ReadonlyArray<unknown>, TResu
46
46
  export declare const defaultTestWorkflowStepMaxRetries = 3;
47
47
  export type TestWorkflowRunInspection = {
48
48
  readonly runId: string;
49
+ /** The `attributes` the run was started with through `sdk.start` (`{}` without any). */
50
+ readonly attributes: Readonly<Record<string, string>>;
49
51
  readonly status: TestWorkflowRunStatus;
50
52
  readonly chunks: ReadonlyArray<unknown>;
51
53
  readonly streamClosed: boolean;
@@ -66,6 +68,7 @@ export declare class TestWorkflowWorld {
66
68
  private readonly runs;
67
69
  private runSequence;
68
70
  start<TArgs extends ReadonlyArray<unknown>, TResult>(workflowFn: (...args: TArgs) => Promise<TResult>, args: TArgs): TestWorkflowWorldStartResult;
71
+ private startRun;
69
72
  settled(runId: string): Promise<void>;
70
73
  inspect(runId: string): TestWorkflowRunInspection;
71
74
  status(runId: string): TestWorkflowRunStatus;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/testing/index.ts"],"mappings":";YAkCY,wBAAwB;qBAKvB,wCAAwC;WACjC;WACT;EAET,YAAY;;qBAKD,qCAAqC;WAC9B;WACT;EAET,YAAY;;qBAKD,sCAAsC;WAC/B;EAElB,YAAY;;qBAKD,sCAAsC;WAC/B;EAElB,YAAY;;qBAKD,qCAAqC;WAC9B;EAElB,YAAY;;qBAKD,sCAAsC;WAC/B;EAElB,YAAY;;YAKF;WAAkC;;YAElC;WACD;WACA;WACA;;;YAIC;WACD;WACA;WACA;;YAGC,yBAAyB,cAAc,wBAAwB,gBACtE,MAAM,UACN,QAAQ;WAAuB;;qBAGvB;YA+LD;WACD;WACA,QAAQ;WACR,QAAQ;WACR;WACA;WACA;WACA,cAAc;WACd;;WAEA,sBAAsB,cAAc;;YAGnC,iBAAiB,KAAK,QAAQ;YAAiB,OAAO;;KAE7D;WAA0C;;qBAElC;mBACM;UACT;EAER,MAAM,cAAc,wBAAwB,SAC1C,gBAAgB,MAAM,UAAU,QAAQ,UACxC,MAAM,QACL;EAoDG,QAAQ,gBAAgB;EAI9B,QAAQ,gBAAgB;EAgBxB,OAAO,gBAAgB;EAIjB,OAAO,gBAAgB;EAmBvB,WAAW,eAAe,mBAAmB;EAoBnD,eAAe;EAiBT,QAAQ,cAAc,wBAAwB,SAClD,QAAQ,yBAAyB,OAAO,UACxC,MAAM,OACN,oBACC,QAAQ;EA6EX,KAAK,cAAc,wBAAwB,SACzC,QAAQ,yBAAyB,OAAO,UACxC,wBACK,MAAM,UAAU,QAAQ;SAMxB,uBAAuB;SAIvB,mBAAmB;SAUnB,YAAY,M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,wBACK,MAAM,UAAU,QAAQ;SAMxB,uBAAuB;SAIvB,mBAAmB;SAUnB,YAAY,MAAM,eAAe;SAMjC,WAAW,GAAG;aAAkB;MAAkB,iBAAiB;UAQlE;UAwBA;EAqBR,YAAY,GACV,eACA,UAAU,gCACT,6BAA6B;UAiCxB;UAIA;UAOA;UAMA;UAUA;WA2BC,KAAK;;qBAmBH;EACX,2BAAmB;EACnB,uBAAe;EACf,cAAc,QAAC,eAAA;EACf,aAAa,GAAC;aAAoB;QAAe,iBAAA"}
@@ -51,15 +51,41 @@ const requireAmbient = () => {
51
51
  return ambient;
52
52
  };
53
53
  let stepErrorSerializer;
54
- const workflowPackageDir = (require) => {
55
- let dir = path.dirname(require.resolve("workflow"));
54
+ const packageDirOf = (entry, name) => {
55
+ let dir = path.dirname(entry);
56
56
  while (!fs.existsSync(path.join(dir, "package.json"))) {
57
57
  const parent = path.dirname(dir);
58
- if (parent === dir) throw new Error("Cannot locate the installed workflow package");
58
+ if (parent === dir) throw new Error(`Cannot locate the installed ${name} package`);
59
59
  dir = parent;
60
60
  }
61
61
  return dir;
62
62
  };
63
+ const workflowPackageDir = (require) => packageDirOf(require.resolve("workflow"), "workflow");
64
+ let attributeValidator;
65
+ const loadAttributeValidator = () => attributeValidator ??= (async () => {
66
+ const require = createRequire(import.meta.url);
67
+ const coreDir = packageDirOf(require.resolve("@workflow/core/serialization", { paths: [workflowPackageDir(require)] }), "@workflow/core");
68
+ const world = await import(require.resolve("@workflow/world", { paths: [coreDir] }));
69
+ if (!Predicate.hasProperty(world, "validateAttributeChanges") || !Predicate.isFunction(world.validateAttributeChanges)) throw new Error("The installed workflow runtime has no attribute validator");
70
+ const { validateAttributeChanges } = world;
71
+ return (changes) => {
72
+ validateAttributeChanges(changes);
73
+ };
74
+ })();
75
+ const validateStartAttributes = async (attributes) => {
76
+ const changes = Object.entries(attributes).map(([key, value]) => ({
77
+ key,
78
+ value
79
+ }));
80
+ if (changes.length === 0) return;
81
+ const validate = await loadAttributeValidator();
82
+ try {
83
+ validate(changes);
84
+ } catch (failure) {
85
+ if (Predicate.hasProperty(failure, "name") && failure.name === "AttributeValidationError" && Predicate.hasProperty(failure, "message") && Predicate.isString(failure.message)) throw platformFatalError(failure.message, void 0);
86
+ throw failure;
87
+ }
88
+ };
63
89
  const loadStepErrorSerializer = () => stepErrorSerializer ??= (async () => {
64
90
  const require = createRequire(import.meta.url);
65
91
  const serialization = await import(require.resolve("@workflow/core/serialization", { paths: [workflowPackageDir(require)] })).catch((cause) => {
@@ -116,10 +142,14 @@ var TestWorkflowWorld = class {
116
142
  runs = /* @__PURE__ */ new Map();
117
143
  runSequence = 0;
118
144
  start(workflowFn, args) {
145
+ return this.startRun(workflowFn, args, {});
146
+ }
147
+ startRun(workflowFn, args, attributes) {
119
148
  this.runSequence += 1;
120
149
  const runId = `twr_${this.runSequence}`;
121
150
  const run = {
122
151
  runId,
152
+ attributes: { ...attributes },
123
153
  status: "pending",
124
154
  returnValue: void 0,
125
155
  runError: void 0,
@@ -163,6 +193,7 @@ var TestWorkflowWorld = class {
163
193
  const run = this.requireRun(runId);
164
194
  return {
165
195
  runId: run.runId,
196
+ attributes: { ...run.attributes },
166
197
  status: run.status,
167
198
  chunks: [...run.chunks],
168
199
  streamClosed: run.streamClosed,
@@ -358,8 +389,10 @@ var TestWorkflowWorld = class {
358
389
  };
359
390
  }
360
391
  sdk = {
361
- start: async (workflowFn, args) => {
362
- const { runId } = this.start(workflowFn, args);
392
+ start: async (workflowFn, args, options) => {
393
+ const attributes = { ...options?.attributes };
394
+ await validateStartAttributes(attributes);
395
+ const { runId } = this.startRun(workflowFn, args, attributes);
363
396
  return this.sdkRun(this.requireRun(runId));
364
397
  },
365
398
  getRun: (runId) => this.sdkRun(this.requireRun(runId)),
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/testing/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport fs from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { types } from 'node:util'\nimport path from 'node:path'\nimport { Predicate } from 'effect'\nimport type {\n VercelWorkflowsSdkClient,\n VercelWorkflowsSdkRun,\n VercelWorkflowReadableOptions,\n VercelWorkflowReadableStream,\n VercelWorkflowRunStatus\n} from '../effect.ts'\n\n// Behavioral emulator of the Vercel Workflow platform for tests: run lifecycle,\n// append-only durable streams with close-once -> 409 write conflicts, a step\n// executor honoring `fn.maxRetries` + `getStepMetadata().attempt`, hooks/resume,\n// and cancellation. Host code under test runs unmodified against it; tests mock\n// only the `workflow` module's ambient APIs, delegating to the active world\n// (see `testWorkflowModule`).\n//\n// Step errors cross the platform boundary the way they do in a deployment: each one is stored with\n// the installed `workflow` runtime's own step-error serializer, and the workflow body sees only the\n// value read back (error tags, prototypes and custom fields are gone; a `cause` survives). A thrown\n// value the serializer cannot store (a class instance anywhere in its `cause` chain) never reaches\n// the body: the platform's queue handler fails and redelivers the step, which runs again until its\n// retries run out and it fails with \"exceeded max retries\" (see `unstorableStepErrors`).\n//\n// The single most important semantic: writing to (or re-closing) a closed\n// durable stream fails with the platform's HTTP 409 \"already completed\"\n// conflict shape. Any code path that performs a terminal stream effect from a\n// retryable step attempt poisons every subsequent platform retry — exactly the\n// #252 production bug. The emulator enforces that invariant permanently.\n\nexport type TestWorkflowRunStatus = VercelWorkflowRunStatus\n\n// Matches the platform's conflict contract: `EntityConflictError.is(value)`\n// checks `value.name === 'EntityConflictError'`, and the Vercel world maps\n// HTTP 409 responses to that class.\nexport class TestWorkflowStreamConflictError extends Error {\n override readonly name = 'EntityConflictError'\n readonly status = 409\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" stream already completed`)\n }\n}\n\nexport class TestWorkflowRunConflictError extends Error {\n override readonly name = 'EntityConflictError'\n readonly status = 409\n\n constructor(message: string) {\n super(message)\n }\n}\n\nexport class TestWorkflowHookNotFoundError extends Error {\n override readonly name = 'HookNotFoundError'\n\n constructor(token: string) {\n super(`Workflow hook \"${token}\" was not found`)\n }\n}\n\nexport class TestWorkflowHookConflictError extends Error {\n override readonly name = 'HookConflictError'\n\n constructor(token: string) {\n super(`Workflow hook \"${token}\" was already resumed`)\n }\n}\n\nexport class TestWorkflowRunNotFoundError extends Error {\n override readonly name = 'WorkflowRunNotFoundError'\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" was not found`)\n }\n}\n\nexport class TestWorkflowRunCancelledError extends Error {\n override readonly name = 'WorkflowRunCancelledError'\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" was cancelled`)\n }\n}\n\nexport type TestWorkflowMetadata = { readonly workflowRunId: string }\n\nexport type TestWorkflowStepMetadata = {\n readonly attempt: number\n readonly stepId: string\n readonly stepName: string\n}\n\n/** A thrown step value the platform could not store; the step was redelivered instead. */\nexport type TestWorkflowUnstorableStepError = {\n readonly stepName: string\n readonly attempt: number\n readonly error: unknown\n}\n\nexport type TestWorkflowStepFunction<TArgs extends ReadonlyArray<unknown>, TResult> = ((\n ...args: TArgs\n) => Promise<TResult>) & { readonly maxRetries?: number }\n\n// The platform default: retries after the first attempt; total attempts = maxRetries + 1.\nexport const defaultTestWorkflowStepMaxRetries = 3\n\ntype HookRecord = {\n readonly resolve: (payload: unknown) => void\n readonly reject: (error: TestWorkflowRunCancelledError) => void\n}\n\ntype TestWorkflowRunRecord = {\n readonly runId: string\n status: TestWorkflowRunStatus\n returnValue: unknown\n runError: unknown\n settled: Promise<void>\n readonly chunks: Array<unknown>\n streamClosed: boolean\n streamCloseCount: number\n writeAfterCloseAttempts: number\n readonly changeListeners: Set<() => void>\n readonly hooks: Map<string, HookRecord>\n readonly resumedHookTokens: Set<string>\n stepSequence: number\n readonly stepAttempts: Map<string, number>\n readonly unstorableStepErrors: Array<TestWorkflowUnstorableStepError>\n}\n\ntype AmbientContext = {\n readonly world: TestWorkflowWorld\n readonly run: TestWorkflowRunRecord\n readonly stepMetadata: TestWorkflowStepMetadata | undefined\n}\n\nconst ambientStorage = new AsyncLocalStorage<AmbientContext>()\n\nconst requireAmbient = (): AmbientContext => {\n const ambient = ambientStorage.getStore()\n\n if (ambient === undefined) {\n throw new Error('Workflow ambient API called outside a TestWorkflowWorld run context')\n }\n\n return ambient\n}\n\ntype StepErrorSerializer = {\n /** Undefined when the platform cannot store the value (its `SerializationError`). */\n readonly dehydrate: (error: unknown, runId: string) => Promise<Uint8Array | undefined>\n readonly hydrate: (bytes: Uint8Array, runId: string) => Promise<unknown>\n}\n\nlet stepErrorSerializer: Promise<StepErrorSerializer> | undefined\n\nconst workflowPackageDir = (require: NodeJS.Require) => {\n let dir = path.dirname(require.resolve('workflow'))\n\n while (!fs.existsSync(path.join(dir, 'package.json'))) {\n const parent = path.dirname(dir)\n\n if (parent === dir) throw new Error('Cannot locate the installed workflow package')\n\n dir = parent\n }\n\n return dir\n}\n\n// The installed `workflow` runtime's own step-error serializer (`@workflow/core`, resolved\n// through `workflow`'s package so its version matches the host's), loaded natively: a\n// `vi.mock('workflow')` of the ambient module never replaces it.\nconst loadStepErrorSerializer = (): Promise<StepErrorSerializer> =>\n (stepErrorSerializer ??= (async () => {\n const require = createRequire(import.meta.url)\n\n const serialization: unknown = await import(\n require.resolve('@workflow/core/serialization', { paths: [workflowPackageDir(require)] })\n ).catch((cause: unknown) => {\n // Workflow 5 captures Node `URL` intrinsics when its serializer loads; jsdom's fail.\n throw new Error(\n 'TestWorkflowWorld cannot load the workflow step-error serializer (under jsdom: step execution needs the Node test environment)',\n { cause }\n )\n })\n\n if (\n !Predicate.hasProperty(serialization, 'dehydrateStepError') ||\n !Predicate.hasProperty(serialization, 'hydrateStepError') ||\n !Predicate.isFunction(serialization.dehydrateStepError) ||\n !Predicate.isFunction(serialization.hydrateStepError)\n ) {\n throw new Error('The installed workflow runtime has no step-error serializer')\n }\n\n const { dehydrateStepError, hydrateStepError } = serialization\n\n return {\n dehydrate: async (error, runId) => {\n let bytes: unknown\n\n try {\n bytes = await dehydrateStepError(error, runId, undefined)\n } catch (failure) {\n // The platform reframes every failure to store a value as `SerializationError`; any\n // other failure is this emulator's integration breaking, never the host's error.\n if (Predicate.hasProperty(failure, 'name') && failure.name === 'SerializationError') {\n return undefined\n }\n\n throw failure\n }\n\n if (!(bytes instanceof Uint8Array)) {\n throw new Error('The workflow step-error serializer returned no bytes')\n }\n\n return bytes\n },\n hydrate: async (bytes, runId) => {\n const error: unknown = await hydrateStepError(bytes, runId, undefined)\n\n return error\n }\n }\n })())\n\n// The platform's error shape check (`@workflow/errors`): duck-typed, so it holds across realms.\nconst isPlatformError = (value: unknown) =>\n Predicate.hasProperty(value, 'name') && Predicate.hasProperty(value, 'message')\n\n// `FatalError.is`: named `FatalError`, or carrying `fatal: true`.\nconst isFatalStepError = (value: unknown) =>\n isPlatformError(value) &&\n ((Predicate.hasProperty(value, 'name') && value.name === 'FatalError') ||\n (Predicate.hasProperty(value, 'fatal') && value.fatal === true))\n\n// The platform turns an abort into a FatalError before classifying a step error\n// (`promoteAbortErrorToFatal`), so an aborted step is never retried.\nconst promoteAbortError = (value: unknown) => {\n if (\n !Predicate.hasProperty(value, 'name') ||\n value.name !== 'AbortError' ||\n !Predicate.hasProperty(value, 'message') ||\n !Predicate.isString(value.message) ||\n (Predicate.hasProperty(value, 'stack') &&\n value.stack !== undefined &&\n !Predicate.isString(value.stack)) ||\n isFatalStepError(value)\n ) {\n return value\n }\n\n const fatal = platformFatalError(`Aborted: ${value.message}`, undefined)\n\n if (Predicate.hasProperty(value, 'stack') && Predicate.isString(value.stack)) {\n fatal.stack = value.stack\n }\n\n return fatal\n}\n\n// Stored and read back, an error named `FatalError` is the platform's FatalError.\nconst platformFatalError = (message: string, cause: unknown) => {\n const error = cause === undefined ? new Error(message) : new Error(message, { cause })\n\n error.name = 'FatalError'\n\n return error\n}\n\n// The platform's `normalizeUnknownError` message: an error's message, a string as is, anything\n// else as JSON (else `String`), and an awaited thenable prefixed `Promise rejection: `.\nconst platformErrorMessage = async (value: unknown): Promise<string> => {\n if (Predicate.hasProperty(value, 'then') && Predicate.isFunction(value.then)) {\n try {\n return `Promise rejection: ${await platformErrorMessage(await value)}`\n } catch (rejection) {\n return `Promise rejection: ${await platformErrorMessage(rejection)}`\n }\n }\n\n if (types.isNativeError(value)) return value.message\n\n if (Predicate.isString(value)) return value\n\n try {\n return String(JSON.stringify(value))\n } catch {\n return String(value)\n }\n}\n\nconst retriesLabel = (count: number) => (count === 1 ? 'retry' : 'retries')\n\nexport type TestWorkflowRunInspection = {\n readonly runId: string\n readonly status: TestWorkflowRunStatus\n readonly chunks: ReadonlyArray<unknown>\n readonly streamClosed: boolean\n readonly streamCloseCount: number\n readonly writeAfterCloseAttempts: number\n readonly stepAttempts: ReadonlyMap<string, number>\n readonly runError: unknown\n /** Every thrown step value the platform could not store, in order. */\n readonly unstorableStepErrors: ReadonlyArray<TestWorkflowUnstorableStepError>\n}\n\nexport type TestWorkflowHook<T> = Promise<T> & { readonly [Symbol.dispose]: () => void }\n\ntype TestWorkflowWorldStartResult = { readonly runId: string }\n\nexport class TestWorkflowWorld {\n private readonly runs = new Map<string, TestWorkflowRunRecord>()\n private runSequence = 0\n\n start<TArgs extends ReadonlyArray<unknown>, TResult>(\n workflowFn: (...args: TArgs) => Promise<TResult>,\n args: TArgs\n ): TestWorkflowWorldStartResult {\n this.runSequence += 1\n const runId = `twr_${this.runSequence}`\n\n const run: TestWorkflowRunRecord = {\n runId,\n status: 'pending',\n returnValue: undefined,\n runError: undefined,\n settled: Promise.resolve(),\n chunks: [],\n streamClosed: false,\n streamCloseCount: 0,\n writeAfterCloseAttempts: 0,\n changeListeners: new Set(),\n hooks: new Map(),\n resumedHookTokens: new Set(),\n stepSequence: 0,\n stepAttempts: new Map(),\n unstorableStepErrors: []\n }\n\n this.runs.set(runId, run)\n\n run.settled = ambientStorage.run(\n { world: this, run, stepMetadata: undefined },\n async (): Promise<void> => {\n // Yield once so callers observe `pending` before execution begins,\n // mirroring the platform's enqueue-then-run lifecycle.\n await Promise.resolve()\n\n if (run.status === 'cancelled') return\n\n run.status = 'running'\n\n try {\n run.returnValue = await workflowFn(...args)\n\n if (run.status === 'running') run.status = 'completed'\n } catch (error) {\n run.runError = error\n\n if (run.status === 'running') run.status = 'failed'\n } finally {\n this.notifyChange(run)\n }\n }\n )\n\n return { runId }\n }\n\n async settled(runId: string): Promise<void> {\n await this.requireRun(runId).settled\n }\n\n inspect(runId: string): TestWorkflowRunInspection {\n const run = this.requireRun(runId)\n\n return {\n runId: run.runId,\n status: run.status,\n chunks: [...run.chunks],\n streamClosed: run.streamClosed,\n streamCloseCount: run.streamCloseCount,\n writeAfterCloseAttempts: run.writeAfterCloseAttempts,\n stepAttempts: new Map(run.stepAttempts),\n runError: run.runError,\n unstorableStepErrors: [...run.unstorableStepErrors]\n }\n }\n\n status(runId: string): TestWorkflowRunStatus {\n return this.requireRun(runId).status\n }\n\n async cancel(runId: string): Promise<void> {\n const run = this.requireRun(runId)\n\n if (run.status === 'completed' || run.status === 'failed' || run.status === 'cancelled') {\n throw new TestWorkflowRunConflictError(\n `Workflow run \"${runId}\" is already ${run.status} and cannot be cancelled`\n )\n }\n\n run.status = 'cancelled'\n\n for (const [token, hook] of run.hooks) {\n run.hooks.delete(token)\n hook.reject(new TestWorkflowRunCancelledError(runId))\n }\n\n this.notifyChange(run)\n }\n\n async resumeHook(token: string, payload: unknown): Promise<void> {\n for (const run of this.runs.values()) {\n const hook = run.hooks.get(token)\n\n if (hook !== undefined) {\n run.hooks.delete(token)\n run.resumedHookTokens.add(token)\n hook.resolve(payload)\n\n return\n }\n\n if (run.resumedHookTokens.has(token)) {\n throw new TestWorkflowHookConflictError(token)\n }\n }\n\n throw new TestWorkflowHookNotFoundError(token)\n }\n\n hasResumedHook(token: string): boolean {\n for (const run of this.runs.values()) {\n if (run.resumedHookTokens.has(token)) return true\n }\n\n return false\n }\n\n // --- Step executor (platform retry semantics) ---\n\n // Runs a step body with the platform's retry contract: `fn.maxRetries`\n // retries after the first attempt (total attempts = maxRetries + 1) and\n // 1-based `getStepMetadata().attempt` visible to the body. A FatalError\n // (by `name`, or `fatal: true`; an AbortError is promoted to one) is never\n // retried; an exhausted step fails with the platform's FatalError whose\n // `cause` is the last thrown value. The caller sees errors only as the\n // platform stores and reads them back.\n async runStep<TArgs extends ReadonlyArray<unknown>, TResult>(\n stepFn: TestWorkflowStepFunction<TArgs, TResult>,\n args: TArgs,\n stepName = stepFn.name === '' ? 'step' : stepFn.name\n ): Promise<TResult> {\n const ambient = requireAmbient()\n const run = ambient.run\n run.stepSequence += 1\n const stepId = `${run.runId}:step:${run.stepSequence}:${stepName}`\n const maxRetries = stepFn.maxRetries ?? defaultTestWorkflowStepMaxRetries\n const maxAttempts = maxRetries + 1\n const serializer = await loadStepErrorSerializer()\n\n let attempt = 1\n\n for (;;) {\n run.stepAttempts.set(stepName, (run.stepAttempts.get(stepName) ?? 0) + 1)\n\n let thrown: unknown\n\n try {\n return await ambientStorage.run(\n { world: this, run, stepMetadata: { attempt, stepId, stepName } },\n () => stepFn(...args)\n )\n } catch (error) {\n thrown = error\n }\n\n const effective = promoteAbortError(thrown)\n // Normalized on every attempt, as the platform does: a thrown thenable is awaited here.\n const message = await platformErrorMessage(effective)\n const fatal = isFatalStepError(effective)\n const exhausted = !fatal && attempt >= maxAttempts\n\n // A fatal error is stored as is (abort promoted); an exhausted step's error becomes the\n // cause of the platform's FatalError; a retried attempt stores the thrown value.\n const recorded = fatal\n ? effective\n : exhausted\n ? platformFatalError(\n `Step \"${stepName}\" failed after ${maxRetries} ${retriesLabel(maxRetries)}: ${message}`,\n thrown\n )\n : thrown\n\n const bytes = await serializer.dehydrate(recorded, run.runId)\n\n if (bytes === undefined) {\n // The platform cannot record this attempt: its queue handler fails and the\n // redelivered message runs the step again as the next attempt.\n run.unstorableStepErrors.push({ stepName, attempt, error: thrown })\n\n if (attempt >= maxAttempts) {\n // The redelivery past the budget fails the step before running it again.\n const exceeded = await serializer.dehydrate(\n platformFatalError(\n `Step \"${stepName}\" exceeded max retries (${maxRetries} ${retriesLabel(maxRetries)})`,\n undefined\n ),\n run.runId\n )\n\n if (exceeded === undefined)\n throw new Error('The workflow runtime cannot store a FatalError')\n\n throw await serializer.hydrate(exceeded, run.runId)\n }\n\n attempt += 1\n continue\n }\n\n if (fatal || exhausted) throw await serializer.hydrate(bytes, run.runId)\n\n attempt += 1\n }\n }\n\n // Wraps a step function so orchestration code can invoke it exactly the way\n // the platform invokes `use step` functions: through the retry executor.\n step<TArgs extends ReadonlyArray<unknown>, TResult>(\n stepFn: TestWorkflowStepFunction<TArgs, TResult>,\n stepName?: string\n ): (...args: TArgs) => Promise<TResult> {\n return (...args: TArgs) => this.runStep(stepFn, args, stepName)\n }\n\n // --- Ambient platform APIs (exposed through `testWorkflowModule`) ---\n\n static getWorkflowMetadata(): TestWorkflowMetadata {\n return { workflowRunId: requireAmbient().run.runId }\n }\n\n static getStepMetadata(): TestWorkflowStepMetadata {\n const ambient = requireAmbient()\n\n if (ambient.stepMetadata === undefined) {\n throw new Error('getStepMetadata called outside a step context')\n }\n\n return ambient.stepMetadata\n }\n\n static getWritable<T>(): WritableStream<T> {\n const ambient = requireAmbient()\n\n return ambient.world.makeWritable(ambient.run)\n }\n\n static createHook<T>(input: { readonly token: string }): TestWorkflowHook<T> {\n const ambient = requireAmbient()\n\n return ambient.world.makeHook<T>(ambient.run, input.token)\n }\n\n // --- Durable streams ---\n\n private makeWritable<T>(run: TestWorkflowRunRecord): WritableStream<T> {\n return new WritableStream<T>({\n write: chunk => {\n if (run.streamClosed || run.status === 'cancelled') {\n run.writeAfterCloseAttempts += 1\n throw new TestWorkflowStreamConflictError(run.runId)\n }\n\n run.chunks.push(chunk)\n this.notifyChange(run)\n },\n close: () => {\n if (run.streamClosed) {\n run.streamCloseCount += 1\n throw new TestWorkflowStreamConflictError(run.runId)\n }\n\n run.streamClosed = true\n run.streamCloseCount += 1\n this.notifyChange(run)\n }\n })\n }\n\n private makeHook<T>(run: TestWorkflowRunRecord, token: string): TestWorkflowHook<T> {\n let resolveHook: (payload: unknown) => void = () => {}\n\n let rejectHook: (error: TestWorkflowRunCancelledError) => void = () => {}\n\n const promise = new Promise<T>((resolve, reject) => {\n // SAFETY: Hook payloads are caller-typed on the platform (`createHook<T>`).\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n resolveHook = payload => resolve(payload as T)\n rejectHook = reject\n })\n\n run.hooks.set(token, { resolve: resolveHook, reject: rejectHook })\n\n return Object.assign(promise, {\n [Symbol.dispose]: () => {\n run.hooks.delete(token)\n }\n })\n }\n\n getReadable<T>(\n runId: string,\n options?: VercelWorkflowReadableOptions\n ): VercelWorkflowReadableStream<T> {\n const run = this.requireRun(runId)\n const requestedStart = options?.startIndex ?? 0\n\n let index =\n requestedStart < 0 ? Math.max(0, run.chunks.length + requestedStart) : requestedStart\n\n const stream = new ReadableStream<T>({\n pull: async controller => {\n while (index >= run.chunks.length && !this.streamEnded(run)) {\n await this.nextChange(run)\n }\n\n if (index < run.chunks.length) {\n // SAFETY: The platform readable is caller-typed (`WorkflowReadableStream<R = any>`);\n // the durable log stores opaque chunks, so this coercion mirrors the\n // platform contract exactly.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n controller.enqueue(run.chunks[index] as T)\n index += 1\n\n return\n }\n\n controller.close()\n }\n })\n\n return Object.assign(stream, {\n getTailIndex: () => Promise.resolve(run.chunks.length - 1)\n })\n }\n\n private streamEnded(run: TestWorkflowRunRecord): boolean {\n return run.streamClosed || run.status === 'cancelled'\n }\n\n private notifyChange(run: TestWorkflowRunRecord): void {\n const listeners = [...run.changeListeners]\n run.changeListeners.clear()\n\n for (const listener of listeners) listener()\n }\n\n private nextChange(run: TestWorkflowRunRecord): Promise<void> {\n return new Promise(resolve => {\n run.changeListeners.add(resolve)\n })\n }\n\n private requireRun(runId: string): TestWorkflowRunRecord {\n const run = this.runs.get(runId)\n\n if (run === undefined) throw new TestWorkflowRunNotFoundError(runId)\n\n return run\n }\n\n // --- SDK adapter for `VercelWorkflows.layerFromSdk` ---\n\n private sdkRun<TResult>(run: TestWorkflowRunRecord): VercelWorkflowsSdkRun<TResult> {\n const getReadable = <Chunk>(options?: VercelWorkflowReadableOptions) =>\n this.getReadable<Chunk>(run.runId, options)\n\n const cancel = () => this.cancel(run.runId)\n\n return {\n runId: run.runId,\n getReadable,\n cancel,\n get status() {\n return Promise.resolve(run.status)\n },\n get returnValue() {\n return run.settled.then(() => {\n if (run.status === 'completed') {\n // SAFETY: Return values are caller-typed on the platform SDK as well.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return run.returnValue as TResult\n }\n\n throw run.runError ?? new TestWorkflowRunCancelledError(run.runId)\n })\n }\n }\n }\n\n readonly sdk: VercelWorkflowsSdkClient = {\n start: async (workflowFn, args) => {\n const { runId } = this.start(workflowFn, args)\n\n return this.sdkRun(this.requireRun(runId))\n },\n getRun: <TResult>(runId: string) => this.sdkRun<TResult>(this.requireRun(runId)),\n resumeHook: (token, payload) => this.resumeHook(token, payload)\n }\n}\n\n// Factory for `vi.mock('workflow', () => testWorkflowModule)`: the mocked\n// module surface delegates every ambient platform API to the active world's\n// AsyncLocalStorage context, so production code under test runs unmodified.\nexport const testWorkflowModule = {\n getWorkflowMetadata: () => TestWorkflowWorld.getWorkflowMetadata(),\n getStepMetadata: () => TestWorkflowWorld.getStepMetadata(),\n getWritable: <T>() => TestWorkflowWorld.getWritable<T>(),\n createHook: <T>(input: { readonly token: string }) => TestWorkflowWorld.createHook<T>(input)\n}\n"],"mappings":";;;;;;;AAuCA,IAAa,kCAAb,cAAqD,MAAM;CACzD,OAAyB;CACzB,SAAkB;CAElB,YAAY,OAAe;EACzB,MAAM,iBAAiB,MAAM,2BAA2B;CAC1D;AACF;AAEA,IAAa,+BAAb,cAAkD,MAAM;CACtD,OAAyB;CACzB,SAAkB;CAElB,YAAY,SAAiB;EAC3B,MAAM,OAAO;CACf;AACF;AAEA,IAAa,gCAAb,cAAmD,MAAM;CACvD,OAAyB;CAEzB,YAAY,OAAe;EACzB,MAAM,kBAAkB,MAAM,gBAAgB;C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B,KAA2C;EAC5D,OAAO,IAAI,SAAQ,YAAW;GAC5B,IAAI,gBAAgB,IAAI,OAAO;EACjC,CAAC;CACH;CAEA,WAAmB,OAAsC;EACvD,MAAM,MAAM,KAAK,KAAK,IAAI,KAAK;EAE/B,IAAI,QAAQ,KAAA,GAAW,MAAM,IAAI,6BAA6B,KAAK;EAEnE,OAAO;CACT;CAIA,OAAwB,KAA4D;EAClF,MAAM,eAAsB,YAC1B,KAAK,YAAmB,IAAI,OAAO,OAAO;EAE5C,MAAM,eAAe,KAAK,OAAO,IAAI,KAAK;EAE1C,OAAO;GACL,OAAO,IAAI;GACX;GACA;GACA,IAAI,SAAS;IACX,OAAO,QAAQ,QAAQ,IAAI,MAAM;GACnC;GACA,IAAI,cAAc;IAChB,OAAO,IAAI,QAAQ,WAAW;KAC5B,IAAI,IAAI,WAAW,aAGjB,OAAO,IAAI;KAGb,MAAM,IAAI,YAAY,IAAI,8BAA8B,IAAI,KAAK;IACnE,CAAC;GACH;EACF;CACF;CAEA,MAAyC;EACvC,OAAO,OAAO,YAAY,SAAS;GACjC,MAAM,EAAE,UAAU,KAAK,MAAM,YAAY,IAAI;GAE7C,OAAO,KAAK,OAAO,KAAK,WAAW,KAAK,CAAC;EAC3C;EACA,SAAkB,UAAkB,KAAK,OAAgB,KAAK,WAAW,KAAK,CAAC;EAC/E,aAAa,OAAO,YAAY,KAAK,WAAW,OAAO,OAAO;CAChE;AACF;AAKA,MAAa,qBAAqB;CAChC,2BAA2B,kBAAkB,oBAAoB;CACjE,uBAAuB,kBAAkB,gBAAgB;CACzD,mBAAsB,kBAAkB,YAAe;CACvD,aAAgB,UAAsC,kBAAkB,WAAc,KAAK;AAC7F"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/testing/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport fs from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { types } from 'node:util'\nimport path from 'node:path'\nimport { Predicate } from 'effect'\nimport type {\n VercelWorkflowsSdkClient,\n VercelWorkflowsSdkRun,\n VercelWorkflowReadableOptions,\n VercelWorkflowReadableStream,\n VercelWorkflowRunStatus\n} from '../effect.ts'\n\n// Behavioral emulator of the Vercel Workflow platform for tests: run lifecycle,\n// append-only durable streams with close-once -> 409 write conflicts, a step\n// executor honoring `fn.maxRetries` + `getStepMetadata().attempt`, hooks/resume,\n// and cancellation. Host code under test runs unmodified against it; tests mock\n// only the `workflow` module's ambient APIs, delegating to the active world\n// (see `testWorkflowModule`).\n//\n// Step errors cross the platform boundary the way they do in a deployment: each one is stored with\n// the installed `workflow` runtime's own step-error serializer, and the workflow body sees only the\n// value read back (error tags, prototypes and custom fields are gone; a `cause` survives). A thrown\n// value the serializer cannot store (a class instance anywhere in its `cause` chain) never reaches\n// the body: the platform's queue handler fails and redelivers the step, which runs again until its\n// retries run out and it fails with \"exceeded max retries\" (see `unstorableStepErrors`).\n//\n// The single most important semantic: writing to (or re-closing) a closed\n// durable stream fails with the platform's HTTP 409 \"already completed\"\n// conflict shape. Any code path that performs a terminal stream effect from a\n// retryable step attempt poisons every subsequent platform retry — exactly the\n// #252 production bug. The emulator enforces that invariant permanently.\n\nexport type TestWorkflowRunStatus = VercelWorkflowRunStatus\n\n// Matches the platform's conflict contract: `EntityConflictError.is(value)`\n// checks `value.name === 'EntityConflictError'`, and the Vercel world maps\n// HTTP 409 responses to that class.\nexport class TestWorkflowStreamConflictError extends Error {\n override readonly name = 'EntityConflictError'\n readonly status = 409\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" stream already completed`)\n }\n}\n\nexport class TestWorkflowRunConflictError extends Error {\n override readonly name = 'EntityConflictError'\n readonly status = 409\n\n constructor(message: string) {\n super(message)\n }\n}\n\nexport class TestWorkflowHookNotFoundError extends Error {\n override readonly name = 'HookNotFoundError'\n\n constructor(token: string) {\n super(`Workflow hook \"${token}\" was not found`)\n }\n}\n\nexport class TestWorkflowHookConflictError extends Error {\n override readonly name = 'HookConflictError'\n\n constructor(token: string) {\n super(`Workflow hook \"${token}\" was already resumed`)\n }\n}\n\nexport class TestWorkflowRunNotFoundError extends Error {\n override readonly name = 'WorkflowRunNotFoundError'\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" was not found`)\n }\n}\n\nexport class TestWorkflowRunCancelledError extends Error {\n override readonly name = 'WorkflowRunCancelledError'\n\n constructor(runId: string) {\n super(`Workflow run \"${runId}\" was cancelled`)\n }\n}\n\nexport type TestWorkflowMetadata = { readonly workflowRunId: string }\n\nexport type TestWorkflowStepMetadata = {\n readonly attempt: number\n readonly stepId: string\n readonly stepName: string\n}\n\n/** A thrown step value the platform could not store; the step was redelivered instead. */\nexport type TestWorkflowUnstorableStepError = {\n readonly stepName: string\n readonly attempt: number\n readonly error: unknown\n}\n\nexport type TestWorkflowStepFunction<TArgs extends ReadonlyArray<unknown>, TResult> = ((\n ...args: TArgs\n) => Promise<TResult>) & { readonly maxRetries?: number }\n\n// The platform default: retries after the first attempt; total attempts = maxRetries + 1.\nexport const defaultTestWorkflowStepMaxRetries = 3\n\ntype HookRecord = {\n readonly resolve: (payload: unknown) => void\n readonly reject: (error: TestWorkflowRunCancelledError) => void\n}\n\ntype TestWorkflowRunRecord = {\n readonly runId: string\n readonly attributes: Readonly<Record<string, string>>\n status: TestWorkflowRunStatus\n returnValue: unknown\n runError: unknown\n settled: Promise<void>\n readonly chunks: Array<unknown>\n streamClosed: boolean\n streamCloseCount: number\n writeAfterCloseAttempts: number\n readonly changeListeners: Set<() => void>\n readonly hooks: Map<string, HookRecord>\n readonly resumedHookTokens: Set<string>\n stepSequence: number\n readonly stepAttempts: Map<string, number>\n readonly unstorableStepErrors: Array<TestWorkflowUnstorableStepError>\n}\n\ntype AmbientContext = {\n readonly world: TestWorkflowWorld\n readonly run: TestWorkflowRunRecord\n readonly stepMetadata: TestWorkflowStepMetadata | undefined\n}\n\nconst ambientStorage = new AsyncLocalStorage<AmbientContext>()\n\nconst requireAmbient = (): AmbientContext => {\n const ambient = ambientStorage.getStore()\n\n if (ambient === undefined) {\n throw new Error('Workflow ambient API called outside a TestWorkflowWorld run context')\n }\n\n return ambient\n}\n\ntype StepErrorSerializer = {\n /** Undefined when the platform cannot store the value (its `SerializationError`). */\n readonly dehydrate: (error: unknown, runId: string) => Promise<Uint8Array | undefined>\n readonly hydrate: (bytes: Uint8Array, runId: string) => Promise<unknown>\n}\n\nlet stepErrorSerializer: Promise<StepErrorSerializer> | undefined\n\nconst packageDirOf = (entry: string, name: string) => {\n let dir = path.dirname(entry)\n\n while (!fs.existsSync(path.join(dir, 'package.json'))) {\n const parent = path.dirname(dir)\n\n if (parent === dir) throw new Error(`Cannot locate the installed ${name} package`)\n\n dir = parent\n }\n\n return dir\n}\n\nconst workflowPackageDir = (require: NodeJS.Require) =>\n packageDirOf(require.resolve('workflow'), 'workflow')\n\ntype AttributeChange = { readonly key: string; readonly value: string }\n\nlet attributeValidator: Promise<(changes: ReadonlyArray<AttributeChange>) => void> | undefined\n\n// The installed runtime's own attribute check (`@workflow/world`, as the installed `@workflow/core`\n// resolves it), which the platform's `start()` runs before creating a run.\nconst loadAttributeValidator = () =>\n (attributeValidator ??= (async () => {\n const require = createRequire(import.meta.url)\n\n const coreDir = packageDirOf(\n require.resolve('@workflow/core/serialization', { paths: [workflowPackageDir(require)] }),\n '@workflow/core'\n )\n\n const world: unknown = await import(require.resolve('@workflow/world', { paths: [coreDir] }))\n\n if (\n !Predicate.hasProperty(world, 'validateAttributeChanges') ||\n !Predicate.isFunction(world.validateAttributeChanges)\n ) {\n throw new Error('The installed workflow runtime has no attribute validator')\n }\n\n const { validateAttributeChanges } = world\n\n return (changes: ReadonlyArray<AttributeChange>) => {\n validateAttributeChanges(changes)\n }\n })())\n\n// A start whose attributes the platform refuses fails with its FatalError before any run exists.\nconst validateStartAttributes = async (attributes: Readonly<Record<string, string>>) => {\n const changes = Object.entries(attributes).map(([key, value]) => ({ key, value }))\n\n if (changes.length === 0) return\n\n const validate = await loadAttributeValidator()\n\n try {\n validate(changes)\n } catch (failure) {\n if (\n Predicate.hasProperty(failure, 'name') &&\n failure.name === 'AttributeValidationError' &&\n Predicate.hasProperty(failure, 'message') &&\n Predicate.isString(failure.message)\n ) {\n throw platformFatalError(failure.message, undefined)\n }\n\n throw failure\n }\n}\n\n// The installed `workflow` runtime's own step-error serializer (`@workflow/core`, resolved\n// through `workflow`'s package so its version matches the host's), loaded natively: a\n// `vi.mock('workflow')` of the ambient module never replaces it.\nconst loadStepErrorSerializer = (): Promise<StepErrorSerializer> =>\n (stepErrorSerializer ??= (async () => {\n const require = createRequire(import.meta.url)\n\n const serialization: unknown = await import(\n require.resolve('@workflow/core/serialization', { paths: [workflowPackageDir(require)] })\n ).catch((cause: unknown) => {\n // Workflow 5 captures Node `URL` intrinsics when its serializer loads; jsdom's fail.\n throw new Error(\n 'TestWorkflowWorld cannot load the workflow step-error serializer (under jsdom: step execution needs the Node test environment)',\n { cause }\n )\n })\n\n if (\n !Predicate.hasProperty(serialization, 'dehydrateStepError') ||\n !Predicate.hasProperty(serialization, 'hydrateStepError') ||\n !Predicate.isFunction(serialization.dehydrateStepError) ||\n !Predicate.isFunction(serialization.hydrateStepError)\n ) {\n throw new Error('The installed workflow runtime has no step-error serializer')\n }\n\n const { dehydrateStepError, hydrateStepError } = serialization\n\n return {\n dehydrate: async (error, runId) => {\n let bytes: unknown\n\n try {\n bytes = await dehydrateStepError(error, runId, undefined)\n } catch (failure) {\n // The platform reframes every failure to store a value as `SerializationError`; any\n // other failure is this emulator's integration breaking, never the host's error.\n if (Predicate.hasProperty(failure, 'name') && failure.name === 'SerializationError') {\n return undefined\n }\n\n throw failure\n }\n\n if (!(bytes instanceof Uint8Array)) {\n throw new Error('The workflow step-error serializer returned no bytes')\n }\n\n return bytes\n },\n hydrate: async (bytes, runId) => {\n const error: unknown = await hydrateStepError(bytes, runId, undefined)\n\n return error\n }\n }\n })())\n\n// The platform's error shape check (`@workflow/errors`): duck-typed, so it holds across realms.\nconst isPlatformError = (value: unknown) =>\n Predicate.hasProperty(value, 'name') && Predicate.hasProperty(value, 'message')\n\n// `FatalError.is`: named `FatalError`, or carrying `fatal: true`.\nconst isFatalStepError = (value: unknown) =>\n isPlatformError(value) &&\n ((Predicate.hasProperty(value, 'name') && value.name === 'FatalError') ||\n (Predicate.hasProperty(value, 'fatal') && value.fatal === true))\n\n// The platform turns an abort into a FatalError before classifying a step error\n// (`promoteAbortErrorToFatal`), so an aborted step is never retried.\nconst promoteAbortError = (value: unknown) => {\n if (\n !Predicate.hasProperty(value, 'name') ||\n value.name !== 'AbortError' ||\n !Predicate.hasProperty(value, 'message') ||\n !Predicate.isString(value.message) ||\n (Predicate.hasProperty(value, 'stack') &&\n value.stack !== undefined &&\n !Predicate.isString(value.stack)) ||\n isFatalStepError(value)\n ) {\n return value\n }\n\n const fatal = platformFatalError(`Aborted: ${value.message}`, undefined)\n\n if (Predicate.hasProperty(value, 'stack') && Predicate.isString(value.stack)) {\n fatal.stack = value.stack\n }\n\n return fatal\n}\n\n// Stored and read back, an error named `FatalError` is the platform's FatalError.\nconst platformFatalError = (message: string, cause: unknown) => {\n const error = cause === undefined ? new Error(message) : new Error(message, { cause })\n\n error.name = 'FatalError'\n\n return error\n}\n\n// The platform's `normalizeUnknownError` message: an error's message, a string as is, anything\n// else as JSON (else `String`), and an awaited thenable prefixed `Promise rejection: `.\nconst platformErrorMessage = async (value: unknown): Promise<string> => {\n if (Predicate.hasProperty(value, 'then') && Predicate.isFunction(value.then)) {\n try {\n return `Promise rejection: ${await platformErrorMessage(await value)}`\n } catch (rejection) {\n return `Promise rejection: ${await platformErrorMessage(rejection)}`\n }\n }\n\n if (types.isNativeError(value)) return value.message\n\n if (Predicate.isString(value)) return value\n\n try {\n return String(JSON.stringify(value))\n } catch {\n return String(value)\n }\n}\n\nconst retriesLabel = (count: number) => (count === 1 ? 'retry' : 'retries')\n\nexport type TestWorkflowRunInspection = {\n readonly runId: string\n /** The `attributes` the run was started with through `sdk.start` (`{}` without any). */\n readonly attributes: Readonly<Record<string, string>>\n readonly status: TestWorkflowRunStatus\n readonly chunks: ReadonlyArray<unknown>\n readonly streamClosed: boolean\n readonly streamCloseCount: number\n readonly writeAfterCloseAttempts: number\n readonly stepAttempts: ReadonlyMap<string, number>\n readonly runError: unknown\n /** Every thrown step value the platform could not store, in order. */\n readonly unstorableStepErrors: ReadonlyArray<TestWorkflowUnstorableStepError>\n}\n\nexport type TestWorkflowHook<T> = Promise<T> & { readonly [Symbol.dispose]: () => void }\n\ntype TestWorkflowWorldStartResult = { readonly runId: string }\n\nexport class TestWorkflowWorld {\n private readonly runs = new Map<string, TestWorkflowRunRecord>()\n private runSequence = 0\n\n start<TArgs extends ReadonlyArray<unknown>, TResult>(\n workflowFn: (...args: TArgs) => Promise<TResult>,\n args: TArgs\n ): TestWorkflowWorldStartResult {\n return this.startRun(workflowFn, args, {})\n }\n\n private startRun<TArgs extends ReadonlyArray<unknown>, TResult>(\n workflowFn: (...args: TArgs) => Promise<TResult>,\n args: TArgs,\n attributes: Readonly<Record<string, string>>\n ): TestWorkflowWorldStartResult {\n this.runSequence += 1\n const runId = `twr_${this.runSequence}`\n\n const run: TestWorkflowRunRecord = {\n runId,\n attributes: { ...attributes },\n status: 'pending',\n returnValue: undefined,\n runError: undefined,\n settled: Promise.resolve(),\n chunks: [],\n streamClosed: false,\n streamCloseCount: 0,\n writeAfterCloseAttempts: 0,\n changeListeners: new Set(),\n hooks: new Map(),\n resumedHookTokens: new Set(),\n stepSequence: 0,\n stepAttempts: new Map(),\n unstorableStepErrors: []\n }\n\n this.runs.set(runId, run)\n\n run.settled = ambientStorage.run(\n { world: this, run, stepMetadata: undefined },\n async (): Promise<void> => {\n // Yield once so callers observe `pending` before execution begins,\n // mirroring the platform's enqueue-then-run lifecycle.\n await Promise.resolve()\n\n if (run.status === 'cancelled') return\n\n run.status = 'running'\n\n try {\n run.returnValue = await workflowFn(...args)\n\n if (run.status === 'running') run.status = 'completed'\n } catch (error) {\n run.runError = error\n\n if (run.status === 'running') run.status = 'failed'\n } finally {\n this.notifyChange(run)\n }\n }\n )\n\n return { runId }\n }\n\n async settled(runId: string): Promise<void> {\n await this.requireRun(runId).settled\n }\n\n inspect(runId: string): TestWorkflowRunInspection {\n const run = this.requireRun(runId)\n\n return {\n runId: run.runId,\n attributes: { ...run.attributes },\n status: run.status,\n chunks: [...run.chunks],\n streamClosed: run.streamClosed,\n streamCloseCount: run.streamCloseCount,\n writeAfterCloseAttempts: run.writeAfterCloseAttempts,\n stepAttempts: new Map(run.stepAttempts),\n runError: run.runError,\n unstorableStepErrors: [...run.unstorableStepErrors]\n }\n }\n\n status(runId: string): TestWorkflowRunStatus {\n return this.requireRun(runId).status\n }\n\n async cancel(runId: string): Promise<void> {\n const run = this.requireRun(runId)\n\n if (run.status === 'completed' || run.status === 'failed' || run.status === 'cancelled') {\n throw new TestWorkflowRunConflictError(\n `Workflow run \"${runId}\" is already ${run.status} and cannot be cancelled`\n )\n }\n\n run.status = 'cancelled'\n\n for (const [token, hook] of run.hooks) {\n run.hooks.delete(token)\n hook.reject(new TestWorkflowRunCancelledError(runId))\n }\n\n this.notifyChange(run)\n }\n\n async resumeHook(token: string, payload: unknown): Promise<void> {\n for (const run of this.runs.values()) {\n const hook = run.hooks.get(token)\n\n if (hook !== undefined) {\n run.hooks.delete(token)\n run.resumedHookTokens.add(token)\n hook.resolve(payload)\n\n return\n }\n\n if (run.resumedHookTokens.has(token)) {\n throw new TestWorkflowHookConflictError(token)\n }\n }\n\n throw new TestWorkflowHookNotFoundError(token)\n }\n\n hasResumedHook(token: string): boolean {\n for (const run of this.runs.values()) {\n if (run.resumedHookTokens.has(token)) return true\n }\n\n return false\n }\n\n // --- Step executor (platform retry semantics) ---\n\n // Runs a step body with the platform's retry contract: `fn.maxRetries`\n // retries after the first attempt (total attempts = maxRetries + 1) and\n // 1-based `getStepMetadata().attempt` visible to the body. A FatalError\n // (by `name`, or `fatal: true`; an AbortError is promoted to one) is never\n // retried; an exhausted step fails with the platform's FatalError whose\n // `cause` is the last thrown value. The caller sees errors only as the\n // platform stores and reads them back.\n async runStep<TArgs extends ReadonlyArray<unknown>, TResult>(\n stepFn: TestWorkflowStepFunction<TArgs, TResult>,\n args: TArgs,\n stepName = stepFn.name === '' ? 'step' : stepFn.name\n ): Promise<TResult> {\n const ambient = requireAmbient()\n const run = ambient.run\n run.stepSequence += 1\n const stepId = `${run.runId}:step:${run.stepSequence}:${stepName}`\n const maxRetries = stepFn.maxRetries ?? defaultTestWorkflowStepMaxRetries\n const maxAttempts = maxRetries + 1\n const serializer = await loadStepErrorSerializer()\n\n let attempt = 1\n\n for (;;) {\n run.stepAttempts.set(stepName, (run.stepAttempts.get(stepName) ?? 0) + 1)\n\n let thrown: unknown\n\n try {\n return await ambientStorage.run(\n { world: this, run, stepMetadata: { attempt, stepId, stepName } },\n () => stepFn(...args)\n )\n } catch (error) {\n thrown = error\n }\n\n const effective = promoteAbortError(thrown)\n // Normalized on every attempt, as the platform does: a thrown thenable is awaited here.\n const message = await platformErrorMessage(effective)\n const fatal = isFatalStepError(effective)\n const exhausted = !fatal && attempt >= maxAttempts\n\n // A fatal error is stored as is (abort promoted); an exhausted step's error becomes the\n // cause of the platform's FatalError; a retried attempt stores the thrown value.\n const recorded = fatal\n ? effective\n : exhausted\n ? platformFatalError(\n `Step \"${stepName}\" failed after ${maxRetries} ${retriesLabel(maxRetries)}: ${message}`,\n thrown\n )\n : thrown\n\n const bytes = await serializer.dehydrate(recorded, run.runId)\n\n if (bytes === undefined) {\n // The platform cannot record this attempt: its queue handler fails and the\n // redelivered message runs the step again as the next attempt.\n run.unstorableStepErrors.push({ stepName, attempt, error: thrown })\n\n if (attempt >= maxAttempts) {\n // The redelivery past the budget fails the step before running it again.\n const exceeded = await serializer.dehydrate(\n platformFatalError(\n `Step \"${stepName}\" exceeded max retries (${maxRetries} ${retriesLabel(maxRetries)})`,\n undefined\n ),\n run.runId\n )\n\n if (exceeded === undefined)\n throw new Error('The workflow runtime cannot store a FatalError')\n\n throw await serializer.hydrate(exceeded, run.runId)\n }\n\n attempt += 1\n continue\n }\n\n if (fatal || exhausted) throw await serializer.hydrate(bytes, run.runId)\n\n attempt += 1\n }\n }\n\n // Wraps a step function so orchestration code can invoke it exactly the way\n // the platform invokes `use step` functions: through the retry executor.\n step<TArgs extends ReadonlyArray<unknown>, TResult>(\n stepFn: TestWorkflowStepFunction<TArgs, TResult>,\n stepName?: string\n ): (...args: TArgs) => Promise<TResult> {\n return (...args: TArgs) => this.runStep(stepFn, args, stepName)\n }\n\n // --- Ambient platform APIs (exposed through `testWorkflowModule`) ---\n\n static getWorkflowMetadata(): TestWorkflowMetadata {\n return { workflowRunId: requireAmbient().run.runId }\n }\n\n static getStepMetadata(): TestWorkflowStepMetadata {\n const ambient = requireAmbient()\n\n if (ambient.stepMetadata === undefined) {\n throw new Error('getStepMetadata called outside a step context')\n }\n\n return ambient.stepMetadata\n }\n\n static getWritable<T>(): WritableStream<T> {\n const ambient = requireAmbient()\n\n return ambient.world.makeWritable(ambient.run)\n }\n\n static createHook<T>(input: { readonly token: string }): TestWorkflowHook<T> {\n const ambient = requireAmbient()\n\n return ambient.world.makeHook<T>(ambient.run, input.token)\n }\n\n // --- Durable streams ---\n\n private makeWritable<T>(run: TestWorkflowRunRecord): WritableStream<T> {\n return new WritableStream<T>({\n write: chunk => {\n if (run.streamClosed || run.status === 'cancelled') {\n run.writeAfterCloseAttempts += 1\n throw new TestWorkflowStreamConflictError(run.runId)\n }\n\n run.chunks.push(chunk)\n this.notifyChange(run)\n },\n close: () => {\n if (run.streamClosed) {\n run.streamCloseCount += 1\n throw new TestWorkflowStreamConflictError(run.runId)\n }\n\n run.streamClosed = true\n run.streamCloseCount += 1\n this.notifyChange(run)\n }\n })\n }\n\n private makeHook<T>(run: TestWorkflowRunRecord, token: string): TestWorkflowHook<T> {\n let resolveHook: (payload: unknown) => void = () => {}\n\n let rejectHook: (error: TestWorkflowRunCancelledError) => void = () => {}\n\n const promise = new Promise<T>((resolve, reject) => {\n // SAFETY: Hook payloads are caller-typed on the platform (`createHook<T>`).\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n resolveHook = payload => resolve(payload as T)\n rejectHook = reject\n })\n\n run.hooks.set(token, { resolve: resolveHook, reject: rejectHook })\n\n return Object.assign(promise, {\n [Symbol.dispose]: () => {\n run.hooks.delete(token)\n }\n })\n }\n\n getReadable<T>(\n runId: string,\n options?: VercelWorkflowReadableOptions\n ): VercelWorkflowReadableStream<T> {\n const run = this.requireRun(runId)\n const requestedStart = options?.startIndex ?? 0\n\n let index =\n requestedStart < 0 ? Math.max(0, run.chunks.length + requestedStart) : requestedStart\n\n const stream = new ReadableStream<T>({\n pull: async controller => {\n while (index >= run.chunks.length && !this.streamEnded(run)) {\n await this.nextChange(run)\n }\n\n if (index < run.chunks.length) {\n // SAFETY: The platform readable is caller-typed (`WorkflowReadableStream<R = any>`);\n // the durable log stores opaque chunks, so this coercion mirrors the\n // platform contract exactly.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n controller.enqueue(run.chunks[index] as T)\n index += 1\n\n return\n }\n\n controller.close()\n }\n })\n\n return Object.assign(stream, {\n getTailIndex: () => Promise.resolve(run.chunks.length - 1)\n })\n }\n\n private streamEnded(run: TestWorkflowRunRecord): boolean {\n return run.streamClosed || run.status === 'cancelled'\n }\n\n private notifyChange(run: TestWorkflowRunRecord): void {\n const listeners = [...run.changeListeners]\n run.changeListeners.clear()\n\n for (const listener of listeners) listener()\n }\n\n private nextChange(run: TestWorkflowRunRecord): Promise<void> {\n return new Promise(resolve => {\n run.changeListeners.add(resolve)\n })\n }\n\n private requireRun(runId: string): TestWorkflowRunRecord {\n const run = this.runs.get(runId)\n\n if (run === undefined) throw new TestWorkflowRunNotFoundError(runId)\n\n return run\n }\n\n // --- SDK adapter for `VercelWorkflows.layerFromSdk` ---\n\n private sdkRun<TResult>(run: TestWorkflowRunRecord): VercelWorkflowsSdkRun<TResult> {\n const getReadable = <Chunk>(options?: VercelWorkflowReadableOptions) =>\n this.getReadable<Chunk>(run.runId, options)\n\n const cancel = () => this.cancel(run.runId)\n\n return {\n runId: run.runId,\n getReadable,\n cancel,\n get status() {\n return Promise.resolve(run.status)\n },\n get returnValue() {\n return run.settled.then(() => {\n if (run.status === 'completed') {\n // SAFETY: Return values are caller-typed on the platform SDK as well.\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return run.returnValue as TResult\n }\n\n throw run.runError ?? new TestWorkflowRunCancelledError(run.runId)\n })\n }\n }\n }\n\n readonly sdk: VercelWorkflowsSdkClient = {\n start: async (workflowFn, args, options) => {\n // One snapshot is validated and stored, as the platform stores its validated changes.\n const attributes = { ...options?.attributes }\n\n await validateStartAttributes(attributes)\n\n const { runId } = this.startRun(workflowFn, args, attributes)\n\n return this.sdkRun(this.requireRun(runId))\n },\n getRun: <TResult>(runId: string) => this.sdkRun<TResult>(this.requireRun(runId)),\n resumeHook: (token, payload) => this.resumeHook(token, payload)\n }\n}\n\n// Factory for `vi.mock('workflow', () => testWorkflowModule)`: the mocked\n// module surface delegates every ambient platform API to the active world's\n// AsyncLocalStorage context, so production code under test runs unmodified.\nexport const testWorkflowModule = {\n getWorkflowMetadata: () => TestWorkflowWorld.getWorkflowMetadata(),\n getStepMetadata: () => TestWorkflowWorld.getStepMetadata(),\n getWritable: <T>() => TestWorkflowWorld.getWritable<T>(),\n createHook: <T>(input: { readonly token: string }) => TestWorkflowWorld.createHook<T>(input)\n}\n"],"mappings":";;;;;;;AAuCA,IAAa,kCAAb,cAAqD,MAAM;CACzD,OAAyB;CACzB,SAAkB;CAElB,YAAY,OAAe;EACzB,MAAM,iBAAiB,MAAM,2BAA2B;CAC1D;AACF;AAEA,IAAa,+BAAb,cAAkD,MAAM;CACtD,OAAyB;CACzB,SAAkB;CAElB,YAAY,SAAiB;EAC3B,MAAM,OAAO;CACf;AACF;AAEA,IAAa,gCAAb,cAAmD,MAAM;CACvD,OAAyB;CAEzB,YAAY,OAAe;EACzB,MAAM,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OAAO;EACjC,CAAC;CACH;CAEA,WAAmB,OAAsC;EACvD,MAAM,MAAM,KAAK,KAAK,IAAI,KAAK;EAE/B,IAAI,QAAQ,KAAA,GAAW,MAAM,IAAI,6BAA6B,KAAK;EAEnE,OAAO;CACT;CAIA,OAAwB,KAA4D;EAClF,MAAM,eAAsB,YAC1B,KAAK,YAAmB,IAAI,OAAO,OAAO;EAE5C,MAAM,eAAe,KAAK,OAAO,IAAI,KAAK;EAE1C,OAAO;GACL,OAAO,IAAI;GACX;GACA;GACA,IAAI,SAAS;IACX,OAAO,QAAQ,QAAQ,IAAI,MAAM;GACnC;GACA,IAAI,cAAc;IAChB,OAAO,IAAI,QAAQ,WAAW;KAC5B,IAAI,IAAI,WAAW,aAGjB,OAAO,IAAI;KAGb,MAAM,IAAI,YAAY,IAAI,8BAA8B,IAAI,KAAK;IACnE,CAAC;GACH;EACF;CACF;CAEA,MAAyC;EACvC,OAAO,OAAO,YAAY,MAAM,YAAY;GAE1C,MAAM,aAAa,EAAE,GAAG,SAAS,WAAW;GAE5C,MAAM,wBAAwB,UAAU;GAExC,MAAM,EAAE,UAAU,KAAK,SAAS,YAAY,MAAM,UAAU;GAE5D,OAAO,KAAK,OAAO,KAAK,WAAW,KAAK,CAAC;EAC3C;EACA,SAAkB,UAAkB,KAAK,OAAgB,KAAK,WAAW,KAAK,CAAC;EAC/E,aAAa,OAAO,YAAY,KAAK,WAAW,OAAO,OAAO;CAChE;AACF;AAKA,MAAa,qBAAqB;CAChC,2BAA2B,kBAAkB,oBAAoB;CACjE,uBAAuB,kBAAkB,gBAAgB;CACzD,mBAAsB,kBAAkB,YAAe;CACvD,aAAgB,UAAsC,kBAAkB,WAAc,KAAK;AAC7F"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolk-sdk/vercel-workflows",
3
- "version": "0.1.0-canary.136",
3
+ "version": "0.1.0-canary.138",
4
4
  "description": "Vercel Workflow orchestration primitives for Yolk agent loops.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/effect.ts CHANGED
@@ -34,6 +34,16 @@ export type VercelWorkflowReadableStream<Chunk> = WorkflowReadableStream<Chunk>
34
34
 
35
35
  export type VercelWorkflowRunStatus = WorkflowRun['status']
36
36
 
37
+ /**
38
+ * Options for starting a run. `attributes` seeds the run's plaintext, searchable metadata at
39
+ * creation (no extra event). The platform validates them before creating the run and the start
40
+ * fails on an invalid one: keys of 1-256 characters not starting with `$` (reserved), values of at
41
+ * most 256 UTF-8 bytes, at most 64 per run. Never put secrets or content in them.
42
+ */
43
+ export type VercelWorkflowStartOptions = {
44
+ readonly attributes?: Readonly<Record<string, string>>
45
+ }
46
+
37
47
  export type VercelWorkflowsSdkRun<TResult> = {
38
48
  readonly runId: string
39
49
  readonly getReadable: <Chunk>(
@@ -47,7 +57,8 @@ export type VercelWorkflowsSdkRun<TResult> = {
47
57
  export type VercelWorkflowsSdkClient = {
48
58
  readonly start: <TArgs extends unknown[], TResult>(
49
59
  workflow: VercelWorkflowFunction<TArgs, TResult>,
50
- args: TArgs
60
+ args: TArgs,
61
+ options?: VercelWorkflowStartOptions
51
62
  ) => Promise<VercelWorkflowsSdkRun<TResult>>
52
63
  readonly getRun: <TResult>(runId: string) => VercelWorkflowsSdkRun<TResult>
53
64
  readonly resumeHook: (token: string, payload: unknown) => Promise<void>
@@ -66,7 +77,8 @@ export type VercelWorkflowRun<TResult> = {
66
77
  export type VercelWorkflowsClient = {
67
78
  readonly start: <TArgs extends unknown[], TResult>(
68
79
  workflow: VercelWorkflowFunction<TArgs, TResult>,
69
- args: TArgs
80
+ args: TArgs,
81
+ options?: VercelWorkflowStartOptions
70
82
  ) => Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError>
71
83
  readonly getRun: <TResult>(
72
84
  runId: string
@@ -136,8 +148,12 @@ const makeWorkflowRun = <TResult>(
136
148
  const VercelWorkflowsSdkLive = Layer.succeed(VercelWorkflowsSdk, {
137
149
  start: <TArgs extends unknown[], TResult>(
138
150
  workflow: VercelWorkflowFunction<TArgs, TResult>,
139
- args: TArgs
140
- ) => workflowStart(workflow, args),
151
+ args: TArgs,
152
+ options?: VercelWorkflowStartOptions
153
+ ) =>
154
+ options?.attributes === undefined
155
+ ? workflowStart(workflow, args)
156
+ : workflowStart(workflow, args, { attributes: { ...options.attributes } }),
141
157
  getRun: <TResult>(runId: string) => workflowGetRun<TResult>(runId),
142
158
  resumeHook: async (token: string, payload: unknown) => {
143
159
  await workflowResumeHook<unknown>(token, payload)
@@ -166,9 +182,10 @@ export class VercelWorkflows extends Context.Service<VercelWorkflows, VercelWork
166
182
  return {
167
183
  start: <TArgs extends unknown[], TResult>(
168
184
  workflow: VercelWorkflowFunction<TArgs, TResult>,
169
- args: TArgs
185
+ args: TArgs,
186
+ options?: VercelWorkflowStartOptions
170
187
  ): Effect.Effect<VercelWorkflowRun<TResult>, VercelWorkflowsError> =>
171
- trySdkPromise('start', () => sdk.start(workflow, args)).pipe(
188
+ trySdkPromise('start', () => sdk.start(workflow, args, options)).pipe(
172
189
  Effect.map(makeWorkflowRun),
173
190
  Effect.withSpan('VercelWorkflows.start')
174
191
  ),
@@ -116,6 +116,7 @@ type HookRecord = {
116
116
 
117
117
  type TestWorkflowRunRecord = {
118
118
  readonly runId: string
119
+ readonly attributes: Readonly<Record<string, string>>
119
120
  status: TestWorkflowRunStatus
120
121
  returnValue: unknown
121
122
  runError: unknown
@@ -158,13 +159,13 @@ type StepErrorSerializer = {
158
159
 
159
160
  let stepErrorSerializer: Promise<StepErrorSerializer> | undefined
160
161
 
161
- const workflowPackageDir = (require: NodeJS.Require) => {
162
- let dir = path.dirname(require.resolve('workflow'))
162
+ const packageDirOf = (entry: string, name: string) => {
163
+ let dir = path.dirname(entry)
163
164
 
164
165
  while (!fs.existsSync(path.join(dir, 'package.json'))) {
165
166
  const parent = path.dirname(dir)
166
167
 
167
- if (parent === dir) throw new Error('Cannot locate the installed workflow package')
168
+ if (parent === dir) throw new Error(`Cannot locate the installed ${name} package`)
168
169
 
169
170
  dir = parent
170
171
  }
@@ -172,6 +173,64 @@ const workflowPackageDir = (require: NodeJS.Require) => {
172
173
  return dir
173
174
  }
174
175
 
176
+ const workflowPackageDir = (require: NodeJS.Require) =>
177
+ packageDirOf(require.resolve('workflow'), 'workflow')
178
+
179
+ type AttributeChange = { readonly key: string; readonly value: string }
180
+
181
+ let attributeValidator: Promise<(changes: ReadonlyArray<AttributeChange>) => void> | undefined
182
+
183
+ // The installed runtime's own attribute check (`@workflow/world`, as the installed `@workflow/core`
184
+ // resolves it), which the platform's `start()` runs before creating a run.
185
+ const loadAttributeValidator = () =>
186
+ (attributeValidator ??= (async () => {
187
+ const require = createRequire(import.meta.url)
188
+
189
+ const coreDir = packageDirOf(
190
+ require.resolve('@workflow/core/serialization', { paths: [workflowPackageDir(require)] }),
191
+ '@workflow/core'
192
+ )
193
+
194
+ const world: unknown = await import(require.resolve('@workflow/world', { paths: [coreDir] }))
195
+
196
+ if (
197
+ !Predicate.hasProperty(world, 'validateAttributeChanges') ||
198
+ !Predicate.isFunction(world.validateAttributeChanges)
199
+ ) {
200
+ throw new Error('The installed workflow runtime has no attribute validator')
201
+ }
202
+
203
+ const { validateAttributeChanges } = world
204
+
205
+ return (changes: ReadonlyArray<AttributeChange>) => {
206
+ validateAttributeChanges(changes)
207
+ }
208
+ })())
209
+
210
+ // A start whose attributes the platform refuses fails with its FatalError before any run exists.
211
+ const validateStartAttributes = async (attributes: Readonly<Record<string, string>>) => {
212
+ const changes = Object.entries(attributes).map(([key, value]) => ({ key, value }))
213
+
214
+ if (changes.length === 0) return
215
+
216
+ const validate = await loadAttributeValidator()
217
+
218
+ try {
219
+ validate(changes)
220
+ } catch (failure) {
221
+ if (
222
+ Predicate.hasProperty(failure, 'name') &&
223
+ failure.name === 'AttributeValidationError' &&
224
+ Predicate.hasProperty(failure, 'message') &&
225
+ Predicate.isString(failure.message)
226
+ ) {
227
+ throw platformFatalError(failure.message, undefined)
228
+ }
229
+
230
+ throw failure
231
+ }
232
+ }
233
+
175
234
  // The installed `workflow` runtime's own step-error serializer (`@workflow/core`, resolved
176
235
  // through `workflow`'s package so its version matches the host's), loaded natively: a
177
236
  // `vi.mock('workflow')` of the ambient module never replaces it.
@@ -300,6 +359,8 @@ const retriesLabel = (count: number) => (count === 1 ? 'retry' : 'retries')
300
359
 
301
360
  export type TestWorkflowRunInspection = {
302
361
  readonly runId: string
362
+ /** The `attributes` the run was started with through `sdk.start` (`{}` without any). */
363
+ readonly attributes: Readonly<Record<string, string>>
303
364
  readonly status: TestWorkflowRunStatus
304
365
  readonly chunks: ReadonlyArray<unknown>
305
366
  readonly streamClosed: boolean
@@ -322,12 +383,21 @@ export class TestWorkflowWorld {
322
383
  start<TArgs extends ReadonlyArray<unknown>, TResult>(
323
384
  workflowFn: (...args: TArgs) => Promise<TResult>,
324
385
  args: TArgs
386
+ ): TestWorkflowWorldStartResult {
387
+ return this.startRun(workflowFn, args, {})
388
+ }
389
+
390
+ private startRun<TArgs extends ReadonlyArray<unknown>, TResult>(
391
+ workflowFn: (...args: TArgs) => Promise<TResult>,
392
+ args: TArgs,
393
+ attributes: Readonly<Record<string, string>>
325
394
  ): TestWorkflowWorldStartResult {
326
395
  this.runSequence += 1
327
396
  const runId = `twr_${this.runSequence}`
328
397
 
329
398
  const run: TestWorkflowRunRecord = {
330
399
  runId,
400
+ attributes: { ...attributes },
331
401
  status: 'pending',
332
402
  returnValue: undefined,
333
403
  runError: undefined,
@@ -383,6 +453,7 @@ export class TestWorkflowWorld {
383
453
 
384
454
  return {
385
455
  runId: run.runId,
456
+ attributes: { ...run.attributes },
386
457
  status: run.status,
387
458
  chunks: [...run.chunks],
388
459
  streamClosed: run.streamClosed,
@@ -708,8 +779,13 @@ export class TestWorkflowWorld {
708
779
  }
709
780
 
710
781
  readonly sdk: VercelWorkflowsSdkClient = {
711
- start: async (workflowFn, args) => {
712
- const { runId } = this.start(workflowFn, args)
782
+ start: async (workflowFn, args, options) => {
783
+ // One snapshot is validated and stored, as the platform stores its validated changes.
784
+ const attributes = { ...options?.attributes }
785
+
786
+ await validateStartAttributes(attributes)
787
+
788
+ const { runId } = this.startRun(workflowFn, args, attributes)
713
789
 
714
790
  return this.sdkRun(this.requireRun(runId))
715
791
  },