@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
package/nextjs.js CHANGED
@@ -220,6 +220,14 @@ var WORKFLOW_CREATED_AT_HEADER = "Upstash-Workflow-CreatedAt";
220
220
  var WORKFLOW_FAILURE_HEADER = "Upstash-Workflow-Is-Failure";
221
221
  var WORKFLOW_FAILURE_CALLBACK_HEADER = "Upstash-Workflow-Failure-Callback";
222
222
  var WORKFLOW_FEATURE_HEADER = "Upstash-Feature-Set";
223
+ var WORKFLOW_FEATURE_SET = "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig";
224
+ var WORKFLOW_STEP_CONFIG_CALL_TYPE = "stepConfig";
225
+ var WORKFLOW_STEP_CONFIG_HEADER = "Upstash-Workflow-Step-Config";
226
+ var FLOW_CONTROL_KEY_HEADER = "Upstash-Flow-Control-Key";
227
+ var FLOW_CONTROL_VALUE_HEADER = "Upstash-Flow-Control-Value";
228
+ var RETRIES_HEADER = "Upstash-Retries";
229
+ var RETRY_DELAY_HEADER = "Upstash-Retry-Delay";
230
+ var WORKFLOW_STEP_CONFIG_FEATURE = "WF_StepConfig";
223
231
  var WORKFLOW_INVOKE_COUNT_HEADER = "Upstash-Workflow-Invoke-Count";
224
232
  var WORKFLOW_RETRIED_HEADER = "Upstash-Retried";
225
233
  var WORKFLOW_LABEL_HEADER = "Upstash-Label";
@@ -237,102 +245,6 @@ var TELEMETRY_HEADER_SDK = "Upstash-Telemetry-Sdk";
237
245
  var TELEMETRY_HEADER_FRAMEWORK = "Upstash-Telemetry-Framework";
238
246
  var TELEMETRY_HEADER_RUNTIME = "Upstash-Telemetry-Runtime";
239
247
 
240
- // src/context/auto-executor.ts
241
- var import_qstash5 = require("@upstash/qstash");
242
-
243
- // src/qstash/headers.ts
244
- var import_qstash4 = require("@upstash/qstash");
245
-
246
- // src/utils.ts
247
- var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
248
- var NANOID_LENGTH = 21;
249
- var RESOURCE_NAME_PATTERN = /^[a-zA-Z0-9\-_.]+$/;
250
- function validateLabel(label) {
251
- if (label === void 0) return;
252
- const labels = Array.isArray(label) ? label : [label];
253
- if (labels.length === 0) {
254
- throw new WorkflowNonRetryableError("Invalid label: label array must not be empty.");
255
- }
256
- for (const value of labels) {
257
- if (!RESOURCE_NAME_PATTERN.test(value)) {
258
- throw new WorkflowNonRetryableError(
259
- `Invalid label "${value}": must be alphanumeric, hyphen, underscore, or period.`
260
- );
261
- }
262
- }
263
- }
264
- function serializeLabel(label) {
265
- return Array.isArray(label) ? label.join(",") : label;
266
- }
267
- function validateFlowControl(flowControl) {
268
- if (flowControl?.key !== void 0 && !RESOURCE_NAME_PATTERN.test(flowControl.key)) {
269
- throw new WorkflowNonRetryableError(
270
- `Invalid flow control key "${flowControl.key}": must be alphanumeric, hyphen, underscore, or period.`
271
- );
272
- }
273
- }
274
- function getRandomInt() {
275
- return Math.floor(Math.random() * NANOID_CHARS.length);
276
- }
277
- function nanoid(length = NANOID_LENGTH) {
278
- return Array.from({ length }).map(() => NANOID_CHARS[getRandomInt()]).join("");
279
- }
280
- function getWorkflowRunId(id) {
281
- return `wfr_${id ?? nanoid()}`;
282
- }
283
- function decodeBase64(base64) {
284
- const binString = atob(base64);
285
- try {
286
- const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
287
- return new TextDecoder().decode(intArray);
288
- } catch (error) {
289
- console.warn(
290
- `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. ${error}`
291
- );
292
- return binString;
293
- }
294
- }
295
- function getUserIdFromToken(qstashClient) {
296
- try {
297
- const token = qstashClient.token;
298
- const decodedToken = decodeBase64(token);
299
- const tokenPayload = JSON.parse(decodedToken);
300
- const userId = tokenPayload.UserID;
301
- if (!userId) {
302
- throw new WorkflowError("QStash token payload does not contain userId");
303
- }
304
- return userId;
305
- } catch (error) {
306
- throw new WorkflowError(
307
- `Failed to decode QStash token while running create webhook step: ${error.message}`
308
- );
309
- }
310
- }
311
- function getQStashUrl(qstashClient) {
312
- try {
313
- const requester = qstashClient.http;
314
- const baseUrl = requester.baseUrl;
315
- if (!baseUrl) {
316
- throw new WorkflowError("QStash client does not have a baseUrl");
317
- }
318
- return baseUrl;
319
- } catch (error) {
320
- throw new WorkflowError(`Failed to get QStash URL from client: ${error.message}`);
321
- }
322
- }
323
- function getEventId() {
324
- return `evt_${nanoid(15)}`;
325
- }
326
- function stringifyBody(body) {
327
- if (body === void 0) {
328
- return void 0;
329
- }
330
- if (typeof body === "string") {
331
- return body;
332
- }
333
- return JSON.stringify(body);
334
- }
335
-
336
248
  // node_modules/neverthrow/dist/index.es.js
