@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
@@ -118,6 +118,14 @@ var WORKFLOW_CREATED_AT_HEADER = "Upstash-Workflow-CreatedAt";
118
118
  var WORKFLOW_FAILURE_HEADER = "Upstash-Workflow-Is-Failure";
119
119
  var WORKFLOW_FAILURE_CALLBACK_HEADER = "Upstash-Workflow-Failure-Callback";
120
120
  var WORKFLOW_FEATURE_HEADER = "Upstash-Feature-Set";
121
+ var WORKFLOW_FEATURE_SET = "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig";
122
+ var WORKFLOW_STEP_CONFIG_CALL_TYPE = "stepConfig";
123
+ var WORKFLOW_STEP_CONFIG_HEADER = "Upstash-Workflow-Step-Config";
124
+ var FLOW_CONTROL_KEY_HEADER = "Upstash-Flow-Control-Key";
125
+ var FLOW_CONTROL_VALUE_HEADER = "Upstash-Flow-Control-Value";
126
+ var RETRIES_HEADER = "Upstash-Retries";
127
+ var RETRY_DELAY_HEADER = "Upstash-Retry-Delay";
128
+ var WORKFLOW_STEP_CONFIG_FEATURE = "WF_StepConfig";
121
129
  var WORKFLOW_INVOKE_COUNT_HEADER = "Upstash-Workflow-Invoke-Count";
122
130
  var WORKFLOW_RETRIED_HEADER = "Upstash-Retried";
123
131
  var WORKFLOW_LABEL_HEADER = "Upstash-Label";
@@ -224,248 +232,6 @@ var getNewUrlFromWorkflowId = (url, workflowId) => {
224
232
  return url.replace(/[^/]+$/, workflowId);
225
233
  };
226
234
 
227
- // src/context/auto-executor.ts
228
- import { QstashError as QstashError5 } from "@upstash/qstash";
229
-
230
- // src/qstash/headers.ts
231
- import { QstashError as QstashError4 } from "@upstash/qstash";
232
-
233
- // src/client/utils.ts
234
- import { QstashError as QstashError2 } from "@upstash/qstash";
235
- var assertNonEmptyId = (id, label = "id") => {
236
- if (!id) {
237
- throw new QstashError2(`${label} cannot be empty`);
238
- }
239
- };
240
- var toNonEmptyIdArray = (request, label = "id") => {
241
- const ids = typeof request === "string" ? [request] : request;
242
- for (const id of ids) assertNonEmptyId(id, label);
243
- return ids;
244
- };
245
- var makeNotifyRequest = async (requester, eventId, eventData, workflowRunId) => {
246
- assertNonEmptyId(eventId, "Event id");
247
- if (workflowRunId !== void 0) assertNonEmptyId(workflowRunId, "Workflow run id");
248
- const path = workflowRunId === void 0 ? ["v2", "notify", eventId] : ["v2", "notify", workflowRunId, eventId];
249
- const result = await requester.request({
250
- path,
251
- method: "POST",
252
- body: typeof eventData === "string" ? eventData : JSON.stringify(eventData)
253
- });
254
- return result;
255
- };
256
- var makeGetWaitersRequest = async (requester, eventId) => {
257
- assertNonEmptyId(eventId, "Event id");
258
- const result = await requester.request({
259
- path: ["v2", "waiters", eventId],
260
- method: "GET"
261
- });
262
- return result;
263
- };
264
- var makeCancelRequest = async (requester, workflowRunId) => {
265
- await requester.request({
266
- path: ["v2", "workflows", "runs", `${workflowRunId}?cancel=true`],
267
- method: "DELETE",
268
- parseResponseAsJson: false
269
- });
270
- return true;
271
- };
272
- var getSteps = async (requester, workflowRunId, messageId, dispatchDebug) => {
273
- try {
274
- const steps = await requester.request({
275
- path: ["v2", "workflows", "runs", workflowRunId],
276
- parseResponseAsJson: true
277
- });
278
- if (steps.length === 1) {
279
- return {
280
- steps,
281
- workflowRunEnded: false
282
- };
283
- }
284
- if (!messageId) {
285
- await dispatchDebug?.("onInfo", {
286
- info: `Pulled ${steps.length} steps from QStashand returned them without filtering with messageId.`
287
- });
288
- return { steps, workflowRunEnded: false };
289
- } else {
290
- const index = steps.findIndex((item) => item.messageId === messageId);
291
- if (index === -1) {
292
- return { steps: [], workflowRunEnded: false };
293
- }
294
- const filteredSteps = steps.slice(0, index + 1);
295
- await dispatchDebug?.("onInfo", {
296
- info: `Pulled ${steps.length} steps from QStash and filtered them to ${filteredSteps.length} using messageId.`
297
- });
298
- return { steps: filteredSteps, workflowRunEnded: false };
299
- }
300
- } catch (error) {
301
- if (isInstanceOf(error, QstashError2) && error.status === 404) {
302
- await dispatchDebug?.("onWarning", {
303
- warning: "Couldn't fetch workflow run steps. This can happen if the workflow run succesfully ends before some callback is executed."
304
- });
305
- return { steps: void 0, workflowRunEnded: true };
306
- } else {
307
- throw error;
308
- }
309
- }
310
- };
311
- function normalizeCursor(response) {
312
- const cursor = response.cursor;
313
- return { ...response, cursor: cursor || void 0 };
314
- }
315
- var DEFAULT_BULK_COUNT = 100;
316
- function buildBulkActionQueryParameters(request, options) {
317
- const cursor = "cursor" in request ? request.cursor : void 0;
318
- if ("all" in request) {
319
- return { count: request.count ?? DEFAULT_BULK_COUNT, cursor };
320
- }
321
- if ("dlqIds" in request) {
322
- const ids = request.dlqIds;
323
- if (Array.isArray(ids) && ids.length === 0) {
324
- throw new QstashError2(
325
- "Empty dlqIds array provided. If you intend to target all DLQ messages, use { all: true } explicitly."
326
- );
327
- }
328
- return { dlqIds: ids, cursor };
329
- }
330
- if ("workflowRunIds" in request && request.workflowRunIds) {
331
- if (request.workflowRunIds.length === 0) {
332
- throw new QstashError2(
333
- "Empty workflowRunIds array provided. If you intend to target all workflow runs, use { all: true } explicitly."
334
- );
335
- }
336
- return { workflowRunIds: request.workflowRunIds };
337
- }
338
- const filter = request.filter;
339
- if (!filter) {
340
- throw new QstashError2(
341
- "No filter provided. Use { filter: { ... } } with at least one filter field, or { all: true }."
342
- );
343
- }
344
- for (const [field, value] of Object.entries(filter)) {
345
- if (Array.isArray(value) && value.length === 0) {
346
- throw new QstashError2(
347
- `Empty array provided for filter field '${field}'. If you intend to target all records, use { all: true } explicitly.`
348
- );
349
- }
350
- }
351
- if (options?.translateWorkflowUrl) {
352
- const { workflowUrlStartingWith, workflowUrl, ...rest } = filter;
353
- if (workflowUrlStartingWith && workflowUrl) {
354
- throw new QstashError2(
355
- "workflowUrl and workflowUrlStartingWith are mutually exclusive. Use workflowUrl for exact match or workflowUrlStartingWith for prefix match."
356
- );
357
- }
358
- const urlParams = {};
359
- if (workflowUrlStartingWith) {
360
- urlParams.workflowUrl = workflowUrlStartingWith;
361
- } else if (workflowUrl) {
362
- urlParams.workflowUrl = workflowUrl;
363
- urlParams.workflowUrlExactMatch = true;
364
- }
365
- return {
366
- ...rest,
367
- ...urlParams,
368
- count: request.count ?? DEFAULT_BULK_COUNT,
369
- cursor
370
- };
371
- }
372
- return {
373
- ...filter,
374
- count: request.count ?? DEFAULT_BULK_COUNT,
375
- cursor
376
- };
377
- }
378
-
379
- // src/utils.ts
380
- var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
381
- var NANOID_LENGTH = 21;
382
- var RESOURCE_NAME_PATTERN = /^[a-zA-Z0-9\-_.]+$/;
383
- function validateLabel(label) {
384
- if (label === void 0) return;
385
- const labels = Array.isArray(label) ? label : [label];
386
- if (labels.length === 0) {
387
- throw new WorkflowNonRetryableError("Invalid label: label array must not be empty.");
388
- }
389
- for (const value of labels) {
390
- if (!RESOURCE_NAME_PATTERN.test(value)) {
391
- throw new WorkflowNonRetryableError(
392
- `Invalid label "${value}": must be alphanumeric, hyphen, underscore, or period.`
393
- );
394
- }
395
- }
396
- }
397
- function serializeLabel(label) {
398
- return Array.isArray(label) ? label.join(",") : label;
399
- }
400
- function validateFlowControl(flowControl) {
401
- if (flowControl?.key !== void 0 && !RESOURCE_NAME_PATTERN.test(flowControl.key)) {
402
- throw new WorkflowNonRetryableError(
403
- `Invalid flow control key "${flowControl.key}": must be alphanumeric, hyphen, underscore, or period.`
404
- );
405
- }
406
- }
407
- function getRandomInt() {
408
- return Math.floor(Math.random() * NANOID_CHARS.length);
409
- }
410
- function nanoid(length = NANOID_LENGTH) {
411
- return Array.from({ length }).map(() => NANOID_CHARS[getRandomInt()]).join("");
412
- }
413
- function getWorkflowRunId(id) {
414
- return `wfr_${id ?? nanoid()}`;
415
- }
416
- function decodeBase64(base64) {
417
- const binString = atob(base64);
418
- try {
419
- const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
420
- return new TextDecoder().decode(intArray);
421
- } catch (error) {
422
- console.warn(
423
- `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. ${error}`
424
- );
425
- return binString;
426
- }
427
- }
428
- function getUserIdFromToken(qstashClient) {
429
- try {
430
- const token = qstashClient.token;
431
- const decodedToken = decodeBase64(token);
432
- const tokenPayload = JSON.parse(decodedToken);
433
- const userId = tokenPayload.UserID;
434
- if (!userId) {
435
- throw new WorkflowError("QStash token payload does not contain userId");
436
- }
437
- return userId;
438
- } catch (error) {
439
- throw new WorkflowError(
440
- `Failed to decode QStash token while running create webhook step: ${error.message}`
441
- );
442
- }
443
- }
444
- function getQStashUrl(qstashClient) {
445
- try {
446
- const requester = qstashClient.http;
447
- const baseUrl = requester.baseUrl;
448
- if (!baseUrl) {
449
- throw new WorkflowError("QStash client does not have a baseUrl");
450
- }
451
- return baseUrl;
452
- } catch (error) {
453
- throw new WorkflowError(`Failed to get QStash URL from client: ${error.message}`);
454
- }
455
- }
456
- function getEventId() {
457
- return `evt_${nanoid(15)}`;
458
- }
459
- function stringifyBody(body) {
460
- if (body === void 0) {
461
- return void 0;
462
- }
463
- if (typeof body === "string") {
464
- return body;
465
- }
466
- return JSON.stringify(body);
467
- }
468
-
469
235
  // node_modules/neverthrow/dist/index.es.js
