workflow 5.0.0-beta.1 → 5.0.0-beta.2
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 +4 -4
- package/dist/api-workflow.js +1 -1
- package/dist/api.js +1 -1
- package/dist/astro.js +1 -1
- package/dist/index.js +1 -1
- package/dist/internal/builtins.js +1 -1
- package/dist/internal/class-serialization.js +1 -1
- package/dist/internal/errors.js +1 -1
- package/dist/nest.js +1 -1
- package/dist/next.cjs +1 -1
- package/dist/nitro.js +1 -1
- package/dist/nuxt.js +1 -1
- package/dist/observability.js +1 -1
- package/dist/runtime.js +1 -1
- package/dist/stdlib.js +1 -1
- package/dist/sveltekit.js +1 -1
- package/dist/typescript-plugin.cjs +1 -1
- package/dist/vite.js +1 -1
- package/dist/workflow.js +1 -1
- package/docs/ai/resumable-streams.mdx +1 -1
- package/docs/api-reference/workflow/create-webhook.mdx +37 -18
- package/docs/api-reference/workflow/get-workflow-metadata.mdx +34 -0
- package/docs/api-reference/workflow-ai/durable-agent.mdx +0 -4
- package/docs/api-reference/workflow-ai/index.mdx +0 -5
- package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +0 -4
- package/docs/cookbook/advanced/custom-serialization.mdx +168 -0
- package/docs/cookbook/advanced/durable-objects.mdx +148 -0
- package/docs/cookbook/advanced/isomorphic-packages.mdx +145 -0
- package/docs/cookbook/advanced/meta.json +10 -0
- package/docs/cookbook/advanced/publishing-libraries.mdx +279 -0
- package/docs/cookbook/advanced/serializable-steps.mdx +135 -0
- package/docs/cookbook/agent-patterns/durable-agent.mdx +191 -0
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +278 -0
- package/docs/cookbook/agent-patterns/meta.json +10 -0
- package/docs/cookbook/agent-patterns/stop-workflow.mdx +216 -0
- package/docs/cookbook/agent-patterns/tool-orchestration.mdx +255 -0
- package/docs/cookbook/agent-patterns/tool-streaming.mdx +181 -0
- package/docs/cookbook/common-patterns/batching.mdx +179 -0
- package/docs/cookbook/common-patterns/child-workflows.mdx +372 -0
- package/docs/cookbook/common-patterns/content-router.mdx +207 -0
- package/docs/cookbook/common-patterns/fan-out.mdx +208 -0
- package/docs/cookbook/common-patterns/idempotency.mdx +107 -0
- package/docs/cookbook/common-patterns/meta.json +15 -0
- package/docs/cookbook/common-patterns/rate-limiting.mdx +228 -0
- package/docs/cookbook/common-patterns/saga.mdx +152 -0
- package/docs/cookbook/common-patterns/scheduling.mdx +249 -0
- package/docs/cookbook/common-patterns/webhooks.mdx +185 -0
- package/docs/cookbook/index.mdx +41 -0
- package/docs/cookbook/integrations/ai-sdk.mdx +204 -0
- package/docs/cookbook/integrations/chat-sdk.mdx +203 -0
- package/docs/cookbook/integrations/meta.json +4 -0
- package/docs/cookbook/integrations/sandbox.mdx +128 -0
- package/docs/cookbook/meta.json +5 -0
- package/docs/deploying/world/local-world.mdx +1 -1
- package/docs/deploying/world/postgres-world.mdx +1 -1
- package/docs/deploying/world/vercel-world.mdx +1 -1
- package/docs/errors/start-invalid-workflow-function.mdx +1 -1
- package/docs/getting-started/index.mdx +8 -1
- package/docs/getting-started/meta.json +2 -1
- package/docs/getting-started/python.mdx +165 -0
- package/docs/meta.json +1 -0
- package/docs/migration-guides/index.mdx +34 -0
- package/docs/migration-guides/meta.json +9 -0
- package/docs/migration-guides/migrating-from-aws-step-functions.mdx +311 -0
- package/docs/migration-guides/migrating-from-inngest.mdx +282 -0
- package/docs/migration-guides/migrating-from-temporal.mdx +284 -0
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +296 -0
- package/package.json +13 -13
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Durable Objects
|
|
3
|
+
description: Model long-lived stateful entities as workflows that persist state across requests.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Build a durable counter or session object whose state survives restarts by using a workflow's event log as the persistence layer.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
<Callout>
|
|
9
|
+
This is an advanced guide. It dives into workflow internals and is not required reading to use workflow.
|
|
10
|
+
</Callout>
|
|
11
|
+
|
|
12
|
+
## The Idea
|
|
13
|
+
|
|
14
|
+
A workflow's event log already records every step result and replays them to reconstruct state. This is the same property that makes an "object" durable — its fields survive cold starts, crashes, and redeployments. Instead of using a workflow to model a *process*, you can use one to model an *entity* with methods.
|
|
15
|
+
|
|
16
|
+
Each "method call" is a hook that the object's workflow loop awaits. External callers resume the hook with a payload describing the operation. The workflow applies the operation, updates its internal state, and waits for the next call.
|
|
17
|
+
|
|
18
|
+
## Pattern: Durable Counter
|
|
19
|
+
|
|
20
|
+
A counter that persists its value without a database. Each increment/decrement is recorded in the event log.
|
|
21
|
+
|
|
22
|
+
```typescript lineNumbers
|
|
23
|
+
import { defineHook, getWorkflowMetadata } from "workflow";
|
|
24
|
+
import { z } from "zod";
|
|
25
|
+
|
|
26
|
+
const counterAction = defineHook({ // [!code highlight]
|
|
27
|
+
schema: z.object({
|
|
28
|
+
type: z.enum(["increment", "decrement", "get"]),
|
|
29
|
+
amount: z.number().default(1),
|
|
30
|
+
}),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
export async function durableCounter() {
|
|
34
|
+
"use workflow";
|
|
35
|
+
|
|
36
|
+
let count = 0;
|
|
37
|
+
const { workflowRunId } = getWorkflowMetadata();
|
|
38
|
+
|
|
39
|
+
while (true) {
|
|
40
|
+
const hook = counterAction.create({ token: `counter:${workflowRunId}` });
|
|
41
|
+
const action = await hook; // [!code highlight]
|
|
42
|
+
|
|
43
|
+
switch (action.type) {
|
|
44
|
+
case "increment":
|
|
45
|
+
count += action.amount;
|
|
46
|
+
await recordState(count);
|
|
47
|
+
break;
|
|
48
|
+
case "decrement":
|
|
49
|
+
count -= action.amount;
|
|
50
|
+
await recordState(count);
|
|
51
|
+
break;
|
|
52
|
+
case "get":
|
|
53
|
+
await emitValue(count);
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function recordState(count: number) {
|
|
60
|
+
"use step";
|
|
61
|
+
// Step records the state transition in the event log.
|
|
62
|
+
// On replay, the step result restores `count` without re-executing.
|
|
63
|
+
return count;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function emitValue(count: number) {
|
|
67
|
+
"use step";
|
|
68
|
+
return { count };
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Calling the Object
|
|
73
|
+
|
|
74
|
+
From an API route, resume the hook to "invoke a method" on the durable object:
|
|
75
|
+
|
|
76
|
+
```typescript lineNumbers
|
|
77
|
+
import { resumeHook } from "workflow/api";
|
|
78
|
+
|
|
79
|
+
export async function POST(request: Request) {
|
|
80
|
+
const { runId, type, amount } = await request.json();
|
|
81
|
+
await resumeHook(`counter:${runId}`, { type, amount }); // [!code highlight]
|
|
82
|
+
return Response.json({ ok: true });
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Pattern: Durable Session
|
|
87
|
+
|
|
88
|
+
A chat session where conversation history is the durable state. Each user message is a hook event; the workflow accumulates messages and generates responses.
|
|
89
|
+
|
|
90
|
+
```typescript lineNumbers
|
|
91
|
+
import { defineHook, getWritable, getWorkflowMetadata } from "workflow";
|
|
92
|
+
import { DurableAgent } from "@workflow/ai/agent";
|
|
93
|
+
import { anthropic } from "@workflow/ai/anthropic";
|
|
94
|
+
import { z } from "zod";
|
|
95
|
+
import type { UIMessageChunk, ModelMessage } from "ai";
|
|
96
|
+
|
|
97
|
+
const messageHook = defineHook({ // [!code highlight]
|
|
98
|
+
schema: z.object({
|
|
99
|
+
role: z.literal("user"),
|
|
100
|
+
content: z.string(),
|
|
101
|
+
}),
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
export async function durableSession() {
|
|
105
|
+
"use workflow";
|
|
106
|
+
|
|
107
|
+
const writable = getWritable<UIMessageChunk>();
|
|
108
|
+
const { workflowRunId: runId } = getWorkflowMetadata();
|
|
109
|
+
const messages: ModelMessage[] = [];
|
|
110
|
+
|
|
111
|
+
const agent = new DurableAgent({
|
|
112
|
+
model: anthropic("claude-sonnet-4-20250514"),
|
|
113
|
+
instructions: "You are a helpful assistant.",
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
while (true) {
|
|
117
|
+
const hook = messageHook.create({ token: `session:${runId}` });
|
|
118
|
+
const userMessage = await hook; // [!code highlight]
|
|
119
|
+
|
|
120
|
+
messages.push({
|
|
121
|
+
role: userMessage.role,
|
|
122
|
+
content: userMessage.content,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
await agent.stream({ messages, writable });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## When to Use This
|
|
131
|
+
|
|
132
|
+
- **Entity-per-workflow**: Each user, document, or device gets its own workflow run. The run ID is the entity ID.
|
|
133
|
+
- **No external database needed**: State lives in the event log. Reads replay from the log; writes append to it.
|
|
134
|
+
- **Automatic consistency**: Only one execution runs at a time per workflow run, so there are no race conditions on the entity's state.
|
|
135
|
+
|
|
136
|
+
## Trade-offs
|
|
137
|
+
|
|
138
|
+
- **Read latency**: Accessing current state requires replaying the event log (or caching the last known state in a step result).
|
|
139
|
+
- **Not a replacement for databases**: If you need to query across entities (e.g., "all counters above 100"), you still need a database. Durable objects are for single-entity state.
|
|
140
|
+
- **Log growth**: Long-lived objects accumulate large event logs. Consider periodic "snapshot" steps that checkpoint the full state.
|
|
141
|
+
|
|
142
|
+
## Key APIs
|
|
143
|
+
|
|
144
|
+
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
|
|
145
|
+
- [`"use step"`](/docs/api-reference/workflow/use-step) — marks functions for durable execution
|
|
146
|
+
- [`defineHook`](/docs/api-reference/workflow/define-hook) — type-safe hook for receiving external method calls
|
|
147
|
+
- [`getWorkflowMetadata`](/docs/api-reference/workflow/get-workflow-metadata) — access the run ID for deterministic hook tokens
|
|
148
|
+
- [`resumeHook`](/docs/api-reference/workflow-api/resume-hook) — invoke a method on the durable object from an API route
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Isomorphic Packages
|
|
3
|
+
description: Publish reusable workflow packages that work both inside and outside the workflow runtime.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Use try/catch around getWorkflowMetadata, dynamic imports, and optional peer dependencies to build libraries that run in workflows and in plain Node.js.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
<Callout>
|
|
9
|
+
This is an advanced guide. It dives into workflow internals and is not required reading to use workflow.
|
|
10
|
+
</Callout>
|
|
11
|
+
|
|
12
|
+
## The Challenge
|
|
13
|
+
|
|
14
|
+
If you're a library author publishing a package that integrates with workflow, your code needs to handle two environments:
|
|
15
|
+
|
|
16
|
+
1. **Inside a workflow run** — `getWorkflowMetadata()` works, `"use step"` directives are transformed, and the full workflow runtime is available.
|
|
17
|
+
2. **Outside a workflow** — your package is imported in a regular Node.js process, a test suite, or a project that doesn't use workflow at all.
|
|
18
|
+
|
|
19
|
+
A hard dependency on `workflow` will crash at import time for users who don't have it installed.
|
|
20
|
+
|
|
21
|
+
## Pattern 1: Feature-Detect with `getWorkflowMetadata`
|
|
22
|
+
|
|
23
|
+
Use a try/catch to detect whether you're running inside a workflow. This lets you add durable behavior when available and fall back to standard execution otherwise.
|
|
24
|
+
|
|
25
|
+
```typescript lineNumbers
|
|
26
|
+
import { getWorkflowMetadata } from "workflow";
|
|
27
|
+
|
|
28
|
+
export async function processPayment(amount: number, currency: string) {
|
|
29
|
+
"use workflow";
|
|
30
|
+
|
|
31
|
+
let runId: string | undefined;
|
|
32
|
+
try {
|
|
33
|
+
const metadata = getWorkflowMetadata(); // [!code highlight]
|
|
34
|
+
runId = metadata.workflowRunId;
|
|
35
|
+
} catch {
|
|
36
|
+
// Not running inside a workflow — proceed without durability
|
|
37
|
+
runId = undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (runId) {
|
|
41
|
+
// Inside a workflow: use the run ID as an idempotency key
|
|
42
|
+
return await chargeWithIdempotency(amount, currency, runId); // [!code highlight]
|
|
43
|
+
} else {
|
|
44
|
+
// Outside a workflow: standard charge
|
|
45
|
+
return await chargeStandard(amount, currency);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function chargeWithIdempotency(amount: number, currency: string, idempotencyKey: string) {
|
|
50
|
+
"use step";
|
|
51
|
+
// Stripe charge with idempotency key from workflow run ID
|
|
52
|
+
return { charged: true, amount, currency, idempotencyKey };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function chargeStandard(amount: number, currency: string) {
|
|
56
|
+
"use step";
|
|
57
|
+
return { charged: true, amount, currency };
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Pattern 2: Dynamic Imports
|
|
62
|
+
|
|
63
|
+
Avoid importing `workflow` at the top level. Use dynamic `import()` so the module is only loaded when actually needed.
|
|
64
|
+
|
|
65
|
+
```typescript lineNumbers
|
|
66
|
+
export async function createDurableTask(name: string, payload: unknown) {
|
|
67
|
+
"use workflow";
|
|
68
|
+
|
|
69
|
+
let sleep: ((duration: string) => Promise<void>) | undefined;
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
const wf = await import("workflow"); // [!code highlight]
|
|
73
|
+
sleep = wf.sleep;
|
|
74
|
+
} catch {
|
|
75
|
+
// workflow not installed — use setTimeout fallback
|
|
76
|
+
sleep = undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
await executeTask(name, payload);
|
|
80
|
+
|
|
81
|
+
if (sleep) {
|
|
82
|
+
// Inside workflow: durable sleep that survives restarts
|
|
83
|
+
await sleep("5m"); // [!code highlight]
|
|
84
|
+
} else {
|
|
85
|
+
// Outside workflow: plain timer (not durable)
|
|
86
|
+
await new Promise((resolve) => setTimeout(resolve, 5 * 60 * 1000));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
await sendNotification(name);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function executeTask(name: string, payload: unknown) {
|
|
93
|
+
"use step";
|
|
94
|
+
return { executed: true, name, payload };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function sendNotification(name: string) {
|
|
98
|
+
"use step";
|
|
99
|
+
return { notified: true, name };
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Pattern 3: Optional Peer Dependencies
|
|
104
|
+
|
|
105
|
+
In your `package.json`, declare `workflow` as an optional peer dependency. This signals to package managers that your library *can* use workflow but doesn't require it.
|
|
106
|
+
|
|
107
|
+
```json
|
|
108
|
+
{
|
|
109
|
+
"name": "@acme/payments",
|
|
110
|
+
"peerDependencies": {
|
|
111
|
+
"workflow": ">=1.0.0"
|
|
112
|
+
},
|
|
113
|
+
"peerDependenciesMeta": {
|
|
114
|
+
"workflow": {
|
|
115
|
+
"optional": true
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Then guard all workflow imports with dynamic `import()` and try/catch as shown above.
|
|
122
|
+
|
|
123
|
+
## Real-World Examples
|
|
124
|
+
|
|
125
|
+
### Mux AI
|
|
126
|
+
|
|
127
|
+
The Mux team published a reusable workflow package for video processing. Their library detects the workflow runtime and falls back to standard async processing when workflow isn't available.
|
|
128
|
+
|
|
129
|
+
### World ID
|
|
130
|
+
|
|
131
|
+
World ID's identity verification library uses `getWorkflowMetadata()` to attach run IDs to their human-in-the-loop verification hooks, but the same library works in non-workflow environments for simple verification flows.
|
|
132
|
+
|
|
133
|
+
## Guidelines for Library Authors
|
|
134
|
+
|
|
135
|
+
1. **Never hard-import `workflow` at the top level** if your package should work without it.
|
|
136
|
+
2. **Use `getWorkflowMetadata()` in a try/catch** as the canonical runtime detection pattern.
|
|
137
|
+
3. **Mark `workflow` as an optional peer dependency** in `package.json`.
|
|
138
|
+
4. **Test both paths**: run your test suite with and without the workflow runtime to catch import errors.
|
|
139
|
+
5. **Document the dual behavior**: make it clear in your README which features require workflow and which work standalone.
|
|
140
|
+
|
|
141
|
+
## Key APIs
|
|
142
|
+
|
|
143
|
+
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
|
|
144
|
+
- [`"use step"`](/docs/api-reference/workflow/use-step) — marks functions for durable execution
|
|
145
|
+
- [`getWorkflowMetadata`](/docs/api-reference/workflow/get-workflow-metadata) — runtime detection and run ID access
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Publishing Libraries
|
|
3
|
+
description: Structure and publish npm packages that export workflow functions for consumers to use with Workflow SDK.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Learn how to build, export, and test npm packages that ship workflow and step functions — including package.json exports, re-exporting for stable workflow IDs, keeping step I/O clean, and integration testing.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
<Callout>
|
|
9
|
+
This is an advanced guide for library authors who want to publish reusable workflow functions as npm packages. It assumes familiarity with `"use workflow"`, `"use step"`, and the workflow execution model.
|
|
10
|
+
</Callout>
|
|
11
|
+
|
|
12
|
+
## Package Structure
|
|
13
|
+
|
|
14
|
+
A workflow library follows a standard TypeScript package layout with a dedicated `workflows/` directory. Each workflow file exports one or more workflow functions that consumers can import and pass to `start()`.
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
my-media-lib/
|
|
18
|
+
├── src/
|
|
19
|
+
│ ├── index.ts # Package entry point
|
|
20
|
+
│ ├── types.ts # Shared types
|
|
21
|
+
│ ├── workflows/
|
|
22
|
+
│ │ ├── index.ts # Re-exports all workflows
|
|
23
|
+
│ │ ├── transcode.ts # Workflow: transcode a video
|
|
24
|
+
│ │ └── generate-thumbnails.ts
|
|
25
|
+
│ └── lib/
|
|
26
|
+
│ └── api-client.ts # Internal helpers (NOT steps)
|
|
27
|
+
├── test-server/
|
|
28
|
+
│ └── workflows.ts # Re-export for integration tests
|
|
29
|
+
├── tsup.config.ts
|
|
30
|
+
├── package.json
|
|
31
|
+
└── tsconfig.json
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Entry Points and Exports
|
|
35
|
+
|
|
36
|
+
Use the `exports` field in `package.json` to expose separate entry points for the main API and the raw workflow functions:
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{
|
|
40
|
+
"name": "@acme/media",
|
|
41
|
+
"type": "module",
|
|
42
|
+
"exports": {
|
|
43
|
+
".": {
|
|
44
|
+
"types": { "import": "./dist/index.d.ts" },
|
|
45
|
+
"import": "./dist/index.js"
|
|
46
|
+
},
|
|
47
|
+
"./workflows": {
|
|
48
|
+
"types": { "import": "./dist/workflows/index.d.ts" },
|
|
49
|
+
"import": "./dist/workflows/index.js"
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"files": ["dist"]
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The main entry point (`@acme/media`) exports types, utilities, and convenience wrappers. The `./workflows` entry point (`@acme/media/workflows`) exports the raw workflow functions that consumers need for the build system.
|
|
57
|
+
|
|
58
|
+
### Source Files
|
|
59
|
+
|
|
60
|
+
The package entry re-exports workflows alongside any utilities:
|
|
61
|
+
|
|
62
|
+
```typescript lineNumbers
|
|
63
|
+
// src/index.ts
|
|
64
|
+
export * from "./types";
|
|
65
|
+
export * as workflows from "./workflows";
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The workflows barrel file re-exports each workflow:
|
|
69
|
+
|
|
70
|
+
```typescript lineNumbers
|
|
71
|
+
// src/workflows/index.ts
|
|
72
|
+
export * from "./transcode";
|
|
73
|
+
export * from "./generate-thumbnails";
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Build Configuration
|
|
77
|
+
|
|
78
|
+
Use a bundler like `tsup` with separate entry points for each export. Mark `workflow` as external so it's resolved from the consumer's project:
|
|
79
|
+
|
|
80
|
+
```typescript lineNumbers
|
|
81
|
+
// tsup.config.ts
|
|
82
|
+
import { defineConfig } from "tsup";
|
|
83
|
+
|
|
84
|
+
export default defineConfig({
|
|
85
|
+
entry: [
|
|
86
|
+
"src/index.ts",
|
|
87
|
+
"src/workflows/index.ts",
|
|
88
|
+
],
|
|
89
|
+
format: ["esm"],
|
|
90
|
+
dts: true,
|
|
91
|
+
sourcemap: true,
|
|
92
|
+
clean: true,
|
|
93
|
+
external: ["workflow"], // [!code highlight]
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Re-Exporting for Workflow ID Stability
|
|
98
|
+
|
|
99
|
+
Workflow SDK's compiler assigns each workflow function a stable ID based on its position in the source file that the build system processes. When a consumer imports a pre-built workflow from an npm package, the compiler never sees the original source — it only sees the compiled output. This means workflow IDs won't match between the library's development environment and the consumer's app.
|
|
100
|
+
|
|
101
|
+
The fix is a **re-export file**. The consumer creates a file in their `workflows/` directory that re-exports the library's workflows. The build system then processes this file and assigns stable IDs.
|
|
102
|
+
|
|
103
|
+
### Consumer Setup
|
|
104
|
+
|
|
105
|
+
```typescript lineNumbers
|
|
106
|
+
// workflows/media.ts (in the consumer's project)
|
|
107
|
+
// Re-export library workflows so the build system assigns stable IDs
|
|
108
|
+
export * from "@acme/media/workflows"; // [!code highlight]
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
This one-line file is all that's needed. The workflow compiler transforms this file, discovers the workflow and step functions from the library, and assigns IDs that are stable across deployments.
|
|
112
|
+
|
|
113
|
+
### Why This Is Necessary
|
|
114
|
+
|
|
115
|
+
Without re-exporting, the workflow runtime cannot match a running workflow to its function definition. When a workflow run is replayed after a cold start, the runtime looks up functions by their compiler-assigned IDs. If the IDs don't exist (because the compiler never processed the library's source), replay fails.
|
|
116
|
+
|
|
117
|
+
The re-export pattern ensures:
|
|
118
|
+
|
|
119
|
+
1. **Stable IDs** — the compiler assigns IDs based on the consumer's source tree
|
|
120
|
+
2. **Replay safety** — IDs persist across deployments and cold starts
|
|
121
|
+
3. **Version upgrades** — re-exported IDs remain stable as long as the consumer's file doesn't change
|
|
122
|
+
|
|
123
|
+
## Keeping Step I/O Clean
|
|
124
|
+
|
|
125
|
+
When you publish a workflow library, every step function's inputs and outputs are recorded in the event log. This has two implications:
|
|
126
|
+
|
|
127
|
+
### 1. Everything Must Be Serializable
|
|
128
|
+
|
|
129
|
+
Step inputs and outputs must be serializable. The workflow runtime supports a rich set of types beyond plain JSON — including `Date`, `RegExp`, `Map`, `Set`, `BigInt`, `Uint8Array`, `URL`, `Error`, and class instances that implement [custom class serialization](/docs/cookbook/advanced/custom-serialization). See the [serialization reference](/docs/foundations/serialization) for the full list of supported types. Do not pass or return:
|
|
130
|
+
|
|
131
|
+
- Functions or closures
|
|
132
|
+
- `WeakRef`, `WeakMap`, or `WeakSet`
|
|
133
|
+
|
|
134
|
+
If your library works with complex objects that don't implement custom class serialization, pass serializable configuration into steps and reconstruct the objects inside the step body.
|
|
135
|
+
|
|
136
|
+
{/* @skip-typecheck - good/bad comparison with duplicate function names */}
|
|
137
|
+
```typescript lineNumbers
|
|
138
|
+
// Good: pass serializable config, construct inside the step
|
|
139
|
+
async function callExternalApi(endpoint: string, params: Record<string, string>) {
|
|
140
|
+
"use step";
|
|
141
|
+
const client = createApiClient(process.env.API_KEY!);
|
|
142
|
+
return await client.request(endpoint, params);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Bad: pass a pre-constructed client object
|
|
146
|
+
async function callExternalApi(client: ApiClient, params: Record<string, string>) {
|
|
147
|
+
"use step";
|
|
148
|
+
// ApiClient is not serializable — this will fail on replay
|
|
149
|
+
return await client.request(params);
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
See [Serializable Steps](/docs/cookbook/advanced/serializable-steps) for the step-as-factory pattern.
|
|
154
|
+
|
|
155
|
+
### 2. Credentials
|
|
156
|
+
|
|
157
|
+
With workflow encryption enabled, credentials passed as step arguments are encrypted in the event log, so either approach is valid:
|
|
158
|
+
|
|
159
|
+
{/* @skip-typecheck - good/bad comparison with duplicate function names */}
|
|
160
|
+
```typescript lineNumbers
|
|
161
|
+
// Option A: resolve credentials from environment inside the step
|
|
162
|
+
async function fetchData(query: string) {
|
|
163
|
+
"use step";
|
|
164
|
+
const client = createClient(process.env.API_KEY!);
|
|
165
|
+
return await client.fetch(query);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Option B: pass credentials as step arguments (encrypted in the event log)
|
|
169
|
+
async function fetchData(apiKey: string, query: string) {
|
|
170
|
+
"use step";
|
|
171
|
+
const client = createClient(apiKey);
|
|
172
|
+
return await client.fetch(query);
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
The choice is a matter of library API design preference. Resolving from environment variables keeps the step signature simpler, while passing credentials explicitly makes dependencies visible and can be easier to test.
|
|
177
|
+
|
|
178
|
+
## Testing Workflow Libraries
|
|
179
|
+
|
|
180
|
+
Library authors need integration tests that exercise workflows through the full Workflow SDK runtime — not just unit tests of individual functions.
|
|
181
|
+
|
|
182
|
+
### Test Server Pattern
|
|
183
|
+
|
|
184
|
+
Create a minimal test server that re-exports your library's workflows, just like a consumer would:
|
|
185
|
+
|
|
186
|
+
```typescript lineNumbers
|
|
187
|
+
// test-server/workflows.ts
|
|
188
|
+
export * from "@acme/media/workflows"; // [!code highlight]
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
This test server acts as a stand-in consumer app. Point your test runner at it to exercise the full workflow lifecycle: start, replay, and completion.
|
|
192
|
+
|
|
193
|
+
### Vitest Configuration
|
|
194
|
+
|
|
195
|
+
Use a dedicated Vitest config for integration tests that run against the Workflow SDK runtime:
|
|
196
|
+
|
|
197
|
+
```typescript lineNumbers
|
|
198
|
+
// vitest.workflowsdk.config.ts
|
|
199
|
+
import { defineConfig } from "vitest/config";
|
|
200
|
+
|
|
201
|
+
export default defineConfig({
|
|
202
|
+
test: {
|
|
203
|
+
include: ["tests/integration/**/*.workflowsdk.test.ts"],
|
|
204
|
+
testTimeout: 120_000, // Workflows may take time to complete
|
|
205
|
+
setupFiles: ["./tests/setup.ts"],
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
Run these tests separately from your unit tests:
|
|
211
|
+
|
|
212
|
+
```bash
|
|
213
|
+
# Unit tests (fast, no workflow runtime)
|
|
214
|
+
pnpm vitest run tests/unit
|
|
215
|
+
|
|
216
|
+
# Integration tests (requires workflow runtime)
|
|
217
|
+
pnpm vitest run --config vitest.workflowsdk.config.ts
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
### What to Test
|
|
221
|
+
|
|
222
|
+
- **Happy path**: workflow starts, all steps execute, and the final result is correct
|
|
223
|
+
- **Serialization round-trip**: inputs and outputs survive the event log
|
|
224
|
+
- **Replay**: kill and restart a workflow mid-execution to verify deterministic replay
|
|
225
|
+
- **Error handling**: verify that step failures produce the expected errors
|
|
226
|
+
|
|
227
|
+
## Working With and Without Workflow Installed
|
|
228
|
+
|
|
229
|
+
If your library should work both as a standalone package and inside Workflow SDK, declare `workflow` as an optional peer dependency:
|
|
230
|
+
|
|
231
|
+
```json
|
|
232
|
+
{
|
|
233
|
+
"peerDependencies": {
|
|
234
|
+
"workflow": ">=4.0.0"
|
|
235
|
+
},
|
|
236
|
+
"peerDependenciesMeta": {
|
|
237
|
+
"workflow": {
|
|
238
|
+
"optional": true
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Use dynamic imports and runtime detection so your library gracefully degrades when workflow is not installed:
|
|
245
|
+
|
|
246
|
+
```typescript lineNumbers
|
|
247
|
+
async function isWorkflowRuntime(): Promise<boolean> {
|
|
248
|
+
try {
|
|
249
|
+
const wf = await import("workflow");
|
|
250
|
+
if (typeof wf.getWorkflowMetadata !== "function") return false;
|
|
251
|
+
wf.getWorkflowMetadata(); // [!code highlight]
|
|
252
|
+
return true;
|
|
253
|
+
} catch {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
See [Isomorphic Packages](/docs/cookbook/advanced/isomorphic-packages) for the full pattern including feature detection, dynamic imports, and dual-path execution.
|
|
260
|
+
|
|
261
|
+
## Checklist
|
|
262
|
+
|
|
263
|
+
Before publishing a workflow library:
|
|
264
|
+
|
|
265
|
+
- [ ] `workflow` is listed as an **optional** peer dependency
|
|
266
|
+
- [ ] Separate `./workflows` export in `package.json` for the raw workflow functions
|
|
267
|
+
- [ ] `workflow` is marked as **external** in your bundler config
|
|
268
|
+
- [ ] Documentation tells consumers to re-export from `@your-lib/workflows`
|
|
269
|
+
- [ ] Credentials are either resolved from environment variables or passed explicitly (both are safe with encryption enabled)
|
|
270
|
+
- [ ] All step I/O uses [supported serializable types](/docs/foundations/serialization)
|
|
271
|
+
- [ ] Integration tests use a test server with re-exported workflows
|
|
272
|
+
- [ ] Both with-workflow and without-workflow code paths are tested
|
|
273
|
+
|
|
274
|
+
## Key APIs
|
|
275
|
+
|
|
276
|
+
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
|
|
277
|
+
- [`"use step"`](/docs/api-reference/workflow/use-step) — marks functions for durable execution
|
|
278
|
+
- [`start`](/docs/api-reference/workflow/start) — starts a workflow run
|
|
279
|
+
- [`getWorkflowMetadata`](/docs/api-reference/workflow/get-workflow-metadata) — runtime detection and run ID access
|