337
249
  var defaultErrorConfig = {
338
250
  withStackTrace: false
@@ -748,6 +660,102 @@ var Err = class {
748
660
  };
749
661
  var fromThrowable = Result.fromThrowable;
750
662
 
663
+ // src/context/auto-executor.ts
664
+ var import_qstash5 = require("@upstash/qstash");
665
+
666
+ // src/qstash/headers.ts
667
+ var import_qstash4 = require("@upstash/qstash");
668
+
669
+ // src/utils.ts
670
+ var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
671
+ var NANOID_LENGTH = 21;
672
+ var RESOURCE_NAME_PATTERN = /^[a-zA-Z0-9\-_.]+$/;
673
+ function validateLabel(label) {
674
+ if (label === void 0) return;
675
+ const labels = Array.isArray(label) ? label : [label];
676
+ if (labels.length === 0) {
677
+ throw new WorkflowNonRetryableError("Invalid label: label array must not be empty.");
678
+ }
679
+ for (const value of labels) {
680
+ if (!RESOURCE_NAME_PATTERN.test(value)) {
681
+ throw new WorkflowNonRetryableError(
682
+ `Invalid label "${value}": must be alphanumeric, hyphen, underscore, or period.`
683
+ );
684
+ }
685
+ }
686
+ }
687
+ function serializeLabel(label) {
688
+ return Array.isArray(label) ? label.join(",") : label;
689
+ }
690
+ function validateFlowControl(flowControl) {
691
+ if (flowControl?.key !== void 0 && !RESOURCE_NAME_PATTERN.test(flowControl.key)) {
692
+ throw new WorkflowNonRetryableError(
693
+ `Invalid flow control key "${flowControl.key}": must be alphanumeric, hyphen, underscore, or period.`
694
+ );
695
+ }
696
+ }
697
+ function getRandomInt() {
698
+ return Math.floor(Math.random() * NANOID_CHARS.length);
699
+ }
700
+ function nanoid(length = NANOID_LENGTH) {
701
+ return Array.from({ length }).map(() => NANOID_CHARS[getRandomInt()]).join("");
702
+ }
703
+ function getWorkflowRunId(id) {
704
+ return `wfr_${id ?? nanoid()}`;
705
+ }
706
+ function decodeBase64(base64) {
707
+ const binString = atob(base64);
708
+ try {
709
+ const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
710
+ return new TextDecoder().decode(intArray);
711
+ } catch (error) {
712
+ console.warn(
713
+ `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. ${error}`
714
+ );
715
+ return binString;
716
+ }
717
+ }
718
+ function getUserIdFromToken(qstashClient) {
719
+ try {
720
+ const token = qstashClient.token;
721
+ const decodedToken = decodeBase64(token);
722
+ const tokenPayload = JSON.parse(decodedToken);
723
+ const userId = tokenPayload.UserID;
724
+ if (!userId) {
725
+ throw new WorkflowError("QStash token payload does not contain userId");
726
+ }
727
+ return userId;
728
+ } catch (error) {
729
+ throw new WorkflowError(
730
+ `Failed to decode QStash token while running create webhook step: ${error.message}`
731
+ );
732
+ }
733
+ }
734
+ function getQStashUrl(qstashClient) {
735
+ try {
736
+ const requester = qstashClient.http;
737
+ const baseUrl = requester.baseUrl;
738
+ if (!baseUrl) {
739
+ throw new WorkflowError("QStash client does not have a baseUrl");
740
+ }
741
+ return baseUrl;
742
+ } catch (error) {
743
+ throw new WorkflowError(`Failed to get QStash URL from client: ${error.message}`);
744
+ }
745
+ }
746
+ function getEventId() {
747
+ return `evt_${nanoid(15)}`;
748
+ }
749
+ function stringifyBody(body) {
750
+ if (body === void 0) {
751
+ return void 0;
752
+ }
753
+ if (typeof body === "string") {
754
+ return body;
755
+ }
756
+ return JSON.stringify(body);
757
+ }
758
+
751
759
  // src/types.ts
752
760
  var StepTypes = [
753
761
  "Initial",
@@ -857,6 +865,10 @@ var triggerFirstInvocation = async (params) => {
857
865
  return err(error_);
858
866
  }
859
867
  };
868
+ var flushPendingStep = async (workflowContext) => {
869
+ const { executor } = workflowContext;
870
+ return await executor.submitPendingStep();
871
+ };
860
872
  var triggerRouteFunction = async ({
861
873
  onCleanup,
862
874
  onStep,
@@ -1069,8 +1081,29 @@ If you want to disable QStash Verification, you should clear env variables QSTAS
1069
1081
  var BaseLazyStep = class _BaseLazyStep {
1070
1082
  stepName;
1071
1083
  context;
1072
- constructor(context, stepName) {
1084
+ /**
1085
+ * step-level settings (flow control, retries etc.) which override the
1086
+ * settings the workflow run was triggered with, for this step only.
1087
+ */
1088
+ stepSettings;
1089
+ /**
1090
+ * whether this step's result can be submitted after the route function
1091
+ * has moved on, instead of right away.
1092
+ *
1093
+ * Enabled for steps whose `getResultStep` produces the final `out` —
1094
+ * which is not the same as "needs no server round trip":
1095
+ * `LazyCreateWebhookStep` builds its result in `getBody` and returns
1096
+ * `out: undefined` from `getResultStep`, so deferring it would hand
1097
+ * `undefined` to the route function.
1098
+ *
1099
+ * Deferring lets the route function continue and reveal the next step,
1100
+ * so that step's settings can ride on this step's submission instead
1101
+ * of needing a step config request of their own.
1102
+ */
1103
+ supportsDeferredSubmission = false;
1104
+ constructor(context, stepName, stepSettings) {
1073
1105
  this.context = context;
1106
+ this.stepSettings = stepSettings;
1074
1107
  if (!stepName) {
1075
1108
  throw new WorkflowError(
1076
1109
  "A workflow step name cannot be undefined or an empty string. Please provide a name for your workflow step."
@@ -1134,7 +1167,13 @@ var BaseLazyStep = class _BaseLazyStep {
1134
1167
  step.out = JSON.stringify(step.out);
1135
1168
  return JSON.stringify(step);
1136
1169
  }
1137
- getHeaders({ context, telemetry, invokeCount, step }) {
1170
+ getHeaders({
1171
+ context,
1172
+ telemetry,
1173
+ invokeCount,
1174
+ step,
1175
+ stepSettings
1176
+ }) {
1138
1177
  return getHeaders({
1139
1178
  initHeaderValue: "false",
1140
1179
  workflowConfig: {
@@ -1148,7 +1187,8 @@ var BaseLazyStep = class _BaseLazyStep {
1148
1187
  stepInfo: {
1149
1188
  step,
1150
1189
  lazyStep: this
1151
- }
1190
+ },
1191
+ stepSettings
1152
1192
  });
1153
1193
  }
1154
1194
  async submitStep({ context, body, headers }) {
@@ -1166,8 +1206,9 @@ var LazyFunctionStep = class extends BaseLazyStep {
1166
1206
  stepFunction;
1167
1207
  stepType = "Run";
1168
1208
  allowUndefinedOut = true;
1169
- constructor(context, stepName, stepFunction) {
1170
- super(context, stepName);
1209
+ supportsDeferredSubmission = true;
1210
+ constructor(context, stepName, stepFunction, stepSettings) {
1211
+ super(context, stepName, stepSettings);
1171
1212
  this.stepFunction = stepFunction;
1172
1213
  }
1173
1214
  getPlanStep(concurrent, targetStep) {
@@ -1197,6 +1238,7 @@ var LazySleepStep = class extends BaseLazyStep {
1197
1238
  sleep;
1198
1239
  stepType = "SleepFor";
1199
1240
  allowUndefinedOut = true;
1241
+ supportsDeferredSubmission = true;
1200
1242
  constructor(context, stepName, sleep) {
1201
1243
  super(context, stepName);
1202
1244
  this.sleep = sleep;
@@ -1236,6 +1278,7 @@ var LazySleepUntilStep = class extends BaseLazyStep {
1236
1278
  sleepUntil;
1237
1279
  stepType = "SleepUntil";
1238
1280
  allowUndefinedOut = true;
1281
+ supportsDeferredSubmission = true;
1239
1282
  constructor(context, stepName, sleepUntil) {
1240
1283
  super(context, stepName);
1241
1284
  this.sleepUntil = sleepUntil;
@@ -1737,6 +1780,7 @@ var WorkflowHeaders = class {
1737
1780
  invokeCount;
1738
1781
  initHeaderValue;
1739
1782
  stepInfo;
1783
+ stepSettings;
1740
1784
  headers;
1741
1785
  /**
1742
1786
  * @param params workflow header parameters
@@ -1746,17 +1790,20 @@ var WorkflowHeaders = class {
1746
1790
  workflowConfig,
1747
1791
  invokeCount,
1748
1792
  initHeaderValue,
1749
- stepInfo
1793
+ stepInfo,
1794
+ stepSettings
1750
1795
  }) {
1751
1796
  this.userHeaders = userHeaders;
1752
1797
  this.workflowConfig = workflowConfig;
1753
1798
  this.invokeCount = invokeCount;
1754
1799
  this.initHeaderValue = initHeaderValue;
1755
1800
  this.stepInfo = stepInfo;
1801
+ this.stepSettings = stepSettings;
1756
1802
  this.headers = {
1757
1803
  rawHeaders: {},
1758
1804
  workflowHeaders: {},
1759
- failureHeaders: {}
1805
+ failureHeaders: {},
1806
+ stepSettingsHeaders: {}
1760
1807
  };
1761
1808
  }
1762
1809
  getHeaders() {
@@ -1767,6 +1814,7 @@ var WorkflowHeaders = class {
1767
1814
  this.addUserHeaders();
1768
1815
  this.addInvokeCount();
1769
1816
  this.addFailureUrl();
1817
+ this.addStepSettings();
1770
1818
  const contentType = this.addContentType();
1771
1819
  return this.prefixHeaders(contentType);
1772
1820
  }
@@ -1776,7 +1824,7 @@ var WorkflowHeaders = class {
1776
1824
  [WORKFLOW_INIT_HEADER]: this.initHeaderValue,
1777
1825
  [WORKFLOW_ID_HEADER]: this.workflowConfig.workflowRunId,
1778
1826
  [WORKFLOW_URL_HEADER]: this.workflowConfig.workflowUrl,
1779
- [WORKFLOW_FEATURE_HEADER]: "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig",
1827
+ [WORKFLOW_FEATURE_HEADER]: WORKFLOW_FEATURE_SET,
1780
1828
  [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
1781
1829
  ...this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {}
1782
1830
  };
@@ -1857,7 +1905,7 @@ var WorkflowHeaders = class {
1857
1905
  this.headers.failureHeaders["Workflow-Init"] = "false";
1858
1906
  this.headers.failureHeaders["Workflow-Url"] = this.workflowConfig.workflowUrl;
1859
1907
  this.headers.failureHeaders["Workflow-Calltype"] = "failureCall";
1860
- this.headers.failureHeaders["Feature-Set"] = "LazyFetch,InitialBody,WF_DetectTrigger,WF_TriggerOnConfig";
1908
+ this.headers.failureHeaders["Feature-Set"] = WORKFLOW_FEATURE_SET;
1861
1909
  if (this.workflowConfig.retries !== void 0 && this.workflowConfig.retries !== DEFAULT_RETRIES) {
1862
1910
  this.headers.failureHeaders["Retries"] = this.workflowConfig.retries.toString();
1863
1911
  }
@@ -1865,6 +1913,42 @@ var WorkflowHeaders = class {
1865
1913
  this.headers.failureHeaders["Retry-Delay"] = this.workflowConfig.retryDelay.toString();
1866
1914
  }
1867
1915
  }
1916
+ /**
1917
+ * Applies the step-level settings of a step to the message.
1918
+ *
1919
+ * These headers configure the message itself, so that QStash uses them
1920
+ * instead of the settings the run was triggered with. The delivery of
1921
+ * the message is what executes the step, which is how a step's
1922
+ * settings reach it.
1923
+ *
1924
+ * When any setting is present the feature set is extended with
1925
+ * `WF_StepConfig`, which is what tells QStash to keep them. QStash
1926
+ * reports that back on the delivery as `Upstash-Workflow-Step-Config`.
1927
+ */
1928
+ addStepSettings() {
1929
+ if (!this.stepSettings) {
1930
+ return;
1931
+ }
1932
+ const headers = {};
1933
+ if (this.stepSettings.flowControl) {
1934
+ const { flowControlKey, flowControlValue } = prepareFlowControl(
1935
+ this.stepSettings.flowControl
1936
+ );
1937
+ headers[FLOW_CONTROL_KEY_HEADER] = flowControlKey;
1938
+ headers[FLOW_CONTROL_VALUE_HEADER] = flowControlValue;
1939
+ }
1940
+ if (this.stepSettings.retries !== void 0) {
1941
+ headers[RETRIES_HEADER] = this.stepSettings.retries.toString();
1942
+ }
1943
+ if (this.stepSettings.retryDelay) {
1944
+ headers[RETRY_DELAY_HEADER] = this.stepSettings.retryDelay;
1945
+ }
1946
+ if (Object.keys(headers).length === 0) {
1947
+ return;
1948
+ }
1949
+ headers[WORKFLOW_FEATURE_HEADER] = `${WORKFLOW_FEATURE_SET},${WORKFLOW_STEP_CONFIG_FEATURE}`;
1950
+ this.headers.stepSettingsHeaders = headers;
1951
+ }
1868
1952
  addContentType() {
1869
1953
  if (this.workflowConfig.useJSONContent) {
1870
1954
  this.headers.rawHeaders["content-type"] = "application/json";
@@ -1878,14 +1962,17 @@ var WorkflowHeaders = class {
1878
1962
  return contentType;
1879
1963
  }
1880
1964
  prefixHeaders(contentType) {
1881
- const { rawHeaders, workflowHeaders, failureHeaders } = this.headers;
1965
+ const { rawHeaders, workflowHeaders, failureHeaders, stepSettingsHeaders } = this.headers;
1882
1966
  const isCall = this.stepInfo?.lazyStep.stepType === "Call";
1883
1967
  return {
1884
1968
  headers: {
1885
1969
  ...rawHeaders,
1886
1970
  ...addPrefixToHeaders(workflowHeaders, isCall ? "Upstash-Callback-" : "Upstash-"),
1887
1971
  ...addPrefixToHeaders(failureHeaders, "Upstash-Failure-Callback-"),
1888
- ...isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {}
1972
+ ...isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {},
1973
+ // last, so they override the run's settings above. Never
1974
+ // prefixed: they configure this message, not its callback.
1975
+ ...stepSettingsHeaders
1889
1976
  },
1890
1977
  contentType
1891
1978
  };
@@ -1936,7 +2023,7 @@ var submitParallelSteps = async ({
1936
2023
  info: `Submitting ${planSteps.length} parallel steps.`
1937
2024
  });
1938
2025
  const result = await context.qstashClient.batch(
1939
- planSteps.map((planStep) => {
2026
+ planSteps.map((planStep, index) => {
1940
2027
  const { headers } = getHeaders({
1941
2028
  initHeaderValue: "false",
1942
2029
  workflowConfig: {
@@ -1945,7 +2032,8 @@ var submitParallelSteps = async ({
1945
2032
  workflowRunCreatedAt: context.workflowRunCreatedAt,
1946
2033
  telemetry
1947
2034
  },
1948
- invokeCount
2035
+ invokeCount,
2036
+ stepSettings: steps[index].stepSettings
1949
2037
  });
1950
2038
  return {
1951
2039
  headers,
@@ -1964,31 +2052,38 @@ var submitParallelSteps = async ({
1964
2052
  }
1965
2053
  throw new WorkflowAbort(planSteps[0].stepName, planSteps[0]);
1966
2054
  };
1967
- var submitSingleStep = async ({
1968
- context,
2055
+ var executeStep = async ({
1969
2056
  lazyStep,
1970
2057
  stepId,
1971
- invokeCount,
1972
2058
  concurrency,
1973
- telemetry,
1974
- dispatchDebug,
1975
2059
  dispatchLifecycle
1976
2060
  }) => {
1977
2061
  await dispatchLifecycle("beforeExecution", {
1978
2062
  stepName: lazyStep.stepName
1979
2063
  });
1980
- let resultStep;
1981
2064
  try {
1982
- resultStep = await lazyStep.getResultStep(concurrency, stepId);
2065
+ return await lazyStep.getResultStep(concurrency, stepId);
1983
2066
  } catch (error) {
1984
2067
  attachStepNameToError(error, lazyStep.stepName);
1985
2068
  throw error;
1986
2069
  }
2070
+ };
2071
+ var submitStepResult = async ({
2072
+ context,
2073
+ lazyStep,
2074
+ resultStep,
2075
+ invokeCount,
2076
+ concurrency,
2077
+ telemetry,
2078
+ dispatchDebug,
2079
+ nextStepSettings
2080
+ }) => {
1987
2081
  const { headers } = lazyStep.getHeaders({
1988
2082
  context,
1989
2083
  step: resultStep,
1990
2084
  invokeCount,
1991
- telemetry
2085
+ telemetry,
2086
+ stepSettings: nextStepSettings
1992
2087
  });
1993
2088
  const body = lazyStep.getBody({
1994
2089
  context,
@@ -2013,6 +2108,154 @@ var submitSingleStep = async ({
2013
2108
  }
2014
2109
  return resultStep;
2015
2110
  };
2111
+ var publishStepConfigRequest = async ({
2112
+ context,
2113
+ lazyStep,
2114
+ targetStep,
2115
+ invokeCount,
2116
+ telemetry,
2117
+ dispatchDebug
2118
+ }) => {
2119
+ const { headers } = getHeaders({
2120
+ initHeaderValue: "false",
2121
+ workflowConfig: {
2122
+ workflowRunId: context.workflowRunId,
2123
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
2124
+ workflowUrl: context.url,
2125
+ telemetry
2126
+ },
2127
+ invokeCount,
2128
+ stepSettings: lazyStep.stepSettings
2129
+ });
2130
+ await dispatchDebug("onInfo", {
2131
+ info: `Step "${lazyStep.stepName}" (${targetStep}) has step-level settings which the current delivery does not carry. Requesting a delivery which does.`
2132
+ });
2133
+ const result = await context.qstashClient.publishJSON({
2134
+ headers: {
2135
+ ...headers,
2136
+ "Upstash-Workflow-CallType": WORKFLOW_STEP_CONFIG_CALL_TYPE,
2137
+ "Upstash-Forward-Upstash-Workflow-StepId": targetStep.toString(),
2138
+ "Upstash-Forward-Upstash-Workflow-StepName": lazyStep.stepName
2139
+ },
2140
+ method: "POST",
2141
+ body: { targetStep, invokeCount },
2142
+ url: context.url,
2143
+ contentBasedDeduplication: true
2144
+ });
2145
+ if (result?.deduplicated) {
2146
+ await dispatchDebug("onWarning", {
2147
+ 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.`
2148
+ });
2149
+ } else if (result?.messageId) {
2150
+ await dispatchDebug("onInfo", {
2151
+ info: `Requested a delivery under the settings of step "${lazyStep.stepName}" with messageId: ${result.messageId}.`
2152
+ });
2153
+ }
2154
+ };
2155
+
2156
+ // src/qstash/step-config.ts
2157
+ var normalizeStepSettings = (settings) => {
2158
+ if (settings === void 0) {
2159
+ return void 0;
2160
+ }
2161
+ const { retries, retryDelay } = settings;
2162
+ if (retryDelay !== void 0 && typeof retryDelay !== "string") {
2163
+ throw new WorkflowNonRetryableError("Invalid step retryDelay: must be a string.");
2164
+ }
2165
+ if (retries !== void 0 && (!Number.isInteger(retries) || retries < 0)) {
2166
+ throw new WorkflowNonRetryableError("Invalid step retries: must be a non-negative integer.");
2167
+ }
2168
+ return { ...settings, retryDelay: retryDelay?.trim() || void 0 };
2169
+ };
2170
+ var DEFAULT_PARALLELISM = 0;
2171
+ var DEFAULT_RATE = 0;
2172
+ var DEFAULT_PERIOD_SECONDS = 1;
2173
+ var SECONDS_PER_UNIT = {
2174
+ s: 1,
2175
+ m: 60,
2176
+ h: 60 * 60,
2177
+ d: 24 * 60 * 60
2178
+ };
2179
+ var durationToSeconds = (duration) => {
2180
+ if (typeof duration === "number") {
2181
+ return Number.isFinite(duration) ? duration : void 0;
2182
+ }
2183
+ const match = /^(\d+)([smhd])$/.exec(duration.trim());
2184
+ if (match) {
2185
+ return Number(match[1]) * SECONDS_PER_UNIT[match[2]];
2186
+ }
2187
+ const seconds = Number(duration.trim());
2188
+ return Number.isFinite(seconds) ? seconds : void 0;
2189
+ };
2190
+ var normalizeFlowControl = (flowControl) => {
2191
+ const period = flowControl.period === void 0 ? void 0 : durationToSeconds(flowControl.period);
2192
+ return {
2193
+ key: flowControl.key,
2194
+ parallelism: flowControl.parallelism ?? DEFAULT_PARALLELISM,
2195
+ rate: flowControl.rate ?? flowControl.ratePerSecond ?? DEFAULT_RATE,
2196
+ period: period ?? DEFAULT_PERIOD_SECONDS
2197
+ };
2198
+ };
2199
+ var parseFlowControlHeaders = (key, value) => {
2200
+ if (!key) {
2201
+ return void 0;
2202
+ }
2203
+ const flowControl = {
2204
+ key,
2205
+ parallelism: DEFAULT_PARALLELISM,
2206
+ rate: DEFAULT_RATE,
2207
+ period: DEFAULT_PERIOD_SECONDS
2208
+ };
2209
+ for (const entry of (value ?? "").split(",")) {
2210
+ const [name, rawValue] = entry.split("=").map((part) => part.trim());
2211
+ if (!name || rawValue === void 0) {
2212
+ continue;
2213
+ }
2214
+ switch (name) {
2215
+ case "parallelism": {
2216
+ flowControl.parallelism = Number(rawValue);
2217
+ break;
2218
+ }
2219
+ case "rate": {
2220
+ flowControl.rate = Number(rawValue);
2221
+ break;
2222
+ }
2223
+ case "period": {
2224
+ flowControl.period = durationToSeconds(rawValue) ?? DEFAULT_PERIOD_SECONDS;
2225
+ break;
2226
+ }
2227
+ }
2228
+ }
2229
+ return flowControl;
2230
+ };
2231
+ var getEffectiveConfig = (headers) => {
2232
+ const retriesHeader = headers.get(RETRIES_HEADER);
2233
+ return {
2234
+ flowControl: parseFlowControlHeaders(
2235
+ headers.get(FLOW_CONTROL_KEY_HEADER),
2236
+ headers.get(FLOW_CONTROL_VALUE_HEADER)
2237
+ ),
2238
+ retries: retriesHeader === null ? void 0 : Number(retriesHeader),
2239
+ retryDelay: headers.get(RETRY_DELAY_HEADER) ?? void 0,
2240
+ hasStepConfig: headers.get(WORKFLOW_STEP_CONFIG_HEADER) === "true"
2241
+ };
2242
+ };
2243
+ var describeStepSettingsMismatch = (stepSettings, effectiveConfig) => {
2244
+ if (stepSettings.flowControl) {
2245
+ const wanted = normalizeFlowControl(stepSettings.flowControl);
2246
+ const applied = effectiveConfig.flowControl;
2247
+ if (!applied || applied.key !== wanted.key || applied.parallelism !== wanted.parallelism || applied.rate !== wanted.rate || applied.period !== wanted.period) {
2248
+ return `flow control: expected ${JSON.stringify(wanted)}, delivery has ${JSON.stringify(applied)}`;
2249
+ }
2250
+ }
2251
+ if (stepSettings.retries !== void 0 && effectiveConfig.retries !== void 0 && stepSettings.retries !== effectiveConfig.retries) {
2252
+ return `retries: expected ${stepSettings.retries}, delivery has ${effectiveConfig.retries}`;
2253
+ }
2254
+ if (stepSettings.retryDelay !== void 0 && stepSettings.retryDelay !== effectiveConfig.retryDelay) {
2255
+ return `retry delay: expected '${stepSettings.retryDelay}', delivery has '${effectiveConfig.retryDelay ?? ""}'`;
2256
+ }
2257
+ return void 0;
2258
+ };
2016
2259
 
2017
2260
  // src/context/auto-executor.ts
2018
2261
  var AutoExecutor = class _AutoExecutor {
@@ -2029,6 +2272,25 @@ var AutoExecutor = class _AutoExecutor {
2029
2272
  stepCount = 0;
2030
2273
  planStepCount = 0;
2031
2274
  executingStep = false;
2275
+ /**
2276
+ * an executed step whose result hasn't been submitted to QStash yet.
2277
+ *
2278
+ * Set when a step which can produce its result in-process executes. The
2279
+ * submission waits so that the route function can continue and reveal
2280
+ * what comes next: if that is a single step with step-level settings,
2281
+ * the settings ride on this submission and no step config request is
2282
+ * needed, since the delivery of the submission is what executes it.
2283
+ *
2284
+ * Flushed when the next step is reached (see `addStep`) or when the
2285
+ * route function ends (see `flushPendingStep` in `serve`).
2286
+ */
2287
+ pendingStep;
2288
+ /**
2289
+ * configuration QStash applied to the delivery being handled. A step
2290
+ * with step-level settings is settled by comparing its settings against
2291
+ * this.
2292
+ */
2293
+ effectiveConfig;
2032
2294
  /**
2033
2295
  * @param context workflow context
2034
2296
  * @param steps list of steps
@@ -2036,14 +2298,17 @@ var AutoExecutor = class _AutoExecutor {
2036
2298
  * @param dispatchLifecycle lifecycle event dispatcher
2037
2299
  * @param telemetry optional telemetry information
2038
2300
  * @param invokeCount optional invoke count
2301
+ * @param effectiveConfig configuration QStash applied to the delivery
2302
+ * being handled
2039
2303
  */
2040
- constructor(context, steps, dispatchDebug, dispatchLifecycle, telemetry, invokeCount) {
2304
+ constructor(context, steps, dispatchDebug, dispatchLifecycle, telemetry, invokeCount, effectiveConfig) {
2041
2305
  this.context = context;
2042
2306
  this.steps = steps;
2043
2307
  this.dispatchDebug = dispatchDebug;
2044
2308
  this.dispatchLifecycle = dispatchLifecycle;
2045
2309
  this.telemetry = telemetry;
2046
2310
  this.invokeCount = invokeCount ?? 0;
2311
+ this.effectiveConfig = effectiveConfig ?? { hasStepConfig: false };
2047
2312
  this.nonPlanStepCount = this.steps.filter((step) => !step.targetStep).length;
2048
2313
  }
2049
2314
  /**
@@ -2078,6 +2343,15 @@ var AutoExecutor = class _AutoExecutor {
2078
2343
  lazyStepList.push(stepInfo);
2079
2344
  const index = this.indexInCurrentList++;
2080
2345
  const requestComplete = this.deferExecution().then(async () => {
2346
+ const submitted = await this.submitPendingStep(
2347
+ lazyStepList.length === 1 ? lazyStepList[0].stepSettings : void 0
2348
+ );
2349
+ if (submitted.isErr()) {
2350
+ throw submitted.error;
2351
+ }
2352
+ if (submitted.value.result === "submitted-step") {
2353
+ throw submitted.value.abort;
2354
+ }
2081
2355
  if (!this.promises.has(lazyStepList)) {
2082
2356
  const promise2 = this.getExecutionPromise(lazyStepList);
2083
2357
  this.promises.set(lazyStepList, promise2);
@@ -2131,18 +2405,108 @@ var AutoExecutor = class _AutoExecutor {
2131
2405
  }
2132
2406
  return parsedOut;
2133
2407
  }
2134
- const resultStep = await submitSingleStep({
2135
- context: this.context,
2408
+ const mismatch = lazyStep.stepSettings ? describeStepSettingsMismatch(lazyStep.stepSettings, this.effectiveConfig) : void 0;
2409
+ if (mismatch) {
2410
+ if (!this.effectiveConfig.hasStepConfig) {
2411
+ await publishStepConfigRequest({
2412
+ context: this.context,
2413
+ lazyStep,
2414
+ targetStep: this.stepCount,
2415
+ invokeCount: this.invokeCount,
2416
+ telemetry: this.telemetry,
2417
+ dispatchDebug: this.dispatchDebug
2418
+ });
2419
+ throw new WorkflowAbort(lazyStep.stepName);
2420
+ } else {
2421
+ await this.dispatchDebug("onWarning", {
2422
+ 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.`
2423
+ });
2424
+ }
2425
+ }
2426
+ const resultStep = await executeStep({
2136
2427
  lazyStep,
2137
2428
  stepId: this.stepCount,
2429
+ concurrency: NO_CONCURRENCY,
2430
+ dispatchLifecycle: this.dispatchLifecycle
2431
+ });
2432
+ if (lazyStep.supportsDeferredSubmission) {
2433
+ const serializedOut = JSON.stringify(resultStep.out);
2434
+ this.pendingStep = {
2435
+ status: "held",
2436
+ lazyStep,
2437
+ resultStep: {
2438
+ ...resultStep,
2439
+ out: serializedOut === void 0 ? void 0 : JSON.parse(serializedOut)
2440
+ }
2441
+ };
2442
+ return lazyStep.parseOut({
2443
+ ...resultStep,
2444
+ out: serializedOut
2445
+ });
2446
+ }
2447
+ await submitStepResult({
2448
+ context: this.context,
2449
+ lazyStep,
2450
+ resultStep,
2138
2451
  invokeCount: this.invokeCount,
2139
- concurrency: 1,
2452
+ concurrency: NO_CONCURRENCY,
2140
2453
  telemetry: this.telemetry,
2141
- dispatchDebug: this.dispatchDebug,
2142
- dispatchLifecycle: this.dispatchLifecycle
2454
+ dispatchDebug: this.dispatchDebug
2143
2455
  });
2144
2456
  throw new WorkflowAbort(lazyStep.stepName, resultStep);
2145
2457
  }
2458
+ /**
2459
+ * Submits the result of the step being held, if there is one, and
2460
+ * returns the abort the caller has to throw to end the invocation.
2461
+ *
2462
+ * Returns undefined when no step is being held, which is the caller's
2463
+ * signal that there is nothing to end. Throws instead of returning
2464
+ * when the submission itself fails, so that error reaches the caller
2465
+ * rather than an abort claiming the step was submitted.
2466
+ *
2467
+ * Callers which arrive while a submission is already under way (the
2468
+ * steps of a parallel group, added together) wait for that one and get
2469
+ * the same abort, rather than submitting a second time.
2470
+ *
2471
+ * The next step's settings are attached whenever it has any, without
2472
+ * checking them against the current delivery: the executor only knows
2473
+ * the configuration of the delivery in hand, which inside a
2474
+ * delivery is the *previous* step's, so such a check would be wrong
2475
+ * exactly when two steps with settings follow each other.
2476
+ *
2477
+ * @param nextStepSettings step-level settings of the next step
2478
+ * @returns `submitted-step` with the abort which ends this invocation,
2479
+ * or `no-pending-step` when nothing was held and there is nothing to
2480
+ * end
2481
+ */
2482
+ async submitPendingStep(nextStepSettings) {
2483
+ if (!this.pendingStep) {
2484
+ return ok({ result: "no-pending-step" });
2485
+ }
2486
+ try {
2487
+ if (this.pendingStep.status === "submitting") {
2488
+ return ok({ result: "submitted-step", abort: await this.pendingStep.submitted });
2489
+ }
2490
+ const { lazyStep, resultStep } = this.pendingStep;
2491
+ const submitted = (async () => {
2492
+ await submitStepResult({
2493
+ context: this.context,
2494
+ lazyStep,
2495
+ resultStep,
2496
+ invokeCount: this.invokeCount,
2497
+ concurrency: NO_CONCURRENCY,
2498
+ telemetry: this.telemetry,
2499
+ dispatchDebug: this.dispatchDebug,
2500
+ nextStepSettings
2501
+ });
2502
+ return new WorkflowAbort(lazyStep.stepName, resultStep);
2503
+ })();
2504
+ this.pendingStep = { status: "submitting", submitted };
2505
+ return ok({ result: "submitted-step", abort: await submitted });
2506
+ } catch (error) {
2507
+ return err(error);
2508
+ }
2509
+ }
2146
2510
  /**
2147
2511
  * Runs steps in parallel.
2148
2512
  *
@@ -2191,15 +2555,20 @@ var AutoExecutor = class _AutoExecutor {
2191
2555
  validateStep(parallelSteps[stepIndex], planStep);
2192
2556
  try {
2193
2557
  const parallelStep = parallelSteps[stepIndex];
2194
- const resultStep = await submitSingleStep({
2195
- context: this.context,
2558
+ const resultStep = await executeStep({
2196
2559
  lazyStep: parallelStep,
2197
2560
  stepId: planStep.targetStep,
2561
+ concurrency: parallelSteps.length,
2562
+ dispatchLifecycle: this.dispatchLifecycle
2563
+ });
2564
+ await submitStepResult({
2565
+ context: this.context,
2566
+ lazyStep: parallelStep,
2567
+ resultStep,
2198
2568
  invokeCount: this.invokeCount,
2199
2569
  concurrency: parallelSteps.length,
2200
2570
  telemetry: this.telemetry,
2201
- dispatchDebug: this.dispatchDebug,
2202
- dispatchLifecycle: this.dispatchLifecycle
2571
+ dispatchDebug: this.dispatchDebug
2203
2572
  });
2204
2573
  throw new WorkflowAbort(parallelStep.stepName, resultStep);
2205
2574
  } catch (error) {
@@ -2417,6 +2786,11 @@ var BaseWorkflowApi = class {
2417
2786
 
2418
2787
  // src/context/api/anthropic.ts
2419
2788
  var AnthropicAPI = class extends BaseWorkflowApi {
2789
+ /**
2790
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2791
+ *
2792
+ * @see node_modules/@upstash/workflow/docs/integrations/anthropic.mdx
2793
+ */
2420
2794
  async call(stepName, settings) {
2421
2795
  const { token, operation, ...parameters } = settings;
2422
2796
  return await this.callApi(stepName, {
@@ -2432,6 +2806,11 @@ var AnthropicAPI = class extends BaseWorkflowApi {
2432
2806
  // src/context/api/openai.ts
2433
2807
  var import_qstash7 = require("@upstash/qstash");
2434
2808
  var OpenAIAPI = class extends BaseWorkflowApi {
2809
+ /**
2810
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2811
+ *
2812
+ * @see node_modules/@upstash/workflow/docs/integrations/openai.mdx
2813
+ */
2435
2814
  async call(stepName, settings) {
2436
2815
  const { token, organization, operation, baseURL, ...parameters } = settings;
2437
2816
  const useOpenAI = baseURL === void 0;
@@ -2449,6 +2828,11 @@ var OpenAIAPI = class extends BaseWorkflowApi {
2449
2828
  // src/context/api/resend.ts
2450
2829
  var import_qstash8 = require("@upstash/qstash");
2451
2830
  var ResendAPI = class extends BaseWorkflowApi {
2831
+ /**
2832
+ * Runs as a `context.call` step, so the `context.call` caveats apply.
2833
+ *
2834
+ * @see node_modules/@upstash/workflow/docs/integrations/resend.mdx
2835
+ */
2452
2836
  async call(stepName, settings) {
2453
2837
  const { token, batch = false, ...parameters } = settings;
2454
2838
  return await this.callApi(stepName, {
@@ -2690,8 +3074,9 @@ var WorkflowContext = class {
2690
3074
  *
2691
3075
  * ```ts
2692
3076
  * import { Client } from "@upstash/qstash"
3077
+ * import { serve } from "@upstash/workflow/nextjs"
2693
3078
  *
2694
- * export const POST = serve(
3079
+ * export const { POST } = serve(
2695
3080
  * async (context) => {
2696
3081
  * ...
2697
3082
  * },
@@ -2716,7 +3101,7 @@ var WorkflowContext = class {
2716
3101
  * Can be overwritten by passing a `url` parameter in `serve`:
2717
3102
  *
2718
3103
  * ```ts
2719
- * export const POST = serve(
3104
+ * export const { POST } = serve(
2720
3105
  * async (context) => {
2721
3106
  * ...
2722
3107
  * },
@@ -2734,7 +3119,7 @@ var WorkflowContext = class {
2734
3119
  *
2735
3120
  * ```ts
2736
3121
  * // set requestPayload type to MyPayload:
2737
- * export const POST = serve<MyPayload>(
3122
+ * export const { POST } = serve<MyPayload>(
2738
3123
  * async (context) => {
2739
3124
  * ...
2740
3125
  * }
@@ -2746,7 +3131,7 @@ var WorkflowContext = class {
2746
3131
  * the `initialPayloadParser` parameter:
2747
3132
  *
2748
3133
  * ```ts
2749
- * export const POST = serve<MyPayload>(
3134
+ * export const { POST } = serve<MyPayload>(
2750
3135
  * async (context) => {
2751
3136
  * ...
2752
3137
  * },
@@ -2755,6 +3140,13 @@ var WorkflowContext = class {
2755
3140
  * }
2756
3141
  * )
2757
3142
  * ```
3143
+ *
3144
+ * When a `context.call` response comes back, the route runs up to its first step with this
3145
+ * set to the call-result envelope (and `workflowRunId` set to a random id) before the SDK
3146
+ * recognizes the request. Code before the first step must not dereference, validate or
3147
+ * return early on the payload; read it inside `context.run`.
3148
+ *
3149
+ * @see node_modules/@upstash/workflow/docs/basics/serve/advanced.mdx
2758
3150
  */
2759
3151
  requestPayload;
2760
3152
  /**
@@ -2767,7 +3159,7 @@ var WorkflowContext = class {
2767
3159
  * Can be set using the `env` option of serve:
2768
3160
  *
2769
3161
  * ```ts
2770
- * export const POST = serve<MyPayload>(
3162
+ * export const { POST } = serve<MyPayload>(
2771
3163
  * async (context) => {
2772
3164
  * const key = context.env["API_KEY"];
2773
3165
  * },
@@ -2815,6 +3207,46 @@ var WorkflowContext = class {
2815
3207
  * `1` on the first retry, `2` on the second, and so on.
2816
3208
  */
2817
3209
  retried;
3210
+ /**
3211
+ * Configuration QStash applied to the request being handled.
3212
+ *
3213
+ * This is the configuration of *this delivery*, not of the run: it is
3214
+ * the configuration the run was triggered with, except inside the
3215
+ * delivery which executes a step that has step-level settings, where
3216
+ * it is that step's settings. The fields below expose it; the executor
3217
+ * gets it directly rather than reaching through the context.
3218
+ */
3219
+ effectiveConfig;
3220
+ /**
3221
+ * Flow control QStash applied to the request being handled, if any.
3222
+ *
3223
+ * This is the flow control of the request in hand, which is the one the
3224
+ * run was triggered with except inside a step carrying its own.
3225
+ */
3226
+ get flowControl() {
3227
+ return this.effectiveConfig.flowControl;
3228
+ }
3229
+ /**
3230
+ * Retry limit QStash applied to the request being handled, if it
3231
+ * reported one.
3232
+ *
3233
+ * Not to be confused with {@link retried}, which is how many retries
3234
+ * have already happened.
3235
+ *
3236
+ * @see {@link flowControl} for what "the request being handled" means
3237
+ */
3238
+ get retries() {
3239
+ return this.effectiveConfig.retries;
3240
+ }
3241
+ /**
3242
+ * Retry delay expression QStash applied to the request being handled,
3243
+ * if any.
3244
+ *
3245
+ * @see {@link flowControl} for what "the request being handled" means
3246
+ */
3247
+ get retryDelay() {
3248
+ return this.effectiveConfig.retryDelay;
3249
+ }
2818
3250
  constructor({
2819
3251
  qstashClient,
2820
3252
  workflowRunId,
@@ -2828,7 +3260,8 @@ var WorkflowContext = class {
2828
3260
  invokeCount,
2829
3261
  label,
2830
3262
  retried,
2831
- middlewareManager
3263
+ middlewareManager,
3264
+ effectiveConfig
2832
3265
  }) {
2833
3266
  this.qstashClient = qstashClient;
2834
3267
  this.workflowRunId = workflowRunId;
@@ -2840,6 +3273,7 @@ var WorkflowContext = class {
2840
3273
  this.env = env ?? {};
2841
3274
  this.labels = label === void 0 ? [] : Array.isArray(label) ? label : label ? label.split(",") : [];
2842
3275
  this.retried = retried ?? 0;
3276
+ this.effectiveConfig = effectiveConfig ?? { hasStepConfig: false };
2843
3277
  const middlewareManagerInstance = middlewareManager ?? new MiddlewareManager([]);
2844
3278
  middlewareManagerInstance.assignContext(this);
2845
3279
  this.executor = new AutoExecutor(
@@ -2848,7 +3282,8 @@ var WorkflowContext = class {
2848
3282
  middlewareManagerInstance.dispatchDebug.bind(middlewareManagerInstance),
2849
3283
  middlewareManagerInstance.dispatchLifecycle.bind(middlewareManagerInstance),
2850
3284
  telemetry,
2851
- invokeCount
3285
+ invokeCount,
3286
+ this.effectiveConfig
2852
3287
  );
2853
3288
  }
2854
3289
  /**
@@ -2874,13 +3309,41 @@ var WorkflowContext = class {
2874
3309
  * ])
2875
3310
  * ```
2876
3311
  *
3312
+ * Step-level settings can be passed as a third argument, overriding
3313
+ * the settings the workflow run was triggered with for this step only:
3314
+ *
3315
+ * ```typescript
3316
+ * const result = await context.run(
3317
+ * "step 1",
3318
+ * () => {
3319
+ * return "result"
3320
+ * },
3321
+ * {
3322
+ * flowControl: { key: "custom-key", parallelism: 3 },
3323
+ * retries: 5,
3324
+ * }
3325
+ * )
3326
+ * ```
3327
+ *
3328
+ * Do not wrap steps in try/catch or `.catch` without rethrowing `WorkflowAbort`: each step
3329
+ * throws it to end the request. To stop retrying a failed step, throw
3330
+ * `WorkflowNonRetryableError`.
3331
+ *
2877
3332
  * @param stepName name of the step
2878
3333
  * @param stepFunction step function to be executed
3334
+ * @param stepSettings step-level settings for this step
2879
3335
  * @returns result of the step function
3336
+ * @see node_modules/@upstash/workflow/docs/steps/run.mdx
2880
3337
  */
2881
- async run(stepName, stepFunction) {
3338
+ async run(stepName, stepFunction, stepSettings) {
3339
+ const normalizedSettings = normalizeStepSettings(stepSettings);
3340
+ if (stepSettings) {
3341
+ validateFlowControl(stepSettings.flowControl);
3342
+ }
2882
3343
  const wrappedStepFunction = (() => this.executor.wrapStep(stepName, stepFunction));
2883
- return await this.addStep(new LazyFunctionStep(this, stepName, wrappedStepFunction));
3344
+ return await this.addStep(
3345
+ new LazyFunctionStep(this, stepName, wrappedStepFunction, normalizedSettings)
3346
+ );
2884
3347
  }
2885
3348
  /**
2886
3349
  * Stops the execution for the duration provided.
@@ -2890,8 +3353,9 @@ var WorkflowContext = class {
2890
3353
  * ```
2891
3354
  *
2892
3355
  * @param stepName
2893
- * @param duration sleep duration in seconds
3356
+ * @param duration sleep duration in seconds, or a duration string such as "10m"
2894
3357
  * @returns undefined
3358
+ * @see node_modules/@upstash/workflow/docs/steps/sleep.mdx
2895
3359
  */
2896
3360
  async sleep(stepName, duration) {
2897
3361
  await this.addStep(new LazySleepStep(this, stepName, duration));
@@ -2905,8 +3369,11 @@ var WorkflowContext = class {
2905
3369
  *
2906
3370
  * @param stepName
2907
3371
  * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
2908
- * as a Date object or a string (passed to `new Date(datetimeString)`)
3372
+ * as a Date object or a string (passed to `new Date(datetimeString)`).
3373
+ * A millisecond timestamp such as `Date.now()` is too far in the future, so QStash
3374
+ * rejects the step and the run fails. Pass `new Date(ms)` instead.
2909
3375
  * @returns undefined
3376
+ * @see node_modules/@upstash/workflow/docs/steps/sleepUntil.mdx
2910
3377
  */
2911
3378
  async sleepUntil(stepName, datetime) {
2912
3379
  let time;
@@ -2957,7 +3424,7 @@ var WorkflowContext = class {
2957
3424
  * Pauses workflow execution until a specific event occurs or a timeout is reached.
2958
3425
  *
2959
3426
  *```ts
2960
- * const result = await workflow.waitForEvent("payment-confirmed", "payment.confirmed", {
3427
+ * const result = await context.waitForEvent("payment-confirmed", "payment.confirmed", {
2961
3428
  * timeout: "5m"
2962
3429
  * });
2963
3430
  *```
@@ -2981,11 +3448,14 @@ var WorkflowContext = class {
2981
3448
  * Alternatively, you can use the `context.notify` method.
2982
3449
  *
2983
3450
  * @param stepName
2984
- * @param eventId - Unique identifier for the event to wait for
3451
+ * @param eventId - Unique identifier for the event to wait for. Only letters, digits,
3452
+ * "-", "_" and "." are allowed. QStash rejects other characters, such as ":", which
3453
+ * stops the run with only a "Tried to append to a cancelled workflow" warning.
2985
3454
  * @param options - Configuration options.
2986
3455
  * @returns `{ timeout: boolean, eventData: TEventData }`.
2987
3456
  * The `timeout` property specifies if the workflow has timed out. The `eventData`
2988
3457
  * is the data passed when notifying this workflow of an event.
3458
+ * @see node_modules/@upstash/workflow/docs/steps/waitForEvent.mdx
2989
3459
  */
2990
3460
  async waitForEvent(stepName, eventId, options = {}) {
2991
3461
  const { timeout = "7d" } = options;
@@ -3007,28 +3477,31 @@ var WorkflowContext = class {
3007
3477
  * will receive the given event data and resume execution.
3008
3478
  *
3009
3479
  * The response includes the same eventId and eventData. Additionally, there is
3010
- * a notifyResponse field which contains a list of `Waiter` objects, each corresponding
3011
- * to a notified workflow run.
3012
- *
3013
- * Optionally, you can pass a workflowRunId to enable lookback functionality:
3014
- *
3015
- * ```ts
3016
- * const { eventId, eventData, notifyResponse } = await context.notify(
3017
- * "notify step", "event-id", "event-data", "wfr_123"
3018
- * );
3019
- * ```
3480
+ * a notifyResponse field which contains a list of `NotifyResponse` objects, each corresponding
3481
+ * to a notified workflow run. The notified `Waiter` is under `notifyResponse[i].waiter`.
3020
3482
  *
3021
3483
  * @param stepName
3022
- * @param eventId event id to notify
3484
+ * @param eventId event id to notify. Only letters, digits, "-", "_" and "." are allowed.
3485
+ * QStash rejects other characters, such as ":", which stops the run with only a
3486
+ * "Tried to append to a cancelled workflow" warning.
3023
3487
  * @param eventData event data to notify with
3024
- * @param workflowRunId optional workflow run id for lookback support
3025
- * @returns notify response which has event id, event data and list of waiters which were notified
3488
+ * @param workflowRunId optional workflow run id for lookback: the event is kept for the run
3489
+ * even if it has not reached `waitForEvent` yet
3490
+ * @returns notify response which has event id, event data and list of waiters which were
3491
+ * notified. With `workflowRunId`, QStash returns `notifyResponse` as a single object instead
3492
+ * of an array, despite the type.
3493
+ * @see node_modules/@upstash/workflow/docs/steps/notify.mdx
3026
3494
  */
3027
3495
  async notify(stepName, eventId, eventData, workflowRunId) {
3028
3496
  return await this.addStep(
3029
3497
  new LazyNotifyStep(this, stepName, eventId, eventData, this.qstashClient.http, workflowRunId)
3030
3498
  );
3031
3499
  }
3500
+ /**
3501
+ * Starts another workflow run and waits for its result.
3502
+ *
3503
+ * @see node_modules/@upstash/workflow/docs/steps/invoke.mdx
3504
+ */
3032
3505
  async invoke(stepName, settings) {
3033
3506
  validateLabel(settings.label);
3034
3507
  validateFlowControl(settings.flowControl);
@@ -3036,9 +3509,15 @@ var WorkflowContext = class {
3036
3509
  new LazyInvokeStep(this, stepName, settings)
3037
3510
  );
3038
3511
  }
3512
+ /**
3513
+ * @see node_modules/@upstash/workflow/docs/steps/createWebhook.mdx
3514
+ */
3039
3515
  async createWebhook(stepName) {
3040
3516
  return await this.addStep(new LazyCreateWebhookStep(this, stepName));
3041
3517
  }
3518
+ /**
3519
+ * @see node_modules/@upstash/workflow/docs/steps/waitForWebhook.mdx
3520
+ */
3042
3521
  async waitForWebhook(stepName, webhook, timeout) {
3043
3522
  return await this.addStep(new LazyWaitForWebhookStep(this, stepName, webhook, timeout));
3044
3523
  }
@@ -3047,6 +3526,8 @@ var WorkflowContext = class {
3047
3526
  *
3048
3527
  * Will throw WorkflowCancelAbort to stop workflow execution.
3049
3528
  * Shouldn't be inside try/catch.
3529
+ *
3530
+ * @see node_modules/@upstash/workflow/docs/steps/cancel.mdx
3050
3531
  */
3051
3532
  async cancel() {
3052
3533
  throw new WorkflowCancelAbort();
@@ -3065,6 +3546,11 @@ var WorkflowContext = class {
3065
3546
  throw error;
3066
3547
  }
3067
3548
  }
3549
+ /**
3550
+ * Calls OpenAI, Anthropic or Resend through QStash, like `context.call`.
3551
+ *
3552
+ * @see node_modules/@upstash/workflow/docs/steps/api.mdx
3553
+ */
3068
3554
  get api() {
3069
3555
  return new WorkflowApi({
3070
3556
  context: this
@@ -3103,7 +3589,7 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
3103
3589
  *
3104
3590
  * @param routeFunction
3105
3591
  */
3106
- static async tryAuthentication(routeFunction, context) {
3592
+ static async tryAuthentication(routeFunction, context, effectiveConfig) {
3107
3593
  const disabledContext = new _DisabledWorkflowContext({
3108
3594
  qstashClient: new import_qstash10.Client({
3109
3595
  baseUrl: "disabled-client",
@@ -3118,7 +3604,10 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
3118
3604
  initialPayload: context.requestPayload,
3119
3605
  env: context.env,
3120
3606
  label: context.labels,
3121
- retried: context.retried
3607
+ retried: context.retried,
3608
+ // the route function runs for real here until it reaches a step, so
3609
+ // it observes the same configuration as it will on the real context
3610
+ effectiveConfig
3122
3611
  });
3123
3612
  try {
3124
3613
  await routeFunction(disabledContext);
@@ -3335,6 +3824,7 @@ var handleFailure = async ({
3335
3824
  }
3336
3825
  const userHeaders = recreateUserHeaders(request.headers);
3337
3826
  const retried = Number(request.headers.get(WORKFLOW_RETRIED_HEADER) ?? "0");
3827
+ const effectiveConfig = getEffectiveConfig(request.headers);
3338
3828
  const workflowContext = new WorkflowContext({
3339
3829
  qstashClient,
3340
3830
  workflowRunId,
@@ -3348,11 +3838,13 @@ var handleFailure = async ({
3348
3838
  label: userHeaders.get(WORKFLOW_LABEL_HEADER) ?? void 0,
3349
3839
  retried,
3350
3840
  workflowRunCreatedAt: workflowCreatedAt,
3351
- middlewareManager: void 0
3841
+ middlewareManager: void 0,
3842
+ effectiveConfig
3352
3843
  });
3353
3844
  const authCheck = await DisabledWorkflowContext.tryAuthentication(
3354
3845
  routeFunction,
3355
- workflowContext
3846
+ workflowContext,
3847
+ effectiveConfig
3356
3848
  );
3357
3849
  if (authCheck.isErr()) {
3358
3850
  await dispatchDebug?.("onError", {
@@ -3843,12 +4335,14 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
3843
4335
  const label = request.headers.get(WORKFLOW_LABEL_HEADER) ?? void 0;
3844
4336
  const workflowRunCreatedAtHeader = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
3845
4337
  const workflowRunCreatedAt = workflowRunCreatedAtHeader ? Number(workflowRunCreatedAtHeader) : isFirstInvocation ? Date.now() : 0;
4338
+ const effectiveConfig = getEffectiveConfig(request.headers);
3846
4339
  const workflowContext = new WorkflowContext({
3847
4340
  qstashClient: regionalClient,
3848
4341
  workflowRunId,
3849
4342
  initialPayload: isThirdPartyCallResult(request) ? JSON.parse(rawInitialPayload) : initialPayloadParser(rawInitialPayload),
3850
4343
  headers: recreateUserHeaders(request.headers),
3851
4344
  steps,
4345
+ effectiveConfig,
3852
4346
  url: workflowUrl,
3853
4347
  env,
3854
4348
  telemetry,
@@ -3860,7 +4354,8 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
3860
4354
  });
3861
4355
  const authCheck = await DisabledWorkflowContext.tryAuthentication(
3862
4356
  routeFunction,
3863
- workflowContext
4357
+ workflowContext,
4358
+ effectiveConfig
3864
4359
  );
3865
4360
  if (authCheck.isErr()) {
3866
4361
  throw authCheck.error;
@@ -3897,7 +4392,23 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
3897
4392
  if (steps.length === 1) {
3898
4393
  await middlewareManager.dispatchLifecycle("runStarted", {});
3899
4394
  }
3900
- return await routeFunction(workflowContext);
4395
+ let outcome;
4396
+ try {
4397
+ outcome = { ran: true, result: await routeFunction(workflowContext) };
4398
+ } catch (error) {
4399
+ outcome = { ran: false, error };
4400
+ }
4401
+ const submitted = await flushPendingStep(workflowContext);
4402
+ if (submitted.isErr()) {
4403
+ throw submitted.error;
4404
+ }
4405
+ if (submitted.value.result === "submitted-step") {
4406
+ throw submitted.value.abort;
4407
+ }
4408
+ if (!outcome.ran) {
4409
+ throw outcome.error;
4410
+ }
4411
+ return outcome.result;
3901
4412
  },
3902
4413
  onCleanup: async (result2) => {
3903
4414
  await middlewareManager.dispatchLifecycle("runCompleted", {