470
236
  var defaultErrorConfig = {
471
237
  withStackTrace: false
@@ -865,21 +631,263 @@ var Err = class {
865
631
  match(_ok, err2) {
866
632
  return err2(this.error);
867
633
  }
868
- safeUnwrap() {
869
- const error = this.error;
870
- return (function* () {
871
- yield err(error);
872
- throw new Error("Do not use this generator out of `safeTry`");
873
- })();
634
+ safeUnwrap() {
635
+ const error = this.error;
636
+ return (function* () {
637
+ yield err(error);
638
+ throw new Error("Do not use this generator out of `safeTry`");
639
+ })();
640
+ }
641
+ _unsafeUnwrap(config) {
642
+ throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
643
+ }
644
+ _unsafeUnwrapErr(_) {
645
+ return this.error;
646
+ }
647
+ };
648
+ var fromThrowable = Result.fromThrowable;
649
+
650
+ // src/context/auto-executor.ts
651
+ import { QstashError as QstashError5 } from "@upstash/qstash";
652
+
653
+ // src/qstash/headers.ts
654
+ import { QstashError as QstashError4 } from "@upstash/qstash";
655
+
656
+ // src/client/utils.ts
657
+ import { QstashError as QstashError2 } from "@upstash/qstash";
658
+ var assertNonEmptyId = (id, label = "id") => {
659
+ if (!id) {
660
+ throw new QstashError2(`${label} cannot be empty`);
661
+ }
662
+ };
663
+ var toNonEmptyIdArray = (request, label = "id") => {
664
+ const ids = typeof request === "string" ? [request] : request;
665
+ for (const id of ids) assertNonEmptyId(id, label);
666
+ return ids;
667
+ };
668
+ var makeNotifyRequest = async (requester, eventId, eventData, workflowRunId) => {
669
+ assertNonEmptyId(eventId, "Event id");
670
+ if (workflowRunId !== void 0) assertNonEmptyId(workflowRunId, "Workflow run id");
671
+ const path = workflowRunId === void 0 ? ["v2", "notify", eventId] : ["v2", "notify", workflowRunId, eventId];
672
+ const result = await requester.request({
673
+ path,
674
+ method: "POST",
675
+ body: typeof eventData === "string" ? eventData : JSON.stringify(eventData)
676
+ });
677
+ return result;
678
+ };
679
+ var makeGetWaitersRequest = async (requester, eventId) => {
680
+ assertNonEmptyId(eventId, "Event id");
681
+ const result = await requester.request({
682
+ path: ["v2", "waiters", eventId],
683
+ method: "GET"
684
+ });
685
+ return result;
686
+ };
687
+ var makeCancelRequest = async (requester, workflowRunId) => {
688
+ await requester.request({
689
+ path: ["v2", "workflows", "runs", `${workflowRunId}?cancel=true`],
690
+ method: "DELETE",
691
+ parseResponseAsJson: false
692
+ });
693
+ return true;
694
+ };
695
+ var getSteps = async (requester, workflowRunId, messageId, dispatchDebug) => {
696
+ try {
697
+ const steps = await requester.request({
698
+ path: ["v2", "workflows", "runs", workflowRunId],
699
+ parseResponseAsJson: true
700
+ });
701
+ if (steps.length === 1) {
702
+ return {
703
+ steps,
704
+ workflowRunEnded: false
705
+ };
706
+ }
707
+ if (!messageId) {
708
+ await dispatchDebug?.("onInfo", {
709
+ info: `Pulled ${steps.length} steps from QStashand returned them without filtering with messageId.`
710
+ });
711
+ return { steps, workflowRunEnded: false };
712
+ } else {
713
+ const index = steps.findIndex((item) => item.messageId === messageId);
714
+ if (index === -1) {
715
+ return { steps: [], workflowRunEnded: false };
716
+ }
717
+ const filteredSteps = steps.slice(0, index + 1);
718
+ await dispatchDebug?.("onInfo", {
719
+ info: `Pulled ${steps.length} steps from QStash and filtered them to ${filteredSteps.length} using messageId.`
720
+ });
721
+ return { steps: filteredSteps, workflowRunEnded: false };
722
+ }
723
+ } catch (error) {
724
+ if (isInstanceOf(error, QstashError2) && error.status === 404) {
725
+ await dispatchDebug?.("onWarning", {
726
+ warning: "Couldn't fetch workflow run steps. This can happen if the workflow run succesfully ends before some callback is executed."
727
+ });
728
+ return { steps: void 0, workflowRunEnded: true };
729
+ } else {
730
+ throw error;
731
+ }
732
+ }
733
+ };
734
+ function normalizeCursor(response) {
735
+ const cursor = response.cursor;
736
+ return { ...response, cursor: cursor || void 0 };
737
+ }
738
+ var DEFAULT_BULK_COUNT = 100;
739
+ function buildBulkActionQueryParameters(request, options) {
740
+ const cursor = "cursor" in request ? request.cursor : void 0;
741
+ if ("all" in request) {
742
+ return { count: request.count ?? DEFAULT_BULK_COUNT, cursor };
743
+ }
744
+ if ("dlqIds" in request) {
745
+ const ids = request.dlqIds;
746
+ if (Array.isArray(ids) && ids.length === 0) {
747
+ throw new QstashError2(
748
+ "Empty dlqIds array provided. If you intend to target all DLQ messages, use { all: true } explicitly."
749
+ );
750
+ }
751
+ return { dlqIds: ids, cursor };
752
+ }
753
+ if ("workflowRunIds" in request && request.workflowRunIds) {
754
+ if (request.workflowRunIds.length === 0) {
755
+ throw new QstashError2(
756
+ "Empty workflowRunIds array provided. If you intend to target all workflow runs, use { all: true } explicitly."
757
+ );
758
+ }
759
+ return { workflowRunIds: request.workflowRunIds };
760
+ }
761
+ const filter = request.filter;
762
+ if (!filter) {
763
+ throw new QstashError2(
764
+ "No filter provided. Use { filter: { ... } } with at least one filter field, or { all: true }."
765
+ );
766
+ }
767
+ for (const [field, value] of Object.entries(filter)) {
768
+ if (Array.isArray(value) && value.length === 0) {
769
+ throw new QstashError2(
770
+ `Empty array provided for filter field '${field}'. If you intend to target all records, use { all: true } explicitly.`
771
+ );
772
+ }
773
+ }
774
+ if (options?.translateWorkflowUrl) {
775
+ const { workflowUrlStartingWith, workflowUrl, ...rest } = filter;
776
+ if (workflowUrlStartingWith && workflowUrl) {
777
+ throw new QstashError2(
778
+ "workflowUrl and workflowUrlStartingWith are mutually exclusive. Use workflowUrl for exact match or workflowUrlStartingWith for prefix match."
779
+ );
780
+ }
781
+ const urlParams = {};
782
+ if (workflowUrlStartingWith) {
783
+ urlParams.workflowUrl = workflowUrlStartingWith;
784
+ } else if (workflowUrl) {
785
+ urlParams.workflowUrl = workflowUrl;
786
+ urlParams.workflowUrlExactMatch = true;
787
+ }
788
+ return {
789
+ ...rest,
790
+ ...urlParams,
791
+ count: request.count ?? DEFAULT_BULK_COUNT,
792
+ cursor
793
+ };
794
+ }
795
+ return {
796
+ ...filter,
797
+ count: request.count ?? DEFAULT_BULK_COUNT,
798
+ cursor
799
+ };
800
+ }
801
+
802
+ // src/utils.ts
803
+ var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
804
+ var NANOID_LENGTH = 21;
805
+ var RESOURCE_NAME_PATTERN = /^[a-zA-Z0-9\-_.]+$/;
806
+ function validateLabel(label) {
807
+ if (label === void 0) return;
808
+ const labels = Array.isArray(label) ? label : [label];
809
+ if (labels.length === 0) {
810
+ throw new WorkflowNonRetryableError("Invalid label: label array must not be empty.");
811
+ }
812
+ for (const value of labels) {
813
+ if (!RESOURCE_NAME_PATTERN.test(value)) {
814
+ throw new WorkflowNonRetryableError(
815
+ `Invalid label "${value}": must be alphanumeric, hyphen, underscore, or period.`
816
+ );
817
+ }
818
+ }
819
+ }
820
+ function serializeLabel(label) {
821
+ return Array.isArray(label) ? label.join(",") : label;
822
+ }
823
+ function validateFlowControl(flowControl) {
824
+ if (flowControl?.key !== void 0 && !RESOURCE_NAME_PATTERN.test(flowControl.key)) {
825
+ throw new WorkflowNonRetryableError(
826
+ `Invalid flow control key "${flowControl.key}": must be alphanumeric, hyphen, underscore, or period.`
827
+ );
828
+ }
829
+ }
830
+ function getRandomInt() {
831
+ return Math.floor(Math.random() * NANOID_CHARS.length);
832
+ }
833
+ function nanoid(length = NANOID_LENGTH) {
834
+ return Array.from({ length }).map(() => NANOID_CHARS[getRandomInt()]).join("");
835
+ }
836
+ function getWorkflowRunId(id) {
837
+ return `wfr_${id ?? nanoid()}`;
838
+ }
839
+ function decodeBase64(base64) {
840
+ const binString = atob(base64);
841
+ try {
842
+ const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
843
+ return new TextDecoder().decode(intArray);
844
+ } catch (error) {
845
+ console.warn(
846
+ `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. ${error}`
847
+ );
848
+ return binString;
849
+ }
850
+ }
851
+ function getUserIdFromToken(qstashClient) {
852
+ try {
853
+ const token = qstashClient.token;
854
+ const decodedToken = decodeBase64(token);
855
+ const tokenPayload = JSON.parse(decodedToken);
856
+ const userId = tokenPayload.UserID;
857
+ if (!userId) {
858
+ throw new WorkflowError("QStash token payload does not contain userId");
859
+ }
860
+ return userId;
861
+ } catch (error) {
862
+ throw new WorkflowError(
863
+ `Failed to decode QStash token while running create webhook step: ${error.message}`
864
+ );
865
+ }
866
+ }
867
+ function getQStashUrl(qstashClient) {
868
+ try {
869
+ const requester = qstashClient.http;
870
+ const baseUrl = requester.baseUrl;
871
+ if (!baseUrl) {
872
+ throw new WorkflowError("QStash client does not have a baseUrl");
873
+ }
874
+ return baseUrl;
875
+ } catch (error) {
876
+ throw new WorkflowError(`Failed to get QStash URL from client: ${error.message}`);
874
877
  }
875
- _unsafeUnwrap(config) {
876
- throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
878
+ }
879
+ function getEventId() {
880
+ return `evt_${nanoid(15)}`;
881
+ }
882
+ function stringifyBody(body) {
883
+ if (body === void 0) {
884
+ return void 0;
877
885
  }
878
- _unsafeUnwrapErr(_) {
879
- return this.error;
886
+ if (typeof body === "string") {
887
+ return body;
880
888
  }
881
- };
882
- var fromThrowable = Result.fromThrowable;
889
+ return JSON.stringify(body);
890
+ }
883
891
 
884
892
  // src/workflow-requests.ts
885
893
  import { QstashError as QstashError3 } from "@upstash/qstash";
@@ -976,6 +984,10 @@ var triggerFirstInvocation = async (params) => {
976
984
  return err(error_);
977
985
  }
978
986
  };
987
+ var flushPendingStep = async (workflowContext) => {
988
+ const { executor } = workflowContext;
989
+ return await executor.submitPendingStep();
990
+ };
979
991
  var triggerRouteFunction = async ({
980
992
  onCleanup,
981
993
  onStep,
@@ -1188,8 +1200,29 @@ If you want to disable QStash Verification, you should clear env variables QSTAS
1188
1200
  var BaseLazyStep = class _BaseLazyStep {
1189
1201
  stepName;
1190
1202
  context;
1191
- constructor(context, stepName) {
1203
+ /**
1204
+ * step-level settings (flow control, retries etc.) which override the
1205
+ * settings the workflow run was triggered with, for this step only.
1206
+ */
1207
+ stepSettings;
1208
+ /**
1209
+ * whether this step's result can be submitted after the route function
1210
+ * has moved on, instead of right away.
1211
+ *
1212
+ * Enabled for steps whose `getResultStep` produces the final `out` —
1213
+ * which is not the same as "needs no server round trip":
1214
+ * `LazyCreateWebhookStep` builds its result in `getBody` and returns
1215
+ * `out: undefined` from `getResultStep`, so deferring it would hand
1216
+ * `undefined` to the route function.
1217
+ *
1218
+ * Deferring lets the route function continue and reveal the next step,
1219
+ * so that step's settings can ride on this step's submission instead
1220
+ * of needing a step config request of their own.
1221
+ */
1222
+ supportsDeferredSubmission = false;
1223
+ constructor(context, stepName, stepSettings) {
1192
1224
  this.context = context;
1225
+ this.stepSettings = stepSettings;
1193
1226
  if (!stepName) {
1194
1227
  throw new WorkflowError(
1195
1228
  "A workflow step name cannot be undefined or an empty string. Please provide a name for your workflow step."
@@ -1253,7 +1286,13 @@ var BaseLazyStep = class _BaseLazyStep {
1253
1286
  step.out = JSON.stringify(step.out);
1254
1287
  return JSON.stringify(step);
1255
1288
  }
1256
- getHeaders({ context, telemetry, invokeCount, step }) {
1289
+ getHeaders({
1290
+ context,
1291
+ telemetry,
1292
+ invokeCount,
1293
+ step,
1294
+ stepSettings
1295
+ }) {
1257
1296
  return getHeaders({
1258
1297
  initHeaderValue: "false",
1259
1298
  workflowConfig: {
@@ -1267,7 +1306,8 @@ var BaseLazyStep = class _BaseLazyStep {
1267
1306
  stepInfo: {
1268
1307
  step,
1269
1308
  lazyStep: this
1270
- }
1309
+ },
1310
+ stepSettings
1271
1311
  });
1272
1312
  }
1273
1313
  async submitStep({ context, body, headers }) {
@@ -1285,8 +1325,9 @@ var LazyFunctionStep = class extends BaseLazyStep {
1285
1325
  stepFunction;
1286
1326
  stepType = "Run";
1287
1327
  allowUndefinedOut = true;
1288
- constructor(context, stepName, stepFunction) {
1289
- super(context, stepName);
1328
+ supportsDeferredSubmission = true;
1329
+ constructor(context, stepName, stepFunction, stepSettings) {
1330
+ super(context, stepName, stepSettings);
1290
1331
  this.stepFunction = stepFunction;
1291
1332
  }
1292
1333
  getPlanStep(concurrent, targetStep) {
@@ -1316,6 +1357,7 @@ var LazySleepStep = class extends BaseLazyStep {
1316
1357
  sleep;
1317
1358
  stepType = "SleepFor";
1318
1359
  allowUndefinedOut = true;
1360
+ supportsDeferredSubmission = true;
1319
1361
  constructor(context, stepName, sleep) {
1320
1362
  super(context, stepName);
1321
1363
  this.sleep = sleep;
@@ -1355,6 +1397,7 @@ var LazySleepUntilStep = class extends BaseLazyStep {
1355
1397
  sleepUntil;
1356
1398
  stepType = "SleepUntil";
1357
1399
  allowUndefinedOut = true;
1400
+ supportsDeferredSubmission = true;
1358
1401
  constructor(context, stepName, sleepUntil) {
1359
1402
  super(context, stepName);
1360
1403
  this.sleepUntil = sleepUntil;
@@ -1856,6 +1899,7 @@ var WorkflowHeaders = class {
1856
1899
  invokeCount;
1857
1900
  initHeaderValue;
1858
1901
  stepInfo;
1902
+ stepSettings;
1859
1903
  headers;
1860
1904
  /**
1861
1905
  * @param params workflow header parameters
@@ -1865,17 +1909,20 @@ var WorkflowHeaders = class {
1865
1909
  workflowConfig,
1866
1910
  invokeCount,
1867
1911
  initHeaderValue,
1868
- stepInfo
1912
+ stepInfo,
1913
+ stepSettings
1869
1914
  }) {
1870
1915
  this.userHeaders = userHeaders;
1871
1916
  this.workflowConfig = workflowConfig;
1872
1917
  this.invokeCount = invokeCount;
1873
1918
  this.initHeaderValue = initHeaderValue;
1874
1919
  this.stepInfo = stepInfo;
1920
+ this.stepSettings = stepSettings;
1875
1921
  this.headers = {
1876
1922
  rawHeaders: {},
1877
1923
  workflowHeaders: {},
1878
- failureHeaders: {}
1924
+ failureHeaders: {},
1925
+ stepSettingsHeaders: {}
1879
1926
  };
1880
1927
  }
1881
1928
  getHeaders() {
@@ -1886,6 +1933,7 @@ var WorkflowHeaders = class {
1886
1933
  this.addUserHeaders();
1887
1934
  this.addInvokeCount();
1888
1935
  this.addFailureUrl();
1936
+ this.addStepSettings();
1889
1937
  const contentType = this.addContentType();
1890
1938
  return this.prefixHeaders(contentType);
1891
1939
  }
@@ -1895,7 +1943,7 @@ var WorkflowHeaders = class {
1895
1943
  [WORKFLOW_INIT_HEADER]: this.initHeaderValue,
1896
1944
  [WORKFLOW_ID_HEADER]: this.workflowConfig.workflowRunId,
1897
1945
  [WORKFLOW_URL_HEADER]: this.workflowConfig.workflowUrl,
1898
- [WORKFLOW_FEATURE_HEADER]: "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig",
1946
+ [WORKFLOW_FEATURE_HEADER]: WORKFLOW_FEATURE_SET,
1899
1947
  [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
1900
1948
  ...this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {}
1901
1949
  };
@@ -1976,7 +2024,7 @@ var WorkflowHeaders = class {
1976
2024
  this.headers.failureHeaders["Workflow-Init"] = "false";
1977
2025
  this.headers.failureHeaders["Workflow-Url"] = this.workflowConfig.workflowUrl;
1978
2026
  this.headers.failureHeaders["Workflow-Calltype"] = "failureCall";
1979
- this.headers.failureHeaders["Feature-Set"] = "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig";
2027
+ this.headers.failureHeaders["Feature-Set"] = WORKFLOW_FEATURE_SET;
1980
2028
  if (this.workflowConfig.retries !== void 0 && this.workflowConfig.retries !== DEFAULT_RETRIES) {
1981
2029
  this.headers.failureHeaders["Retries"] = this.workflowConfig.retries.toString();
1982
2030
  }
@@ -1984,6 +2032,42 @@ var WorkflowHeaders = class {
1984
2032
  this.headers.failureHeaders["Retry-Delay"] = this.workflowConfig.retryDelay.toString();
1985
2033
  }
1986
2034
  }
2035
+ /**
2036
+ * Applies the step-level settings of a step to the message.
2037
+ *
2038
+ * These headers configure the message itself, so that QStash uses them
2039
+ * instead of the settings the run was triggered with. The delivery of
2040
+ * the message is what executes the step, which is how a step's
2041
+ * settings reach it.
2042
+ *
2043
+ * When any setting is present the feature set is extended with
2044
+ * `WF_StepConfig`, which is what tells QStash to keep them. QStash
2045
+ * reports that back on the delivery as `Upstash-Workflow-Step-Config`.
2046
+ */
2047
+ addStepSettings() {
2048
+ if (!this.stepSettings) {
2049
+ return;
2050
+ }
2051
+ const headers = {};
2052
+ if (this.stepSettings.flowControl) {
2053
+ const { flowControlKey, flowControlValue } = prepareFlowControl(
2054
+ this.stepSettings.flowControl
2055
+ );
2056
+ headers[FLOW_CONTROL_KEY_HEADER] = flowControlKey;
2057
+ headers[FLOW_CONTROL_VALUE_HEADER] = flowControlValue;
2058
+ }
2059
+ if (this.stepSettings.retries !== void 0) {
2060
+ headers[RETRIES_HEADER] = this.stepSettings.retries.toString();
2061
+ }
2062
+ if (this.stepSettings.retryDelay) {
2063
+ headers[RETRY_DELAY_HEADER] = this.stepSettings.retryDelay;
2064
+ }
2065
+ if (Object.keys(headers).length === 0) {
2066
+ return;
2067
+ }
2068
+ headers[WORKFLOW_FEATURE_HEADER] = `${WORKFLOW_FEATURE_SET},${WORKFLOW_STEP_CONFIG_FEATURE}`;
2069
+ this.headers.stepSettingsHeaders = headers;
2070
+ }
1987
2071
  addContentType() {
1988
2072
  if (this.workflowConfig.useJSONContent) {
1989
2073
  this.headers.rawHeaders["content-type"] = "application/json";
@@ -1997,14 +2081,17 @@ var WorkflowHeaders = class {
1997
2081
  return contentType;
1998
2082
  }
1999
2083
  prefixHeaders(contentType) {
2000
- const { rawHeaders, workflowHeaders, failureHeaders } = this.headers;
2084
+ const { rawHeaders, workflowHeaders, failureHeaders, stepSettingsHeaders } = this.headers;
2001
2085
  const isCall = this.stepInfo?.lazyStep.stepType === "Call";
2002
2086
  return {
2003
2087
  headers: {
2004
2088
  ...rawHeaders,
2005
2089
  ...addPrefixToHeaders(workflowHeaders, isCall ? "Upstash-Callback-" : "Upstash-"),
2006
2090
  ...addPrefixToHeaders(failureHeaders, "Upstash-Failure-Callback-"),
2007
- ...isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {}
2091
+ ...isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {},
2092
+ // last, so they override the run's settings above. Never
2093
+ // prefixed: they configure this message, not its callback.
2094
+ ...stepSettingsHeaders
2008
2095
  },
2009
2096
  contentType
2010
2097
  };
@@ -2055,7 +2142,7 @@ var submitParallelSteps = async ({
2055
2142
  info: `Submitting ${planSteps.length} parallel steps.`
2056
2143
  });
2057
2144
  const result = await context.qstashClient.batch(
2058
- planSteps.map((planStep) => {
2145
+ planSteps.map((planStep, index) => {
2059
2146
  const { headers } = getHeaders({
2060
2147
  initHeaderValue: "false",
2061
2148
  workflowConfig: {
@@ -2064,7 +2151,8 @@ var submitParallelSteps = async ({
2064
2151
  workflowRunCreatedAt: context.workflowRunCreatedAt,
2065
2152
  telemetry
2066
2153
  },
2067
- invokeCount
2154
+ invokeCount,
2155
+ stepSettings: steps[index].stepSettings
2068
2156
  });
2069
2157
  return {
2070
2158
  headers,
@@ -2083,31 +2171,38 @@ var submitParallelSteps = async ({
2083
2171
  }
2084
2172
  throw new WorkflowAbort(planSteps[0].stepName, planSteps[0]);
2085
2173
  };
2086
- var submitSingleStep = async ({
2087
- context,
2174
+ var executeStep = async ({
2088
2175
  lazyStep,
2089
2176
  stepId,
2090
- invokeCount,
2091
2177
  concurrency,
2092
- telemetry,
2093
- dispatchDebug,
2094
2178
  dispatchLifecycle
2095
2179
  }) => {
2096
2180
  await dispatchLifecycle("beforeExecution", {
2097
2181
  stepName: lazyStep.stepName
2098
2182
  });
2099
- let resultStep;
2100
2183
  try {
2101
- resultStep = await lazyStep.getResultStep(concurrency, stepId);
2184
+ return await lazyStep.getResultStep(concurrency, stepId);
2102
2185
  } catch (error) {
2103
2186
  attachStepNameToError(error, lazyStep.stepName);
2104
2187
  throw error;
2105
2188
  }
2189
+ };
2190
+ var submitStepResult = async ({
2191
+ context,
2192
+ lazyStep,
2193
+ resultStep,
2194
+ invokeCount,
2195
+ concurrency,
2196
+ telemetry,
2197
+ dispatchDebug,
2198
+ nextStepSettings
2199
+ }) => {
2106
2200
  const { headers } = lazyStep.getHeaders({
2107
2201
  context,
2108
2202
  step: resultStep,
2109
2203
  invokeCount,
2110
- telemetry
2204
+ telemetry,
2205
+ stepSettings: nextStepSettings
2111
2206
  });
2112
2207
  const body = lazyStep.getBody({
2113
2208
  context,
@@ -2132,6 +2227,154 @@ var submitSingleStep = async ({
2132
2227
  }
2133
2228
  return resultStep;
2134
2229
  };
2230
+ var publishStepConfigRequest = async ({
2231
+ context,
2232
+ lazyStep,
2233
+ targetStep,
2234
+ invokeCount,
2235
+ telemetry,
2236
+ dispatchDebug
2237
+ }) => {
2238
+ const { headers } = getHeaders({
2239
+ initHeaderValue: "false",
2240
+ workflowConfig: {
2241
+ workflowRunId: context.workflowRunId,
2242
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
2243
+ workflowUrl: context.url,
2244
+ telemetry
2245
+ },
2246
+ invokeCount,
2247
+ stepSettings: lazyStep.stepSettings
2248
+ });
2249
+ await dispatchDebug("onInfo", {
2250
+ info: `Step "${lazyStep.stepName}" (${targetStep}) has step-level settings which the current delivery does not carry. Requesting a delivery which does.`
2251
+ });
2252
+ const result = await context.qstashClient.publishJSON({
2253
+ headers: {
2254
+ ...headers,
2255
+ "Upstash-Workflow-CallType": WORKFLOW_STEP_CONFIG_CALL_TYPE,
2256
+ "Upstash-Forward-Upstash-Workflow-StepId": targetStep.toString(),
2257
+ "Upstash-Forward-Upstash-Workflow-StepName": lazyStep.stepName
2258
+ },
2259
+ method: "POST",
2260
+ body: { targetStep, invokeCount },
2261
+ url: context.url,
2262
+ contentBasedDeduplication: true
2263
+ });
2264
+ if (result?.deduplicated) {
2265
+ await dispatchDebug("onWarning", {
2266
+ warning: `A step config request for step "${lazyStep.stepName}" (${targetStep}) was already published and this one was deduplicated. Expected when the delivery which published it is being retried; otherwise the run stops here.`
2267
+ });
2268
+ } else if (result?.messageId) {
2269
+ await dispatchDebug("onInfo", {
2270
+ info: `Requested a delivery under the settings of step "${lazyStep.stepName}" with messageId: ${result.messageId}.`
2271
+ });
2272
+ }
2273
+ };
2274
+
2275
+ // src/qstash/step-config.ts
2276
+ var normalizeStepSettings = (settings) => {
2277
+ if (settings === void 0) {
2278
+ return void 0;
2279
+ }
2280
+ const { retries, retryDelay } = settings;
2281
+ if (retryDelay !== void 0 && typeof retryDelay !== "string") {
2282
+ throw new WorkflowNonRetryableError("Invalid step retryDelay: must be a string.");
2283
+ }
2284
+ if (retries !== void 0 && (!Number.isInteger(retries) || retries < 0)) {
2285
+ throw new WorkflowNonRetryableError("Invalid step retries: must be a non-negative integer.");
2286
+ }
2287
+ return { ...settings, retryDelay: retryDelay?.trim() || void 0 };
2288
+ };
2289
+ var DEFAULT_PARALLELISM = 0;
2290
+ var DEFAULT_RATE = 0;
2291
+ var DEFAULT_PERIOD_SECONDS = 1;
2292
+ var SECONDS_PER_UNIT = {
2293
+ s: 1,
2294
+ m: 60,
2295
+ h: 60 * 60,
2296
+ d: 24 * 60 * 60
2297
+ };
2298
+ var durationToSeconds = (duration) => {
2299
+ if (typeof duration === "number") {
2300
+ return Number.isFinite(duration) ? duration : void 0;
2301
+ }
2302
+ const match = /^(\d+)([smhd])$/.exec(duration.trim());
2303
+ if (match) {
2304
+ return Number(match[1]) * SECONDS_PER_UNIT[match[2]];
2305
+ }
2306
+ const seconds = Number(duration.trim());
2307
+ return Number.isFinite(seconds) ? seconds : void 0;
2308
+ };
2309
+ var normalizeFlowControl = (flowControl) => {
2310
+ const period = flowControl.period === void 0 ? void 0 : durationToSeconds(flowControl.period);
2311
+ return {
2312
+ key: flowControl.key,
2313
+ parallelism: flowControl.parallelism ?? DEFAULT_PARALLELISM,
2314
+ rate: flowControl.rate ?? flowControl.ratePerSecond ?? DEFAULT_RATE,
2315
+ period: period ?? DEFAULT_PERIOD_SECONDS
2316
+ };
2317
+ };
2318
+ var parseFlowControlHeaders = (key, value) => {
2319
+ if (!key) {
2320
+ return void 0;
2321
+ }
2322
+ const flowControl = {
2323
+ key,
2324
+ parallelism: DEFAULT_PARALLELISM,
2325
+ rate: DEFAULT_RATE,
2326
+ period: DEFAULT_PERIOD_SECONDS
2327
+ };
2328
+ for (const entry of (value ?? "").split(",")) {
2329
+ const [name, rawValue] = entry.split("=").map((part) => part.trim());
2330
+ if (!name || rawValue === void 0) {
2331
+ continue;
2332
+ }
2333
+ switch (name) {
2334
+ case "parallelism": {
2335
+ flowControl.parallelism = Number(rawValue);
2336
+ break;
2337
+ }
2338
+ case "rate": {
2339
+ flowControl.rate = Number(rawValue);
2340
+ break;
2341
+ }
2342
+ case "period": {
2343
+ flowControl.period = durationToSeconds(rawValue) ?? DEFAULT_PERIOD_SECONDS;
2344
+ break;
2345
+ }
2346
+ }
2347
+ }
2348
+ return flowControl;
2349
+ };
2350
+ var getEffectiveConfig = (headers) => {
2351
+ const retriesHeader = headers.get(RETRIES_HEADER);
2352
+ return {
2353
+ flowControl: parseFlowControlHeaders(
2354
+ headers.get(FLOW_CONTROL_KEY_HEADER),
2355
+ headers.get(FLOW_CONTROL_VALUE_HEADER)
2356
+ ),
2357
+ retries: retriesHeader === null ? void 0 : Number(retriesHeader),
2358
+ retryDelay: headers.get(RETRY_DELAY_HEADER) ?? void 0,
2359
+ hasStepConfig: headers.get(WORKFLOW_STEP_CONFIG_HEADER) === "true"
2360
+ };
2361
+ };
2362
+ var describeStepSettingsMismatch = (stepSettings, effectiveConfig) => {
2363
+ if (stepSettings.flowControl) {
2364
+ const wanted = normalizeFlowControl(stepSettings.flowControl);
2365
+ const applied = effectiveConfig.flowControl;
2366
+ if (!applied || applied.key !== wanted.key || applied.parallelism !== wanted.parallelism || applied.rate !== wanted.rate || applied.period !== wanted.period) {
2367
+ return `flow control: expected ${JSON.stringify(wanted)}, delivery has ${JSON.stringify(applied)}`;
2368
+ }
2369
+ }
2370
+ if (stepSettings.retries !== void 0 && effectiveConfig.retries !== void 0 && stepSettings.retries !== effectiveConfig.retries) {
2371
+ return `retries: expected ${stepSettings.retries}, delivery has ${effectiveConfig.retries}`;
2372
+ }
2373
+ if (stepSettings.retryDelay !== void 0 && stepSettings.retryDelay !== effectiveConfig.retryDelay) {
2374
+ return `retry delay: expected '${stepSettings.retryDelay}', delivery has '${effectiveConfig.retryDelay ?? ""}'`;
2375
+ }
2376
+ return void 0;
2377
+ };
2135
2378
 
2136
2379
  // src/context/auto-executor.ts
2137
2380
  var AutoExecutor = class _AutoExecutor {
@@ -2148,6 +2391,25 @@ var AutoExecutor = class _AutoExecutor {
2148
2391
  stepCount = 0;
2149
2392
  planStepCount = 0;
2150
2393
  executingStep = false;
2394
+ /**
2395
+ * an executed step whose result hasn't been submitted to QStash yet.
2396
+ *
2397
+ * Set when a step which can produce its result in-process executes. The
2398
+ * submission waits so that the route function can continue and reveal
2399
+ * what comes next: if that is a single step with step-level settings,
2400
+ * the settings ride on this submission and no step config request is
2401
+ * needed, since the delivery of the submission is what executes it.
2402
+ *
2403
+ * Flushed when the next step is reached (see `addStep`) or when the
2404
+ * route function ends (see `flushPendingStep` in `serve`).
2405
+ */
2406
+ pendingStep;
2407
+ /**
2408
+ * configuration QStash applied to the delivery being handled. A step
2409
+ * with step-level settings is settled by comparing its settings against
2410
+ * this.
2411
+ */
2412
+ effectiveConfig;
2151
2413
  /**
2152
2414
  * @param context workflow context
2153
2415
  * @param steps list of steps
@@ -2155,14 +2417,17 @@ var AutoExecutor = class _AutoExecutor {
2155
2417
  * @param dispatchLifecycle lifecycle event dispatcher
2156
2418
  * @param telemetry optional telemetry information
2157
2419
  * @param invokeCount optional invoke count
2420
+ * @param effectiveConfig configuration QStash applied to the delivery
2421
+ * being handled
2158
2422
  */
2159
- constructor(context, steps, dispatchDebug, dispatchLifecycle, telemetry, invokeCount) {
2423
+ constructor(context, steps, dispatchDebug, dispatchLifecycle, telemetry, invokeCount, effectiveConfig) {
2160
2424
  this.context = context;
2161
2425
  this.steps = steps;
2162
2426
  this.dispatchDebug = dispatchDebug;
2163
2427
  this.dispatchLifecycle = dispatchLifecycle;
2164
2428
  this.telemetry = telemetry;
2165
2429
  this.invokeCount = invokeCount ?? 0;
2430
+ this.effectiveConfig = effectiveConfig ?? { hasStepConfig: false };
2166
2431
  this.nonPlanStepCount = this.steps.filter((step) => !step.targetStep).length;
2167
2432
  }
2168
2433
  /**
@@ -2197,6 +2462,15 @@ var AutoExecutor = class _AutoExecutor {
2197
2462
  lazyStepList.push(stepInfo);
2198
2463
  const index = this.indexInCurrentList++;
2199
2464
  const requestComplete = this.deferExecution().then(async () => {
2465
+ const submitted = await this.submitPendingStep(
2466
+ lazyStepList.length === 1 ? lazyStepList[0].stepSettings : void 0
2467
+ );
2468
+ if (submitted.isErr()) {
2469
+ throw submitted.error;
2470
+ }
2471
+ if (submitted.value.result === "submitted-step") {
2472
+ throw submitted.value.abort;
2473
+ }
2200
2474
  if (!this.promises.has(lazyStepList)) {
2201
2475
  const promise2 = this.getExecutionPromise(lazyStepList);
2202
2476
  this.promises.set(lazyStepList, promise2);
@@ -2250,18 +2524,108 @@ var AutoExecutor = class _AutoExecutor {
2250
2524
  }
2251
2525
  return parsedOut;
2252
2526
  }
2253
- const resultStep = await submitSingleStep({
2254
- context: this.context,
2527
+ const mismatch = lazyStep.stepSettings ? describeStepSettingsMismatch(lazyStep.stepSettings, this.effectiveConfig) : void 0;
2528
+ if (mismatch) {
2529
+ if (!this.effectiveConfig.hasStepConfig) {
2530
+ await publishStepConfigRequest({
2531
+ context: this.context,
2532
+ lazyStep,
2533
+ targetStep: this.stepCount,
2534
+ invokeCount: this.invokeCount,
2535
+ telemetry: this.telemetry,
2536
+ dispatchDebug: this.dispatchDebug
2537
+ });
2538
+ throw new WorkflowAbort(lazyStep.stepName);
2539
+ } else {
2540
+ await this.dispatchDebug("onWarning", {
2541
+ warning: `The step-level settings of step '${lazyStep.stepName}' were published but are not recognized on the delivery which carries them (${mismatch}). Executing the step with the settings of the delivery instead. This is a bug in @upstash/workflow, please report it.`
2542
+ });
2543
+ }
2544
+ }
2545
+ const resultStep = await executeStep({
2255
2546
  lazyStep,
2256
2547
  stepId: this.stepCount,
2548
+ concurrency: NO_CONCURRENCY,
2549
+ dispatchLifecycle: this.dispatchLifecycle
2550
+ });
2551
+ if (lazyStep.supportsDeferredSubmission) {
2552
+ const serializedOut = JSON.stringify(resultStep.out);
2553
+ this.pendingStep = {
2554
+ status: "held",
2555
+ lazyStep,
2556
+ resultStep: {
2557
+ ...resultStep,
2558
+ out: serializedOut === void 0 ? void 0 : JSON.parse(serializedOut)
2559
+ }
2560
+ };
2561
+ return lazyStep.parseOut({
2562
+ ...resultStep,
2563
+ out: serializedOut
2564
+ });
2565
+ }
2566
+ await submitStepResult({
2567
+ context: this.context,
2568
+ lazyStep,
2569
+ resultStep,
2257
2570
  invokeCount: this.invokeCount,
2258
- concurrency: 1,
2571
+ concurrency: NO_CONCURRENCY,
2259
2572
  telemetry: this.telemetry,
2260
- dispatchDebug: this.dispatchDebug,
2261
- dispatchLifecycle: this.dispatchLifecycle
2573
+ dispatchDebug: this.dispatchDebug
2262
2574
  });
2263
2575
  throw new WorkflowAbort(lazyStep.stepName, resultStep);
2264
2576
  }
2577
+ /**
2578
+ * Submits the result of the step being held, if there is one, and
2579
+ * returns the abort the caller has to throw to end the invocation.
2580
+ *
2581
+ * Returns undefined when no step is being held, which is the caller's
2582
+ * signal that there is nothing to end. Throws instead of returning
2583
+ * when the submission itself fails, so that error reaches the caller
2584
+ * rather than an abort claiming the step was submitted.
2585
+ *
2586
+ * Callers which arrive while a submission is already under way (the
2587
+ * steps of a parallel group, added together) wait for that one and get
2588
+ * the same abort, rather than submitting a second time.
2589
+ *
2590
+ * The next step's settings are attached whenever it has any, without
2591
+ * checking them against the current delivery: the executor only knows
2592
+ * the configuration of the delivery in hand, which inside a
2593
+ * delivery is the *previous* step's, so such a check would be wrong
2594
+ * exactly when two steps with settings follow each other.
2595
+ *
2596
+ * @param nextStepSettings step-level settings of the next step
2597
+ * @returns `submitted-step` with the abort which ends this invocation,
2598
+ * or `no-pending-step` when nothing was held and there is nothing to
2599
+ * end
2600
+ */
2601
+ async submitPendingStep(nextStepSettings) {
2602
+ if (!this.pendingStep) {
2603
+ return ok({ result: "no-pending-step" });
2604
+ }
2605
+ try {
2606
+ if (this.pendingStep.status === "submitting") {
2607
+ return ok({ result: "submitted-step", abort: await this.pendingStep.submitted });
2608
+ }
2609
+ const { lazyStep, resultStep } = this.pendingStep;
2610
+ const submitted = (async () => {
2611
+ await submitStepResult({
2612
+ context: this.context,
2613
+ lazyStep,
2614
+ resultStep,
2615
+ invokeCount: this.invokeCount,
2616
+ concurrency: NO_CONCURRENCY,
2617
+ telemetry: this.telemetry,
2618
+ dispatchDebug: this.dispatchDebug,
2619
+ nextStepSettings
2620
+ });
2621
+ return new WorkflowAbort(lazyStep.stepName, resultStep);
2622
+ })();
2623
+ this.pendingStep = { status: "submitting", submitted };
2624
+ return ok({ result: "submitted-step", abort: await submitted });
2625
+ } catch (error) {
2626
+ return err(error);
2627
+ }
2628
+ }
2265
2629
  /**
2266
2630
  * Runs steps in parallel.
2267
2631
  *
@@ -2310,15 +2674,20 @@ var AutoExecutor = class _AutoExecutor {
2310
2674
  validateStep(parallelSteps[stepIndex], planStep);
2311
2675
  try {
2312
2676
  const parallelStep = parallelSteps[stepIndex];
2313
- const resultStep = await submitSingleStep({
2314
- context: this.context,
2677
+ const resultStep = await executeStep({
2315
2678
  lazyStep: parallelStep,
2316
2679
  stepId: planStep.targetStep,
2680
+ concurrency: parallelSteps.length,
2681
+ dispatchLifecycle: this.dispatchLifecycle
2682
+ });
2683
+ await submitStepResult({
2684
+ context: this.context,
2685
+ lazyStep: parallelStep,
2686
+ resultStep,
2317
2687
  invokeCount: this.invokeCount,
2318
2688
  concurrency: parallelSteps.length,
2319
2689
  telemetry: this.telemetry,
2320
- dispatchDebug: this.dispatchDebug,
2321
- dispatchLifecycle: this.dispatchLifecycle
2690
+ dispatchDebug: this.dispatchDebug
2322
2691
  });
2323
2692
  throw new WorkflowAbort(parallelStep.stepName, resultStep);
2324
2693
  } catch (error) {
@@ -2536,6 +2905,11 @@ var BaseWorkflowApi = class {
2536
2905
 
2537
2906
  // src/context/api/anthropic.ts
2538
2907
  var AnthropicAPI = class extends BaseWorkflowApi {
2908
+ /**
2909
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2910
+ *
2911
+ * @see node_modules/@upstash/workflow/docs/integrations/anthropic.mdx
2912
+ */
2539
2913
  async call(stepName, settings) {
2540
2914
  const { token, operation, ...parameters } = settings;
2541
2915
  return await this.callApi(stepName, {
@@ -2551,6 +2925,11 @@ var AnthropicAPI = class extends BaseWorkflowApi {
2551
2925
  // src/context/api/openai.ts
2552
2926
  import { custom, openai } from "@upstash/qstash";
2553
2927
  var OpenAIAPI = class extends BaseWorkflowApi {
2928
+ /**
2929
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2930
+ *
2931
+ * @see node_modules/@upstash/workflow/docs/integrations/openai.mdx
2932
+ */
2554
2933
  async call(stepName, settings) {
2555
2934
  const { token, organization, operation, baseURL, ...parameters } = settings;
2556
2935
  const useOpenAI = baseURL === void 0;
@@ -2568,6 +2947,11 @@ var OpenAIAPI = class extends BaseWorkflowApi {
2568
2947
  // src/context/api/resend.ts
2569
2948
  import { resend } from "@upstash/qstash";
2570
2949
  var ResendAPI = class extends BaseWorkflowApi {
2950
+ /**
2951
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2952
+ *
2953
+ * @see node_modules/@upstash/workflow/docs/integrations/resend.mdx
2954
+ */
2571
2955
  async call(stepName, settings) {
2572
2956
  const { token, batch = false, ...parameters } = settings;
2573
2957
  return await this.callApi(stepName, {
@@ -2734,8 +3118,9 @@ var WorkflowContext = class {
2734
3118
  *
2735
3119
  * ```ts
2736
3120
  * import { Client } from "@upstash/qstash"
3121
+ * import { serve } from "@upstash/workflow/nextjs"
2737
3122
  *
2738
- * export const POST = serve(
3123
+ * export const { POST } = serve(
2739
3124
  * async (context) => {
2740
3125
  * ...
2741
3126
  * },
@@ -2760,7 +3145,7 @@ var WorkflowContext = class {
2760
3145
  * Can be overwritten by passing a `url` parameter in `serve`:
2761
3146
  *
2762
3147
  * ```ts
2763
- * export const POST = serve(
3148
+ * export const { POST } = serve(
2764
3149
  * async (context) => {
2765
3150
  * ...
2766
3151
  * },
@@ -2778,7 +3163,7 @@ var WorkflowContext = class {
2778
3163
  *
2779
3164
  * ```ts
2780
3165
  * // set requestPayload type to MyPayload:
2781
- * export const POST = serve<MyPayload>(
3166
+ * export const { POST } = serve<MyPayload>(
2782
3167
  * async (context) => {
2783
3168
  * ...
2784
3169
  * }
@@ -2790,7 +3175,7 @@ var WorkflowContext = class {
2790
3175
  * the `initialPayloadParser` parameter:
2791
3176
  *
2792
3177
  * ```ts
2793
- * export const POST = serve<MyPayload>(
3178
+ * export const { POST } = serve<MyPayload>(
2794
3179
  * async (context) => {
2795
3180
  * ...
2796
3181
  * },
@@ -2799,6 +3184,13 @@ var WorkflowContext = class {
2799
3184
  * }
2800
3185
  * )
2801
3186
  * ```
3187
+ *
3188
+ * When a `context.call` response comes back, the route runs up to its first step with this
3189
+ * set to the call-result envelope (and `workflowRunId` set to a random id) before the SDK
3190
+ * recognizes the request. Code before the first step must not dereference, validate or
3191
+ * return early on the payload; read it inside `context.run`.
3192
+ *
3193
+ * @see node_modules/@upstash/workflow/docs/basics/serve/advanced.mdx
2802
3194
  */
2803
3195
  requestPayload;
2804
3196
  /**
@@ -2811,7 +3203,7 @@ var WorkflowContext = class {
2811
3203
  * Can be set using the `env` option of serve:
2812
3204
  *
2813
3205
  * ```ts
2814
- * export const POST = serve<MyPayload>(
3206
+ * export const { POST } = serve<MyPayload>(
2815
3207
  * async (context) => {
2816
3208
  * const key = context.env["API_KEY"];
2817
3209
  * },
@@ -2859,6 +3251,46 @@ var WorkflowContext = class {
2859
3251
  * `1` on the first retry, `2` on the second, and so on.
2860
3252
  */
2861
3253
  retried;
3254
+ /**
3255
+ * Configuration QStash applied to the request being handled.
3256
+ *
3257
+ * This is the configuration of *this delivery*, not of the run: it is
3258
+ * the configuration the run was triggered with, except inside the
3259
+ * delivery which executes a step that has step-level settings, where
3260
+ * it is that step's settings. The fields below expose it; the executor
3261
+ * gets it directly rather than reaching through the context.
3262
+ */
3263
+ effectiveConfig;
3264
+ /**
3265
+ * Flow control QStash applied to the request being handled, if any.
3266
+ *
3267
+ * This is the flow control of the request in hand, which is the one the
3268
+ * run was triggered with except inside a step carrying its own.
3269
+ */
3270
+ get flowControl() {
3271
+ return this.effectiveConfig.flowControl;
3272
+ }
3273
+ /**
3274
+ * Retry limit QStash applied to the request being handled, if it
3275
+ * reported one.
3276
+ *
3277
+ * Not to be confused with {@link retried}, which is how many retries
3278
+ * have already happened.
3279
+ *
3280
+ * @see {@link flowControl} for what "the request being handled" means
3281
+ */
3282
+ get retries() {
3283
+ return this.effectiveConfig.retries;
3284
+ }
3285
+ /**
3286
+ * Retry delay expression QStash applied to the request being handled,
3287
+ * if any.
3288
+ *
3289
+ * @see {@link flowControl} for what "the request being handled" means
3290
+ */
3291
+ get retryDelay() {
3292
+ return this.effectiveConfig.retryDelay;
3293
+ }
2862
3294
  constructor({
2863
3295
  qstashClient,
2864
3296
  workflowRunId,
@@ -2872,7 +3304,8 @@ var WorkflowContext = class {
2872
3304
  invokeCount,
2873
3305
  label,
2874
3306
  retried,
2875
- middlewareManager
3307
+ middlewareManager,
3308
+ effectiveConfig
2876
3309
  }) {
2877
3310
  this.qstashClient = qstashClient;
2878
3311
  this.workflowRunId = workflowRunId;
@@ -2884,6 +3317,7 @@ var WorkflowContext = class {
2884
3317
  this.env = env ?? {};
2885
3318
  this.labels = label === void 0 ? [] : Array.isArray(label) ? label : label ? label.split(",") : [];
2886
3319
  this.retried = retried ?? 0;
3320
+ this.effectiveConfig = effectiveConfig ?? { hasStepConfig: false };
2887
3321
  const middlewareManagerInstance = middlewareManager ?? new MiddlewareManager([]);
2888
3322
  middlewareManagerInstance.assignContext(this);
2889
3323
  this.executor = new AutoExecutor(
@@ -2892,7 +3326,8 @@ var WorkflowContext = class {
2892
3326
  middlewareManagerInstance.dispatchDebug.bind(middlewareManagerInstance),
2893
3327
  middlewareManagerInstance.dispatchLifecycle.bind(middlewareManagerInstance),
2894
3328
  telemetry,
2895
- invokeCount
3329
+ invokeCount,
3330
+ this.effectiveConfig
2896
3331
  );
2897
3332
  }
2898
3333
  /**
@@ -2918,13 +3353,41 @@ var WorkflowContext = class {
2918
3353
  * ])
2919
3354
  * ```
2920
3355
  *
3356
+ * Step-level settings can be passed as a third argument, overriding
3357
+ * the settings the workflow run was triggered with for this step only:
3358
+ *
3359
+ * ```typescript
3360
+ * const result = await context.run(
3361
+ * "step 1",
3362
+ * () => {
3363
+ * return "result"
3364
+ * },
3365
+ * {
3366
+ * flowControl: { key: "custom-key", parallelism: 3 },
3367
+ * retries: 5,
3368
+ * }
3369
+ * )
3370
+ * ```
3371
+ *
3372
+ * Do not wrap steps in try/catch or `.catch` without rethrowing `WorkflowAbort`: each step
3373
+ * throws it to end the request. To stop retrying a failed step, throw
3374
+ * `WorkflowNonRetryableError`.
3375
+ *
2921
3376
  * @param stepName name of the step
2922
3377
  * @param stepFunction step function to be executed
3378
+ * @param stepSettings step-level settings for this step
2923
3379
  * @returns result of the step function
3380
+ * @see node_modules/@upstash/workflow/docs/steps/run.mdx
2924
3381
  */
2925
- async run(stepName, stepFunction) {
3382
+ async run(stepName, stepFunction, stepSettings) {
3383
+ const normalizedSettings = normalizeStepSettings(stepSettings);
3384
+ if (stepSettings) {
3385
+ validateFlowControl(stepSettings.flowControl);
3386
+ }
2926
3387
  const wrappedStepFunction = (() => this.executor.wrapStep(stepName, stepFunction));
2927
- return await this.addStep(new LazyFunctionStep(this, stepName, wrappedStepFunction));
3388
+ return await this.addStep(
3389
+ new LazyFunctionStep(this, stepName, wrappedStepFunction, normalizedSettings)
3390
+ );
2928
3391
  }
2929
3392
  /**
2930
3393
  * Stops the execution for the duration provided.
@@ -2934,8 +3397,9 @@ var WorkflowContext = class {
2934
3397
  * ```
2935
3398
  *
2936
3399
  * @param stepName
2937
- * @param duration sleep duration in seconds
3400
+ * @param duration sleep duration in seconds, or a duration string such as "10m"
2938
3401
  * @returns undefined
3402
+ * @see node_modules/@upstash/workflow/docs/steps/sleep.mdx
2939
3403
  */
2940
3404
  async sleep(stepName, duration) {
2941
3405
  await this.addStep(new LazySleepStep(this, stepName, duration));
@@ -2949,8 +3413,11 @@ var WorkflowContext = class {
2949
3413
  *
2950
3414
  * @param stepName
2951
3415
  * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
2952
- * as a Date object or a string (passed to `new Date(datetimeString)`)
3416
+ * as a Date object or a string (passed to `new Date(datetimeString)`).
3417
+ * A millisecond timestamp such as `Date.now()` is too far in the future, so QStash
3418
+ * rejects the step and the run fails. Pass `new Date(ms)` instead.
2953
3419
  * @returns undefined
3420
+ * @see node_modules/@upstash/workflow/docs/steps/sleepUntil.mdx
2954
3421
  */
2955
3422
  async sleepUntil(stepName, datetime) {
2956
3423
  let time;
@@ -3001,7 +3468,7 @@ var WorkflowContext = class {
3001
3468
  * Pauses workflow execution until a specific event occurs or a timeout is reached.
3002
3469
  *
3003
3470
  *```ts
3004
- * const result = await workflow.waitForEvent("payment-confirmed", "payment.confirmed", {
3471
+ * const result = await context.waitForEvent("payment-confirmed", "payment.confirmed", {
3005
3472
  * timeout: "5m"
3006
3473
  * });
3007
3474
  *```
@@ -3025,11 +3492,14 @@ var WorkflowContext = class {
3025
3492
  * Alternatively, you can use the `context.notify` method.
3026
3493
  *
3027
3494
  * @param stepName
3028
- * @param eventId - Unique identifier for the event to wait for
3495
+ * @param eventId - Unique identifier for the event to wait for. Only letters, digits,
3496
+ * "-", "_" and "." are allowed. QStash rejects other characters, such as ":", which
3497
+ * stops the run with only a "Tried to append to a cancelled workflow" warning.
3029
3498
  * @param options - Configuration options.
3030
3499
  * @returns `{ timeout: boolean, eventData: TEventData }`.
3031
3500
  * The `timeout` property specifies if the workflow has timed out. The `eventData`
3032
3501
  * is the data passed when notifying this workflow of an event.
3502
+ * @see node_modules/@upstash/workflow/docs/steps/waitForEvent.mdx
3033
3503
  */
3034
3504
  async waitForEvent(stepName, eventId, options = {}) {
3035
3505
  const { timeout = "7d" } = options;
@@ -3051,28 +3521,31 @@ var WorkflowContext = class {
3051
3521
  * will receive the given event data and resume execution.
3052
3522
  *
3053
3523
  * The response includes the same eventId and eventData. Additionally, there is
3054
- * a notifyResponse field which contains a list of `Waiter` objects, each corresponding
3055
- * to a notified workflow run.
3056
- *
3057
- * Optionally, you can pass a workflowRunId to enable lookback functionality:
3058
- *
3059
- * ```ts
3060
- * const { eventId, eventData, notifyResponse } = await context.notify(
3061
- * "notify step", "event-id", "event-data", "wfr_123"
3062
- * );
3063
- * ```
3524
+ * a notifyResponse field which contains a list of `NotifyResponse` objects, each corresponding
3525
+ * to a notified workflow run. The notified `Waiter` is under `notifyResponse[i].waiter`.
3064
3526
  *
3065
3527
  * @param stepName
3066
- * @param eventId event id to notify
3528
+ * @param eventId event id to notify. Only letters, digits, "-", "_" and "." are allowed.
3529
+ * QStash rejects other characters, such as ":", which stops the run with only a
3530
+ * "Tried to append to a cancelled workflow" warning.
3067
3531
  * @param eventData event data to notify with
3068
- * @param workflowRunId optional workflow run id for lookback support
3069
- * @returns notify response which has event id, event data and list of waiters which were notified
3532
+ * @param workflowRunId optional workflow run id for lookback: the event is kept for the run
3533
+ * even if it has not reached `waitForEvent` yet
3534
+ * @returns notify response which has event id, event data and list of waiters which were
3535
+ * notified. With `workflowRunId`, QStash returns `notifyResponse` as a single object instead
3536
+ * of an array, despite the type.
3537
+ * @see node_modules/@upstash/workflow/docs/steps/notify.mdx
3070
3538
  */
3071
3539
  async notify(stepName, eventId, eventData, workflowRunId) {
3072
3540
  return await this.addStep(
3073
3541
  new LazyNotifyStep(this, stepName, eventId, eventData, this.qstashClient.http, workflowRunId)
3074
3542
  );
3075
3543
  }
3544
+ /**
3545
+ * Starts another workflow run and waits for its result.
3546
+ *
3547
+ * @see node_modules/@upstash/workflow/docs/steps/invoke.mdx
3548
+ */
3076
3549
  async invoke(stepName, settings) {
3077
3550
  validateLabel(settings.label);
3078
3551
  validateFlowControl(settings.flowControl);
@@ -3080,9 +3553,15 @@ var WorkflowContext = class {
3080
3553
  new LazyInvokeStep(this, stepName, settings)
3081
3554
  );
3082
3555
  }
3556
+ /**
3557
+ * @see node_modules/@upstash/workflow/docs/steps/createWebhook.mdx
3558
+ */
3083
3559
  async createWebhook(stepName) {
3084
3560
  return await this.addStep(new LazyCreateWebhookStep(this, stepName));
3085
3561
  }
3562
+ /**
3563
+ * @see node_modules/@upstash/workflow/docs/steps/waitForWebhook.mdx
3564
+ */
3086
3565
  async waitForWebhook(stepName, webhook, timeout) {
3087
3566
  return await this.addStep(new LazyWaitForWebhookStep(this, stepName, webhook, timeout));
3088
3567
  }
@@ -3091,6 +3570,8 @@ var WorkflowContext = class {
3091
3570
  *
3092
3571
  * Will throw WorkflowCancelAbort to stop workflow execution.
3093
3572
  * Shouldn't be inside try/catch.
3573
+ *
3574
+ * @see node_modules/@upstash/workflow/docs/steps/cancel.mdx
3094
3575
  */
3095
3576
  async cancel() {
3096
3577
  throw new WorkflowCancelAbort();
@@ -3109,6 +3590,11 @@ var WorkflowContext = class {
3109
3590
  throw error;
3110
3591
  }
3111
3592
  }
3593
+ /**
3594
+ * Calls OpenAI, Anthropic or Resend through QStash, like `context.call`.
3595
+ *
3596
+ * @see node_modules/@upstash/workflow/docs/steps/api.mdx
3597
+ */
3112
3598
  get api() {
3113
3599
  return new WorkflowApi({
3114
3600
  context: this
@@ -3224,7 +3710,7 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
3224
3710
  *
3225
3711
  * @param routeFunction
3226
3712
  */
3227
- static async tryAuthentication(routeFunction, context) {
3713
+ static async tryAuthentication(routeFunction, context, effectiveConfig) {
3228
3714
  const disabledContext = new _DisabledWorkflowContext({
3229
3715
  qstashClient: new Client2({
3230
3716
  baseUrl: "disabled-client",
@@ -3239,7 +3725,10 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
3239
3725
  initialPayload: context.requestPayload,
3240
3726
  env: context.env,
3241
3727
  label: context.labels,
3242
- retried: context.retried
3728
+ retried: context.retried,
3729
+ // the route function runs for real here until it reaches a step, so
3730
+ // it observes the same configuration as it will on the real context
3731
+ effectiveConfig
3243
3732
  });
3244
3733
  try {
3245
3734
  await routeFunction(disabledContext);
@@ -3456,6 +3945,7 @@ var handleFailure = async ({
3456
3945
  }
3457
3946
  const userHeaders = recreateUserHeaders(request.headers);
3458
3947
  const retried = Number(request.headers.get(WORKFLOW_RETRIED_HEADER) ?? "0");
3948
+ const effectiveConfig = getEffectiveConfig(request.headers);
3459
3949
  const workflowContext = new WorkflowContext({
3460
3950
  qstashClient,
3461
3951
  workflowRunId,
@@ -3469,11 +3959,13 @@ var handleFailure = async ({
3469
3959
  label: userHeaders.get(WORKFLOW_LABEL_HEADER) ?? void 0,
3470
3960
  retried,
3471
3961
  workflowRunCreatedAt: workflowCreatedAt,
3472
- middlewareManager: void 0
3962
+ middlewareManager: void 0,
3963
+ effectiveConfig
3473
3964
  });
3474
3965
  const authCheck = await DisabledWorkflowContext.tryAuthentication(
3475
3966
  routeFunction,
3476
- workflowContext
3967
+ workflowContext,
3968
+ effectiveConfig
3477
3969
  );
3478
3970
  if (authCheck.isErr()) {
3479
3971
  await dispatchDebug?.("onError", {
@@ -3890,12 +4382,14 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
3890
4382
  const label = request.headers.get(WORKFLOW_LABEL_HEADER) ?? void 0;
3891
4383
  const workflowRunCreatedAtHeader = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
3892
4384
  const workflowRunCreatedAt = workflowRunCreatedAtHeader ? Number(workflowRunCreatedAtHeader) : isFirstInvocation ? Date.now() : 0;
4385
+ const effectiveConfig = getEffectiveConfig(request.headers);
3893
4386
  const workflowContext = new WorkflowContext({
3894
4387
  qstashClient: regionalClient,
3895
4388
  workflowRunId,
3896
4389
  initialPayload: isThirdPartyCallResult(request) ? JSON.parse(rawInitialPayload) : initialPayloadParser(rawInitialPayload),
3897
4390
  headers: recreateUserHeaders(request.headers),
3898
4391
  steps,
4392
+ effectiveConfig,
3899
4393
  url: workflowUrl,
3900
4394
  env,
3901
4395
  telemetry,
@@ -3907,7 +4401,8 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
3907
4401
  });
3908
4402
  const authCheck = await DisabledWorkflowContext.tryAuthentication(
3909
4403
  routeFunction,
3910
- workflowContext
4404
+ workflowContext,
4405
+ effectiveConfig
3911
4406
  );
3912
4407
  if (authCheck.isErr()) {
3913
4408
  throw authCheck.error;
@@ -3944,7 +4439,23 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
3944
4439
  if (steps.length === 1) {
3945
4440
  await middlewareManager.dispatchLifecycle("runStarted", {});
3946
4441
  }
3947
- return await routeFunction(workflowContext);
4442
+ let outcome;
4443
+ try {
4444
+ outcome = { ran: true, result: await routeFunction(workflowContext) };
4445
+ } catch (error) {
4446
+ outcome = { ran: false, error };
4447
+ }
4448
+ const submitted = await flushPendingStep(workflowContext);
4449
+ if (submitted.isErr()) {
4450
+ throw submitted.error;
4451
+ }
4452
+ if (submitted.value.result === "submitted-step") {
4453
+ throw submitted.value.abort;
4454
+ }
4455
+ if (!outcome.ran) {
4456
+ throw outcome.error;
4457
+ }
4458
+ return outcome.result;
3948
4459
  },
3949
4460
  onCleanup: async (result2) => {
3950
4461
  await middlewareManager.dispatchLifecycle("runCompleted", {