@upstash/workflow 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/README.md +9 -0
  2. package/astro.d.mts +19 -2
  3. package/astro.d.ts +19 -2
  4. package/astro.js +670 -159
  5. package/astro.mjs +1 -1
  6. package/{chunk-DRHEHWMS.mjs → chunk-J3PXPHSB.mjs} +828 -317
  7. package/cloudflare.d.mts +17 -2
  8. package/cloudflare.d.ts +17 -2
  9. package/cloudflare.js +670 -159
  10. package/cloudflare.mjs +1 -1
  11. package/docs/agents/examples.mdx +8 -0
  12. package/docs/agents/features.mdx +374 -0
  13. package/docs/agents/getting-started.mdx +139 -0
  14. package/docs/agents/overview.mdx +40 -0
  15. package/docs/agents/patterns/evaluator-optimizer.mdx +72 -0
  16. package/docs/agents/patterns/orchestrator-workers.mdx +95 -0
  17. package/docs/agents/patterns/parallelization.mdx +77 -0
  18. package/docs/agents/patterns/prompt-chaining.mdx +84 -0
  19. package/docs/basics/best-practices/at-least-one-step.mdx +57 -0
  20. package/docs/basics/best-practices/business-logic-in-steps.mdx +52 -0
  21. package/docs/basics/best-practices/deterministic-code.mdx +132 -0
  22. package/docs/basics/best-practices/idempotency.mdx +38 -0
  23. package/docs/basics/best-practices/nested-context-methods.mdx +38 -0
  24. package/docs/basics/best-practices/overview.mdx +35 -0
  25. package/docs/basics/best-practices/promise-any.mdx +9 -0
  26. package/docs/basics/best-practices/return-step-results.mdx +80 -0
  27. package/docs/basics/best-practices/workflow-limits.mdx +62 -0
  28. package/docs/basics/client/cancel.mdx +137 -0
  29. package/docs/basics/client/dlq/callback.mdx +21 -0
  30. package/docs/basics/client/dlq/delete.mdx +120 -0
  31. package/docs/basics/client/dlq/list.mdx +96 -0
  32. package/docs/basics/client/dlq/restart.mdx +164 -0
  33. package/docs/basics/client/dlq/resume.mdx +167 -0
  34. package/docs/basics/client/logs.mdx +139 -0
  35. package/docs/basics/client/notify.mdx +79 -0
  36. package/docs/basics/client/trigger.mdx +139 -0
  37. package/docs/basics/client/waiters.mdx +31 -0
  38. package/docs/basics/client.mdx +40 -0
  39. package/docs/basics/how.mdx +65 -0
  40. package/docs/basics/serve/advanced.mdx +435 -0
  41. package/docs/basics/serve.mdx +142 -0
  42. package/docs/changelog.mdx +174 -0
  43. package/docs/examples/allInOne.mdx +377 -0
  44. package/docs/examples/authWebhook.mdx +567 -0
  45. package/docs/examples/customRetry.mdx +309 -0
  46. package/docs/examples/customerOnboarding.mdx +230 -0
  47. package/docs/examples/dynamicWorkflow.mdx +203 -0
  48. package/docs/examples/eCommerceOrderFulfillment.mdx +281 -0
  49. package/docs/examples/imageProcessing.mdx +339 -0
  50. package/docs/examples/paymentRetry.mdx +438 -0
  51. package/docs/examples/waitForEvent.mdx +201 -0
  52. package/docs/features/dlq/callback.mdx +42 -0
  53. package/docs/features/dlq/delete.mdx +29 -0
  54. package/docs/features/dlq/restart.mdx +33 -0
  55. package/docs/features/dlq/resume.mdx +37 -0
  56. package/docs/features/dlq.mdx +39 -0
  57. package/docs/features/failure-callback.mdx +102 -0
  58. package/docs/features/failureFunction/advanced.mdx +36 -0
  59. package/docs/features/failureFunction/reliability.mdx +33 -0
  60. package/docs/features/flow-control/monitor.mdx +22 -0
  61. package/docs/features/flow-control/parallelism.mdx +45 -0
  62. package/docs/features/flow-control/rate-period.mdx +46 -0
  63. package/docs/features/flow-control.mdx +164 -0
  64. package/docs/features/invoke/serveMany.mdx +109 -0
  65. package/docs/features/invoke.mdx +39 -0
  66. package/docs/features/notify.mdx +127 -0
  67. package/docs/features/parallel-steps.mdx +41 -0
  68. package/docs/features/retries/prevent-retries.mdx +140 -0
  69. package/docs/features/retries.mdx +93 -0
  70. package/docs/features/wait-for-event.mdx +104 -0
  71. package/docs/features/wait.mdx +44 -0
  72. package/docs/features/webhooks.mdx +116 -0
  73. package/docs/getstarted.mdx +200 -0
  74. package/docs/howto/cancel.mdx +50 -0
  75. package/docs/howto/changes.mdx +33 -0
  76. package/docs/howto/configure.mdx +42 -0
  77. package/docs/howto/failures.mdx +185 -0
  78. package/docs/howto/get-token.mdx +18 -0
  79. package/docs/howto/local-development/development-server.mdx +130 -0
  80. package/docs/howto/local-development/local-tunnel.mdx +73 -0
  81. package/docs/howto/middlewares.mdx +263 -0
  82. package/docs/howto/migrations.mdx +335 -0
  83. package/docs/howto/multi-region.mdx +107 -0
  84. package/docs/howto/parallel-runs.mdx +52 -0
  85. package/docs/howto/readonly-token.mdx +19 -0
  86. package/docs/howto/realtime/basic.mdx +315 -0
  87. package/docs/howto/realtime/human-in-the-loop.mdx +454 -0
  88. package/docs/howto/redact-fields.mdx +61 -0
  89. package/docs/howto/retry-now.mdx +41 -0
  90. package/docs/howto/schedule.mdx +104 -0
  91. package/docs/howto/security.mdx +143 -0
  92. package/docs/howto/singleton.mdx +137 -0
  93. package/docs/howto/start.mdx +69 -0
  94. package/docs/howto/use-webhooks.mdx +256 -0
  95. package/docs/integrations/aisdk.mdx +316 -0
  96. package/docs/integrations/anthropic.mdx +51 -0
  97. package/docs/integrations/datadog.mdx +69 -0
  98. package/docs/integrations/openai.mdx +87 -0
  99. package/docs/integrations/prometheus.mdx +65 -0
  100. package/docs/integrations/resend.mdx +82 -0
  101. package/docs/llms-txt.mdx +4 -0
  102. package/docs/openapi.yaml +2944 -0
  103. package/docs/pricing.mdx +22 -0
  104. package/docs/quickstarts/astro.mdx +185 -0
  105. package/docs/quickstarts/cloudflare-workers.mdx +190 -0
  106. package/docs/quickstarts/express.mdx +190 -0
  107. package/docs/quickstarts/fastapi.mdx +282 -0
  108. package/docs/quickstarts/flask.mdx +282 -0
  109. package/docs/quickstarts/hono.mdx +221 -0
  110. package/docs/quickstarts/nextjs-fastapi.mdx +147 -0
  111. package/docs/quickstarts/nextjs-flask.mdx +147 -0
  112. package/docs/quickstarts/nuxt.mdx +169 -0
  113. package/docs/quickstarts/platforms.mdx +78 -0
  114. package/docs/quickstarts/solidjs.mdx +161 -0
  115. package/docs/quickstarts/svelte.mdx +170 -0
  116. package/docs/quickstarts/tanstack-start.mdx +205 -0
  117. package/docs/quickstarts/vercel-nextjs.mdx +233 -0
  118. package/docs/roadmap.mdx +8 -0
  119. package/docs/sdk/workflow-js.mdx +4 -0
  120. package/docs/sdk/workflow-py.mdx +4 -0
  121. package/docs/steps/api.mdx +64 -0
  122. package/docs/steps/call.mdx +183 -0
  123. package/docs/steps/cancel.mdx +25 -0
  124. package/docs/steps/createWebhook.mdx +40 -0
  125. package/docs/steps/invoke.mdx +100 -0
  126. package/docs/steps/notify.mdx +105 -0
  127. package/docs/steps/run.mdx +150 -0
  128. package/docs/steps/sleep.mdx +97 -0
  129. package/docs/steps/sleepUntil.mdx +88 -0
  130. package/docs/steps/waitForEvent.mdx +60 -0
  131. package/docs/steps/waitForWebhook.mdx +78 -0
  132. package/docs/steps.mdx +108 -0
  133. package/docs/troubleshooting/general.mdx +331 -0
  134. package/docs/troubleshooting/vercel.mdx +82 -0
  135. package/express.d.mts +19 -2
  136. package/express.d.ts +19 -2
  137. package/express.js +670 -159
  138. package/express.mjs +1 -1
  139. package/h3.d.mts +19 -2
  140. package/h3.d.ts +19 -2
  141. package/h3.js +670 -159
  142. package/h3.mjs +1 -1
  143. package/hono.d.mts +17 -2
  144. package/hono.d.ts +17 -2
  145. package/hono.js +670 -159
  146. package/hono.mjs +1 -1
  147. package/index.d.mts +50 -21
  148. package/index.d.ts +50 -21
  149. package/index.js +686 -171
  150. package/index.mjs +17 -13
  151. package/nextjs.d.mts +40 -2
  152. package/nextjs.d.ts +40 -2
  153. package/nextjs.js +670 -159
  154. package/nextjs.mjs +1 -1
  155. package/package.json +1 -1
  156. package/react-router.d.mts +16 -2
  157. package/react-router.d.ts +16 -2
  158. package/react-router.js +670 -159
  159. package/react-router.mjs +1 -1
  160. package/{serve-many-CG3BFvO3.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
  161. package/{serve-many-iJF1IUXk.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
  162. package/solidjs.d.mts +10 -1
  163. package/solidjs.d.ts +10 -1
  164. package/solidjs.js +670 -159
  165. package/solidjs.mjs +1 -1
  166. package/src/platforms/astro.ts +84 -0
  167. package/src/platforms/cloudflare.ts +127 -0
  168. package/src/platforms/express.ts +147 -0
  169. package/src/platforms/h3.ts +105 -0
  170. package/src/platforms/hono.ts +103 -0
  171. package/src/platforms/nextjs.ts +193 -0
  172. package/src/platforms/react-router.ts +92 -0
  173. package/src/platforms/solidjs.ts +59 -0
  174. package/src/platforms/svelte.ts +99 -0
  175. package/src/platforms/tanstack.ts +96 -0
  176. package/src/src/client/dlq.ts +387 -0
  177. package/src/src/client/filter-types.ts +166 -0
  178. package/src/src/client/index.ts +350 -0
  179. package/src/src/client/types.ts +501 -0
  180. package/src/src/client/utils.ts +307 -0
  181. package/src/src/constants.ts +82 -0
  182. package/src/src/context/api/anthropic.ts +58 -0
  183. package/src/src/context/api/base.ts +52 -0
  184. package/src/src/context/api/index.ts +24 -0
  185. package/src/src/context/api/openai.ts +125 -0
  186. package/src/src/context/api/resend.ts +57 -0
  187. package/src/src/context/auto-executor.ts +707 -0
  188. package/src/src/context/context.ts +681 -0
  189. package/src/src/context/index.ts +1 -0
  190. package/src/src/context/provider.ts +37 -0
  191. package/src/src/context/steps.ts +965 -0
  192. package/src/src/error.ts +203 -0
  193. package/src/src/index.ts +13 -0
  194. package/src/src/middleware/default-callbacks.ts +20 -0
  195. package/src/src/middleware/index.ts +2 -0
  196. package/src/src/middleware/logging.ts +39 -0
  197. package/src/src/middleware/manager.ts +148 -0
  198. package/src/src/middleware/middleware.ts +46 -0
  199. package/src/src/middleware/types.ts +72 -0
  200. package/src/src/qstash/headers.ts +397 -0
  201. package/src/src/qstash/step-config.ts +268 -0
  202. package/src/src/qstash/submit-steps.ts +284 -0
  203. package/src/src/serve/authorization.ts +118 -0
  204. package/src/src/serve/index.ts +475 -0
  205. package/src/src/serve/multi-region/handlers.ts +225 -0
  206. package/src/src/serve/multi-region/utils.ts +88 -0
  207. package/src/src/serve/options.ts +241 -0
  208. package/src/src/serve/serve-many.ts +117 -0
  209. package/src/src/serve/utils.ts +11 -0
  210. package/src/src/types.ts +590 -0
  211. package/src/src/utils.ts +141 -0
  212. package/src/src/workflow-parser.ts +472 -0
  213. package/src/src/workflow-requests.ts +575 -0
  214. package/svelte.d.mts +17 -2
  215. package/svelte.d.ts +17 -2
  216. package/svelte.js +670 -159
  217. package/svelte.mjs +1 -1
  218. package/tanstack.d.mts +15 -2
  219. package/tanstack.d.ts +15 -2
  220. package/tanstack.js +670 -159
  221. package/tanstack.mjs +1 -1
  222. package/{types-CekOpKvz.d.ts → types-CrgK5P6p.d.mts} +372 -32
  223. package/{types-CekOpKvz.d.mts → types-CrgK5P6p.d.ts} +372 -32
@@ -0,0 +1,681 @@
1
+ import type {
2
+ CallResponse,
3
+ CallSettings,
4
+ LazyInvokeStepParams,
5
+ NotifyStepResponse,
6
+ StepSettings,
7
+ Telemetry,
8
+ WaitEventOptions,
9
+ WaitStepResponse,
10
+ WorkflowClient,
11
+ } from "../types";
12
+ import { type StepFunction, type Step } from "../types";
13
+ import { AutoExecutor } from "./auto-executor";
14
+ import type { BaseLazyStep, WaitForWebhookResponse, Webhook } from "./steps";
15
+ import {
16
+ LazyCallStep,
17
+ LazyCreateWebhookStep,
18
+ LazyFunctionStep,
19
+ LazyInvokeStep,
20
+ LazyNotifyStep,
21
+ LazySleepStep,
22
+ LazySleepUntilStep,
23
+ LazyWaitForEventStep,
24
+ LazyWaitForWebhookStep,
25
+ } from "./steps";
26
+ import { isInstanceOf, WorkflowCancelAbort, WorkflowNonRetryableError } from "../error";
27
+ import type { Duration } from "../types";
28
+ import { WorkflowApi } from "./api";
29
+ import { getNewUrlFromWorkflowId } from "../serve/serve-many";
30
+ import { MiddlewareManager } from "../middleware/manager";
31
+ import { QstashError } from "@upstash/qstash";
32
+ import { validateFlowControl, validateLabel } from "../utils";
33
+ import type { EffectiveConfig, NormalizedFlowControl } from "../qstash/step-config";
34
+ import { normalizeStepSettings } from "../qstash/step-config";
35
+
36
+ /**
37
+ * Upstash Workflow context
38
+ *
39
+ * See the docs for fields and methods https://upstash.com/docs/qstash/workflows/basics/context
40
+ *
41
+ * Code outside steps runs again on every request of the run. Anything it branches on or
42
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
43
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
44
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
45
+ * result.
46
+ *
47
+ * @see node_modules/@upstash/workflow/docs/steps.mdx
48
+ * @see node_modules/@upstash/workflow/docs/basics/best-practices/deterministic-code.mdx
49
+ * @see node_modules/@upstash/workflow/docs/basics/best-practices/business-logic-in-steps.mdx
50
+ */
51
+ export class WorkflowContext<TInitialPayload = unknown> {
52
+ protected readonly executor: AutoExecutor;
53
+ protected readonly steps: Step[];
54
+
55
+ /**
56
+ * QStash client of the workflow
57
+ *
58
+ * Can be overwritten by passing `qstashClient` parameter in `serve`:
59
+ *
60
+ * ```ts
61
+ * import { Client } from "@upstash/qstash"
62
+ * import { serve } from "@upstash/workflow/nextjs"
63
+ *
64
+ * export const { POST } = serve(
65
+ * async (context) => {
66
+ * ...
67
+ * },
68
+ * {
69
+ * qstashClient: new Client({...})
70
+ * }
71
+ * )
72
+ * ```
73
+ */
74
+ public readonly qstashClient: WorkflowClient;
75
+ /**
76
+ * Run id of the workflow
77
+ */
78
+ public readonly workflowRunId: string;
79
+ /**
80
+ * Creation time of the workflow run
81
+ */
82
+ public readonly workflowRunCreatedAt: number;
83
+ /**
84
+ * URL of the workflow
85
+ *
86
+ * Can be overwritten by passing a `url` parameter in `serve`:
87
+ *
88
+ * ```ts
89
+ * export const { POST } = serve(
90
+ * async (context) => {
91
+ * ...
92
+ * },
93
+ * {
94
+ * url: "new-url-value"
95
+ * }
96
+ * )
97
+ * ```
98
+ */
99
+ public readonly url: string;
100
+ /**
101
+ * Payload of the request which started the workflow.
102
+ *
103
+ * To specify its type, you can define `serve` as follows:
104
+ *
105
+ * ```ts
106
+ * // set requestPayload type to MyPayload:
107
+ * export const { POST } = serve<MyPayload>(
108
+ * async (context) => {
109
+ * ...
110
+ * }
111
+ * )
112
+ * ```
113
+ *
114
+ * By default, `serve` tries to apply `JSON.parse` to the request payload.
115
+ * If your payload is encoded in a format other than JSON, you can utilize
116
+ * the `initialPayloadParser` parameter:
117
+ *
118
+ * ```ts
119
+ * export const { POST } = serve<MyPayload>(
120
+ * async (context) => {
121
+ * ...
122
+ * },
123
+ * {
124
+ * initialPayloadParser: (initialPayload) => {return doSomething(initialPayload)}
125
+ * }
126
+ * )
127
+ * ```
128
+ *
129
+ * When a `context.call` response comes back, the route runs up to its first step with this
130
+ * set to the call-result envelope (and `workflowRunId` set to a random id) before the SDK
131
+ * recognizes the request. Code before the first step must not dereference, validate or
132
+ * return early on the payload; read it inside `context.run`.
133
+ *
134
+ * @see node_modules/@upstash/workflow/docs/basics/serve/advanced.mdx
135
+ */
136
+ public readonly requestPayload: TInitialPayload;
137
+ /**
138
+ * headers of the initial request
139
+ */
140
+ public readonly headers: Headers;
141
+ /**
142
+ * Map of environment variables and their values.
143
+ *
144
+ * Can be set using the `env` option of serve:
145
+ *
146
+ * ```ts
147
+ * export const { POST } = serve<MyPayload>(
148
+ * async (context) => {
149
+ * const key = context.env["API_KEY"];
150
+ * },
151
+ * {
152
+ * env: {
153
+ * "API_KEY": "*****";
154
+ * }
155
+ * }
156
+ * )
157
+ * ```
158
+ *
159
+ * Default value is set to `process.env`.
160
+ */
161
+ public readonly env: Record<string, string | undefined>;
162
+
163
+ /**
164
+ * Labels attached to the workflow run.
165
+ *
166
+ * Can be used to filter the workflow run logs. A run can have multiple
167
+ * labels when triggered with `label: string[]`.
168
+ *
169
+ * Can be set by passing a `label` parameter when triggering the workflow
170
+ * with `client.trigger`:
171
+ *
172
+ * ```ts
173
+ * await client.trigger({
174
+ * url: "https://workflow-endpoint.com",
175
+ * label: ["label-1", "label-2"]
176
+ * });
177
+ * ```
178
+ */
179
+ public readonly labels: string[];
180
+
181
+ /**
182
+ * Label of the workflow run.
183
+ *
184
+ * @deprecated Use `labels` instead. When a run has multiple labels, this
185
+ * only returns the first one.
186
+ */
187
+ public get label(): string | undefined {
188
+ return this.labels[0];
189
+ }
190
+
191
+ /**
192
+ * Number of times QStash has retried delivering the current request.
193
+ *
194
+ * Sourced from the `Upstash-Retried` header. `0` on the first delivery,
195
+ * `1` on the first retry, `2` on the second, and so on.
196
+ */
197
+ public readonly retried: number;
198
+
199
+ /**
200
+ * Configuration QStash applied to the request being handled.
201
+ *
202
+ * This is the configuration of *this delivery*, not of the run: it is
203
+ * the configuration the run was triggered with, except inside the
204
+ * delivery which executes a step that has step-level settings, where
205
+ * it is that step's settings. The fields below expose it; the executor
206
+ * gets it directly rather than reaching through the context.
207
+ */
208
+ private readonly effectiveConfig: EffectiveConfig;
209
+
210
+ /**
211
+ * Flow control QStash applied to the request being handled, if any.
212
+ *
213
+ * This is the flow control of the request in hand, which is the one the
214
+ * run was triggered with except inside a step carrying its own.
215
+ */
216
+ public get flowControl(): NormalizedFlowControl | undefined {
217
+ return this.effectiveConfig.flowControl;
218
+ }
219
+
220
+ /**
221
+ * Retry limit QStash applied to the request being handled, if it
222
+ * reported one.
223
+ *
224
+ * Not to be confused with {@link retried}, which is how many retries
225
+ * have already happened.
226
+ *
227
+ * @see {@link flowControl} for what "the request being handled" means
228
+ */
229
+ public get retries(): number | undefined {
230
+ return this.effectiveConfig.retries;
231
+ }
232
+
233
+ /**
234
+ * Retry delay expression QStash applied to the request being handled,
235
+ * if any.
236
+ *
237
+ * @see {@link flowControl} for what "the request being handled" means
238
+ */
239
+ public get retryDelay(): string | undefined {
240
+ return this.effectiveConfig.retryDelay;
241
+ }
242
+
243
+ constructor({
244
+ qstashClient,
245
+ workflowRunId,
246
+ workflowRunCreatedAt,
247
+ headers,
248
+ steps,
249
+ url,
250
+ initialPayload,
251
+ env,
252
+ telemetry,
253
+ invokeCount,
254
+ label,
255
+ retried,
256
+ middlewareManager,
257
+ effectiveConfig,
258
+ }: {
259
+ qstashClient: WorkflowClient;
260
+ workflowRunId: string;
261
+ workflowRunCreatedAt: number;
262
+ headers: Headers;
263
+ steps: Step[];
264
+ url: string;
265
+ initialPayload: TInitialPayload;
266
+ env?: Record<string, string | undefined>;
267
+ telemetry?: Telemetry;
268
+ invokeCount?: number;
269
+ label?: string | string[];
270
+ retried?: number;
271
+ middlewareManager?: MiddlewareManager<TInitialPayload>;
272
+ /**
273
+ * configuration QStash applied to the delivery being handled, read
274
+ * from its headers. Defaults to no flow control and no retries,
275
+ * which is what a context created outside a delivery observes.
276
+ */
277
+ effectiveConfig?: EffectiveConfig;
278
+ }) {
279
+ this.qstashClient = qstashClient;
280
+ this.workflowRunId = workflowRunId;
281
+ this.workflowRunCreatedAt = workflowRunCreatedAt;
282
+ this.steps = steps;
283
+ this.url = url;
284
+ this.headers = headers;
285
+ this.requestPayload = initialPayload;
286
+ this.env = env ?? {};
287
+ // The `Upstash-Label` header carries labels as a comma-separated string,
288
+ // so normalize both that and the array form into a single array.
289
+ this.labels =
290
+ label === undefined ? [] : Array.isArray(label) ? label : label ? label.split(",") : [];
291
+ this.retried = retried ?? 0;
292
+ this.effectiveConfig = effectiveConfig ?? { hasStepConfig: false };
293
+
294
+ const middlewareManagerInstance =
295
+ middlewareManager ?? new MiddlewareManager<TInitialPayload, unknown>([]);
296
+ middlewareManagerInstance.assignContext(this);
297
+
298
+ this.executor = new AutoExecutor(
299
+ this,
300
+ this.steps,
301
+ middlewareManagerInstance.dispatchDebug.bind(middlewareManagerInstance),
302
+ middlewareManagerInstance.dispatchLifecycle.bind(middlewareManagerInstance),
303
+ telemetry,
304
+ invokeCount,
305
+ this.effectiveConfig
306
+ );
307
+ }
308
+
309
+ /**
310
+ * Executes a workflow step
311
+ *
312
+ * ```typescript
313
+ * const result = await context.run("step 1", () => {
314
+ * return "result"
315
+ * })
316
+ * ```
317
+ *
318
+ * Can also be called in parallel and the steps will be executed
319
+ * simulatenously:
320
+ *
321
+ * ```typescript
322
+ * const [result1, result2] = await Promise.all([
323
+ * context.run("step 1", () => {
324
+ * return "result1"
325
+ * }),
326
+ * context.run("step 2", async () => {
327
+ * return await fetchResults()
328
+ * })
329
+ * ])
330
+ * ```
331
+ *
332
+ * Step-level settings can be passed as a third argument, overriding
333
+ * the settings the workflow run was triggered with for this step only:
334
+ *
335
+ * ```typescript
336
+ * const result = await context.run(
337
+ * "step 1",
338
+ * () => {
339
+ * return "result"
340
+ * },
341
+ * {
342
+ * flowControl: { key: "custom-key", parallelism: 3 },
343
+ * retries: 5,
344
+ * }
345
+ * )
346
+ * ```
347
+ *
348
+ * Do not wrap steps in try/catch or `.catch` without rethrowing `WorkflowAbort`: each step
349
+ * throws it to end the request. To stop retrying a failed step, throw
350
+ * `WorkflowNonRetryableError`.
351
+ *
352
+ * @param stepName name of the step
353
+ * @param stepFunction step function to be executed
354
+ * @param stepSettings step-level settings for this step
355
+ * @returns result of the step function
356
+ * @see node_modules/@upstash/workflow/docs/steps/run.mdx
357
+ */
358
+ public async run<TResult>(
359
+ stepName: string,
360
+ stepFunction: StepFunction<TResult>,
361
+ stepSettings?: StepSettings
362
+ ): Promise<TResult> {
363
+ const normalizedSettings = normalizeStepSettings(stepSettings);
364
+ if (stepSettings) {
365
+ validateFlowControl(stepSettings.flowControl);
366
+ }
367
+ const wrappedStepFunction = (() =>
368
+ this.executor.wrapStep(stepName, stepFunction)) as StepFunction<TResult>;
369
+ return await this.addStep<TResult>(
370
+ new LazyFunctionStep(this, stepName, wrappedStepFunction, normalizedSettings)
371
+ );
372
+ }
373
+
374
+ /**
375
+ * Stops the execution for the duration provided.
376
+ *
377
+ * ```typescript
378
+ * await context.sleep('sleep1', 3) // wait for three seconds
379
+ * ```
380
+ *
381
+ * @param stepName
382
+ * @param duration sleep duration in seconds, or a duration string such as "10m"
383
+ * @returns undefined
384
+ * @see node_modules/@upstash/workflow/docs/steps/sleep.mdx
385
+ */
386
+ public async sleep(stepName: string, duration: number | Duration): Promise<void> {
387
+ await this.addStep(new LazySleepStep(this, stepName, duration));
388
+ }
389
+
390
+ /**
391
+ * Stops the execution until the date time provided.
392
+ *
393
+ * ```typescript
394
+ * await context.sleepUntil('sleep1', Date.now() / 1000 + 3) // wait for three seconds
395
+ * ```
396
+ *
397
+ * @param stepName
398
+ * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
399
+ * as a Date object or a string (passed to `new Date(datetimeString)`).
400
+ * A millisecond timestamp such as `Date.now()` is too far in the future, so QStash
401
+ * rejects the step and the run fails. Pass `new Date(ms)` instead.
402
+ * @returns undefined
403
+ * @see node_modules/@upstash/workflow/docs/steps/sleepUntil.mdx
404
+ */
405
+ public async sleepUntil(stepName: string, datetime: Date | string | number): Promise<void> {
406
+ let time: number;
407
+ if (typeof datetime === "number") {
408
+ time = datetime;
409
+ } else {
410
+ datetime = typeof datetime === "string" ? new Date(datetime) : datetime;
411
+ // get unix seconds
412
+ time = Math.round(datetime.getTime() / 1000);
413
+ }
414
+ await this.addStep(new LazySleepUntilStep(this, stepName, time));
415
+ }
416
+
417
+ /**
418
+ * Makes a third party call through QStash in order to make a
419
+ * network call without consuming any runtime.
420
+ *
421
+ * ```ts
422
+ * const { status, body } = await context.call<string>(
423
+ * "post call step",
424
+ * {
425
+ * url: "https://www.some-endpoint.com/api",
426
+ * method: "POST",
427
+ * body: "my-payload"
428
+ * }
429
+ * );
430
+ * ```
431
+ *
432
+ * tries to parse the result of the request as JSON. If it's
433
+ * not a JSON which can be parsed, simply returns the response
434
+ * body as it is. This applies to text/plain too: "42" comes back as the number 42,
435
+ * "3.10" as 3.1 and "null" as null. To keep text exact, use fetch inside `context.run`.
436
+ *
437
+ * The response comes back to this endpoint as a separate request. Before the SDK
438
+ * recognizes it, your route runs up to its first step with `requestPayload` set to the
439
+ * call-result envelope and a random `workflowRunId`. Code before the first step must not
440
+ * dereference, validate or return early on the payload, or look anything up by
441
+ * `workflowRunId`; do that inside `context.run`.
442
+ *
443
+ * Do not wrap steps in try/catch or `.catch` without rethrowing `WorkflowAbort`: each step
444
+ * throws it to end the request. A non-2xx response is returned, not thrown; check `status`.
445
+ *
446
+ * @param stepName
447
+ * @param url url to call
448
+ * @param method call method. "GET" by default.
449
+ * @param body call body
450
+ * @param headers call headers
451
+ * @param retries number of call retries. 0 by default
452
+ * @param retryDelay delay / time gap between retries.
453
+ * @param timeout max duration to wait for the endpoint to respond, as a duration string
454
+ * such as "10s". See `CallSettings.timeout`.
455
+ * @returns call result as {
456
+ * status: number;
457
+ * body: unknown;
458
+ * header: Record<string, string[]>
459
+ * }
460
+ * @see node_modules/@upstash/workflow/docs/steps/call.mdx
461
+ */
462
+ public async call<TResult = unknown>(
463
+ stepName: string,
464
+ settings: CallSettings
465
+ ): Promise<CallResponse<TResult>>;
466
+ public async call<
467
+ TResult extends { workflowRunId: string } = { workflowRunId: string },
468
+ TBody = unknown,
469
+ >(
470
+ stepName: string,
471
+ settings: LazyInvokeStepParams<TBody, unknown> & Pick<CallSettings, "timeout">
472
+ ): Promise<CallResponse<TResult>>;
473
+ public async call<TResult = unknown, TBody = unknown>(
474
+ stepName: string,
475
+ settings: CallSettings | (LazyInvokeStepParams<TBody, unknown> & Pick<CallSettings, "timeout">)
476
+ ): Promise<CallResponse<TResult | { workflowRunId: string }>> {
477
+ validateFlowControl(settings.flowControl);
478
+ let callStep: LazyCallStep<TResult | { workflowRunId: string }>;
479
+ if ("workflow" in settings) {
480
+ validateLabel(settings.label);
481
+ const url = getNewUrlFromWorkflowId(this.url, settings.workflow.workflowId);
482
+ const stringBody =
483
+ typeof settings.body === "string"
484
+ ? settings.body
485
+ : settings.body === undefined // leave body as undefined if it's undefined
486
+ ? undefined
487
+ : JSON.stringify(settings.body);
488
+
489
+ callStep = new LazyCallStep<{ workflowRunId: string }>({
490
+ context: this,
491
+ stepName,
492
+ url,
493
+ method: "POST",
494
+ body: stringBody,
495
+ headers: settings.headers || {},
496
+ retries: settings.retries || 0,
497
+ retryDelay: settings.retryDelay,
498
+ timeout: settings.timeout,
499
+ flowControl: settings.flowControl,
500
+ });
501
+ } else {
502
+ callStep = new LazyCallStep<TResult>({
503
+ context: this,
504
+ stepName,
505
+ url: settings.url,
506
+ method: settings.method ?? "GET",
507
+ body: settings.body,
508
+ headers: settings.headers ?? {},
509
+ retries: settings.retries ?? 0,
510
+ retryDelay: settings.retryDelay,
511
+ timeout: settings.timeout,
512
+ flowControl: settings.flowControl,
513
+ });
514
+ }
515
+
516
+ return await this.addStep(callStep);
517
+ }
518
+
519
+ /**
520
+ * Pauses workflow execution until a specific event occurs or a timeout is reached.
521
+ *
522
+ *```ts
523
+ * const result = await context.waitForEvent("payment-confirmed", "payment.confirmed", {
524
+ * timeout: "5m"
525
+ * });
526
+ *```
527
+ *
528
+ * To notify a waiting workflow:
529
+ *
530
+ * ```ts
531
+ * import { Client } from "@upstash/workflow";
532
+ *
533
+ * const client = new Client({ token: "<QSTASH_TOKEN>" });
534
+ *
535
+ * await client.notify({
536
+ * eventId: "payment.confirmed",
537
+ * data: {
538
+ * amount: 99.99,
539
+ * currency: "USD"
540
+ * }
541
+ * })
542
+ * ```
543
+ *
544
+ * Alternatively, you can use the `context.notify` method.
545
+ *
546
+ * @param stepName
547
+ * @param eventId - Unique identifier for the event to wait for. Only letters, digits,
548
+ * "-", "_" and "." are allowed. QStash rejects other characters, such as ":", which
549
+ * stops the run with only a "Tried to append to a cancelled workflow" warning.
550
+ * @param options - Configuration options.
551
+ * @returns `{ timeout: boolean, eventData: TEventData }`.
552
+ * The `timeout` property specifies if the workflow has timed out. The `eventData`
553
+ * is the data passed when notifying this workflow of an event.
554
+ * @see node_modules/@upstash/workflow/docs/steps/waitForEvent.mdx
555
+ */
556
+ public async waitForEvent<TEventData = unknown>(
557
+ stepName: string,
558
+ eventId: string,
559
+ options: WaitEventOptions = {}
560
+ ): Promise<WaitStepResponse<TEventData>> {
561
+ const { timeout = "7d" } = options;
562
+
563
+ const timeoutStr = typeof timeout === "string" ? timeout : `${timeout}s`;
564
+
565
+ return await this.addStep(
566
+ new LazyWaitForEventStep<TEventData>(this, stepName, eventId, timeoutStr)
567
+ );
568
+ }
569
+
570
+ /**
571
+ * Notify workflow runs waiting for an event
572
+ *
573
+ * ```ts
574
+ * const { eventId, eventData, notifyResponse } = await context.notify(
575
+ * "notify step", "event-id", "event-data"
576
+ * );
577
+ * ```
578
+ *
579
+ * Upon `context.notify`, the workflow runs waiting for the given eventId (context.waitForEvent)
580
+ * will receive the given event data and resume execution.
581
+ *
582
+ * The response includes the same eventId and eventData. Additionally, there is
583
+ * a notifyResponse field which contains a list of `NotifyResponse` objects, each corresponding
584
+ * to a notified workflow run. The notified `Waiter` is under `notifyResponse[i].waiter`.
585
+ *
586
+ * @param stepName
587
+ * @param eventId event id to notify. Only letters, digits, "-", "_" and "." are allowed.
588
+ * QStash rejects other characters, such as ":", which stops the run with only a
589
+ * "Tried to append to a cancelled workflow" warning.
590
+ * @param eventData event data to notify with
591
+ * @param workflowRunId optional workflow run id for lookback: the event is kept for the run
592
+ * even if it has not reached `waitForEvent` yet
593
+ * @returns notify response which has event id, event data and list of waiters which were
594
+ * notified. With `workflowRunId`, QStash returns `notifyResponse` as a single object instead
595
+ * of an array, despite the type.
596
+ * @see node_modules/@upstash/workflow/docs/steps/notify.mdx
597
+ */
598
+ public async notify(
599
+ stepName: string,
600
+ eventId: string,
601
+ eventData: unknown,
602
+ workflowRunId?: string
603
+ ): Promise<NotifyStepResponse> {
604
+ return await this.addStep(
605
+ new LazyNotifyStep(this, stepName, eventId, eventData, this.qstashClient.http, workflowRunId)
606
+ );
607
+ }
608
+
609
+ /**
610
+ * Starts another workflow run and waits for its result.
611
+ *
612
+ * @see node_modules/@upstash/workflow/docs/steps/invoke.mdx
613
+ */
614
+ public async invoke<TInitialPayload, TResult>(
615
+ stepName: string,
616
+ settings: LazyInvokeStepParams<TInitialPayload, TResult>
617
+ ) {
618
+ validateLabel(settings.label);
619
+ validateFlowControl(settings.flowControl);
620
+ return await this.addStep(
621
+ new LazyInvokeStep<TResult, TInitialPayload>(this, stepName, settings)
622
+ );
623
+ }
624
+
625
+ /**
626
+ * @see node_modules/@upstash/workflow/docs/steps/createWebhook.mdx
627
+ */
628
+ public async createWebhook(stepName: string): Promise<Webhook> {
629
+ return await this.addStep(new LazyCreateWebhookStep(this, stepName));
630
+ }
631
+
632
+ /**
633
+ * @see node_modules/@upstash/workflow/docs/steps/waitForWebhook.mdx
634
+ */
635
+ public async waitForWebhook(
636
+ stepName: string,
637
+ webhook: Webhook,
638
+ timeout: Duration
639
+ ): Promise<WaitForWebhookResponse> {
640
+ return await this.addStep(new LazyWaitForWebhookStep(this, stepName, webhook, timeout));
641
+ }
642
+
643
+ /**
644
+ * Cancel the current workflow run
645
+ *
646
+ * Will throw WorkflowCancelAbort to stop workflow execution.
647
+ * Shouldn't be inside try/catch.
648
+ *
649
+ * @see node_modules/@upstash/workflow/docs/steps/cancel.mdx
650
+ */
651
+ public async cancel() {
652
+ // throw an abort which will make the workflow cancel
653
+ throw new WorkflowCancelAbort();
654
+ }
655
+
656
+ /**
657
+ * Adds steps to the executor. Needed so that it can be overwritten in
658
+ * DisabledWorkflowContext.
659
+ */
660
+ protected async addStep<TResult = unknown>(step: BaseLazyStep<TResult>) {
661
+ try {
662
+ return await this.executor.addStep(step);
663
+ } catch (error) {
664
+ if (isInstanceOf(error, QstashError) && error.status === 412) {
665
+ throw new WorkflowNonRetryableError(error.message);
666
+ }
667
+ throw error;
668
+ }
669
+ }
670
+
671
+ /**
672
+ * Calls OpenAI, Anthropic or Resend through QStash, like `context.call`.
673
+ *
674
+ * @see node_modules/@upstash/workflow/docs/steps/api.mdx
675
+ */
676
+ public get api() {
677
+ return new WorkflowApi({
678
+ context: this,
679
+ });
680
+ }
681
+ }
@@ -0,0 +1 @@
1
+ export * from "./context";