@upstash/workflow 1.4.0-rc → 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 +18 -2
  3. package/astro.d.ts +18 -2
  4. package/astro.js +129 -29
  5. package/astro.mjs +1 -1
  6. package/{chunk-UH6O5IJY.mjs → chunk-J3PXPHSB.mjs} +129 -29
  7. package/cloudflare.d.mts +16 -2
  8. package/cloudflare.d.ts +16 -2
  9. package/cloudflare.js +129 -29
  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 +18 -2
  136. package/express.d.ts +18 -2
  137. package/express.js +129 -29
  138. package/express.mjs +1 -1
  139. package/h3.d.mts +18 -2
  140. package/h3.d.ts +18 -2
  141. package/h3.js +129 -29
  142. package/h3.mjs +1 -1
  143. package/hono.d.mts +16 -2
  144. package/hono.d.ts +16 -2
  145. package/hono.js +129 -29
  146. package/hono.mjs +1 -1
  147. package/index.d.mts +49 -21
  148. package/index.d.ts +49 -21
  149. package/index.js +145 -41
  150. package/index.mjs +17 -13
  151. package/nextjs.d.mts +39 -2
  152. package/nextjs.d.ts +39 -2
  153. package/nextjs.js +129 -29
  154. package/nextjs.mjs +1 -1
  155. package/package.json +1 -1
  156. package/react-router.d.mts +15 -2
  157. package/react-router.d.ts +15 -2
  158. package/react-router.js +129 -29
  159. package/react-router.mjs +1 -1
  160. package/{serve-many-CbIV7145.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
  161. package/{serve-many-BCtZg31b.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
  162. package/solidjs.d.mts +9 -1
  163. package/solidjs.d.ts +9 -1
  164. package/solidjs.js +129 -29
  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 +16 -2
  215. package/svelte.d.ts +16 -2
  216. package/svelte.js +129 -29
  217. package/svelte.mjs +1 -1
  218. package/tanstack.d.mts +14 -2
  219. package/tanstack.d.ts +14 -2
  220. package/tanstack.js +129 -29
  221. package/tanstack.mjs +1 -1
  222. package/{types-ffLPVG5_.d.ts → types-CrgK5P6p.d.mts} +124 -24
  223. package/{types-ffLPVG5_.d.mts → types-CrgK5P6p.d.ts} +124 -24
@@ -914,6 +914,10 @@ var triggerFirstInvocation = async (params) => {
914
914
  workflowConfig: {
915
915
  workflowRunId: workflowContext.workflowRunId,
916
916
  workflowUrl: workflowContext.url,
917
+ // the run doesn't exist yet, so the trigger time is sent when the creation time
918
+ // is not known. serve and client.trigger set it on the context already, so a
919
+ // retry of this request carries the same value and is deduplicated.
920
+ workflowRunCreatedAt: workflowContext.workflowRunCreatedAt || Date.now(),
917
921
  failureUrl,
918
922
  retries,
919
923
  retryDelay,
@@ -1021,7 +1025,10 @@ var triggerWorkflowDelete = async (workflowContext, result, cancel = false, disp
1021
1025
  path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
1022
1026
  method: "DELETE",
1023
1027
  parseResponseAsJson: false,
1024
- body: JSON.stringify(result)
1028
+ body: JSON.stringify(result),
1029
+ // with the creation time, QStash deletes the run only if it is the same run.
1030
+ // a late delete of a previous run can't delete a new run with the same id.
1031
+ headers: workflowContext.workflowRunCreatedAt ? { [WORKFLOW_CREATED_AT_HEADER]: workflowContext.workflowRunCreatedAt.toString() } : void 0
1025
1032
  });
1026
1033
  await dispatchDebug?.("onInfo", {
1027
1034
  info: `Workflow run ${workflowContext.workflowRunId} deleted from QStash successfully.`
@@ -1098,6 +1105,7 @@ ${atob(callbackMessage.body ?? "")}`
1098
1105
  const concurrentString = request.headers.get("Upstash-Workflow-Concurrent");
1099
1106
  const contentType = request.headers.get("Upstash-Workflow-ContentType");
1100
1107
  const invokeCount = request.headers.get(WORKFLOW_INVOKE_COUNT_HEADER);
1108
+ const workflowRunCreatedAt = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
1101
1109
  if (!(workflowRunId && stepIdString && stepName && StepTypes.includes(stepType) && concurrentString && contentType)) {
1102
1110
  throw new Error(
1103
1111
  `Missing info in callback message source header: ${JSON.stringify({
@@ -1115,6 +1123,7 @@ ${atob(callbackMessage.body ?? "")}`
1115
1123
  workflowConfig: {
1116
1124
  workflowRunId,
1117
1125
  workflowUrl,
1126
+ workflowRunCreatedAt: Number(workflowRunCreatedAt ?? "0"),
1118
1127
  telemetry
1119
1128
  },
1120
1129
  invokeCount: Number(invokeCount)
@@ -1289,6 +1298,7 @@ var BaseLazyStep = class _BaseLazyStep {
1289
1298
  workflowConfig: {
1290
1299
  workflowRunId: context.workflowRunId,
1291
1300
  workflowUrl: context.url,
1301
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
1292
1302
  useJSONContent: false,
1293
1303
  telemetry
1294
1304
  },
@@ -1620,6 +1630,8 @@ var LazyWaitEventStep = class extends BaseLazyStep {
1620
1630
  ) : {},
1621
1631
  // note: using WORKFLOW_ID_HEADER doesn't work, because Runid -> RunId:
1622
1632
  "Upstash-Workflow-Runid": [context.workflowRunId],
1633
+ // same for WORKFLOW_CREATED_AT_HEADER, because Createdat -> CreatedAt:
1634
+ ...context.workflowRunCreatedAt ? { "Upstash-Workflow-Createdat": [context.workflowRunCreatedAt.toString()] } : {},
1623
1635
  [WORKFLOW_INIT_HEADER]: ["false"],
1624
1636
  [WORKFLOW_URL_HEADER]: [context.url],
1625
1637
  "Upstash-Workflow-CallType": ["step"]
@@ -1722,6 +1734,7 @@ var LazyInvokeStep = class extends BaseLazyStep {
1722
1734
  workflowConfig: {
1723
1735
  workflowRunId: context.workflowRunId,
1724
1736
  workflowUrl: context.url,
1737
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
1725
1738
  telemetry,
1726
1739
  useJSONContent: false
1727
1740
  },
@@ -1731,6 +1744,9 @@ var LazyInvokeStep = class extends BaseLazyStep {
1731
1744
  invokerHeaders[key] = value;
1732
1745
  });
1733
1746
  invokerHeaders["Upstash-Workflow-Runid"] = context.workflowRunId;
1747
+ if (context.workflowRunCreatedAt) {
1748
+ invokerHeaders["Upstash-Workflow-Createdat"] = context.workflowRunCreatedAt.toString();
1749
+ }
1734
1750
  const request = {
1735
1751
  body: stringifyBody(this.params.body),
1736
1752
  headers: Object.fromEntries(
@@ -1759,6 +1775,9 @@ var LazyInvokeStep = class extends BaseLazyStep {
1759
1775
  workflowConfig: {
1760
1776
  workflowRunId: getWorkflowRunId(workflowRunId),
1761
1777
  workflowUrl: newUrl,
1778
+ // the invoked run doesn't exist yet, so the creation time of the invoker run is sent.
1779
+ // it separates the invocations made by different runs of the invoker.
1780
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
1762
1781
  retries,
1763
1782
  retryDelay,
1764
1783
  telemetry,
@@ -1928,6 +1947,9 @@ var WorkflowHeaders = class {
1928
1947
  [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
1929
1948
  ...this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {}
1930
1949
  };
1950
+ if (this.workflowConfig.workflowRunCreatedAt) {
1951
+ this.headers.rawHeaders[WORKFLOW_CREATED_AT_HEADER] = this.workflowConfig.workflowRunCreatedAt.toString();
1952
+ }
1931
1953
  if (this.stepInfo?.lazyStep.stepType !== "Call") {
1932
1954
  this.headers.rawHeaders[`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`] = WORKFLOW_PROTOCOL_VERSION;
1933
1955
  }
@@ -2126,6 +2148,7 @@ var submitParallelSteps = async ({
2126
2148
  workflowConfig: {
2127
2149
  workflowRunId: context.workflowRunId,
2128
2150
  workflowUrl: context.url,
2151
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
2129
2152
  telemetry
2130
2153
  },
2131
2154
  invokeCount,
@@ -2216,6 +2239,7 @@ var publishStepConfigRequest = async ({
2216
2239
  initHeaderValue: "false",
2217
2240
  workflowConfig: {
2218
2241
  workflowRunId: context.workflowRunId,
2242
+ workflowRunCreatedAt: context.workflowRunCreatedAt,
2219
2243
  workflowUrl: context.url,
2220
2244
  telemetry
2221
2245
  },
@@ -2228,7 +2252,9 @@ var publishStepConfigRequest = async ({
2228
2252
  const result = await context.qstashClient.publishJSON({
2229
2253
  headers: {
2230
2254
  ...headers,
2231
- "Upstash-Workflow-CallType": WORKFLOW_STEP_CONFIG_CALL_TYPE
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
2232
2258
  },
2233
2259
  method: "POST",
2234
2260
  body: { targetStep, invokeCount },
@@ -2247,6 +2273,19 @@ var publishStepConfigRequest = async ({
2247
2273
  };
2248
2274
 
2249
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
+ };
2250
2289
  var DEFAULT_PARALLELISM = 0;
2251
2290
  var DEFAULT_RATE = 0;
2252
2291
  var DEFAULT_PERIOD_SECONDS = 1;
@@ -2510,10 +2549,18 @@ var AutoExecutor = class _AutoExecutor {
2510
2549
  dispatchLifecycle: this.dispatchLifecycle
2511
2550
  });
2512
2551
  if (lazyStep.supportsDeferredSubmission) {
2513
- this.pendingStep = { status: "held", lazyStep, resultStep };
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
+ };
2514
2561
  return lazyStep.parseOut({
2515
2562
  ...resultStep,
2516
- out: resultStep.out === void 0 ? void 0 : JSON.stringify(resultStep.out)
2563
+ out: serializedOut
2517
2564
  });
2518
2565
  }
2519
2566
  await submitStepResult({
@@ -2858,6 +2905,11 @@ var BaseWorkflowApi = class {
2858
2905
 
2859
2906
  // src/context/api/anthropic.ts
2860
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
+ */
2861
2913
  async call(stepName, settings) {
2862
2914
  const { token, operation, ...parameters } = settings;
2863
2915
  return await this.callApi(stepName, {
@@ -2873,6 +2925,11 @@ var AnthropicAPI = class extends BaseWorkflowApi {
2873
2925
  // src/context/api/openai.ts
2874
2926
  import { custom, openai } from "@upstash/qstash";
2875
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
+ */
2876
2933
  async call(stepName, settings) {
2877
2934
  const { token, organization, operation, baseURL, ...parameters } = settings;
2878
2935
  const useOpenAI = baseURL === void 0;
@@ -2890,6 +2947,11 @@ var OpenAIAPI = class extends BaseWorkflowApi {
2890
2947
  // src/context/api/resend.ts
2891
2948
  import { resend } from "@upstash/qstash";
2892
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
+ */
2893
2955
  async call(stepName, settings) {
2894
2956
  const { token, batch = false, ...parameters } = settings;
2895
2957
  return await this.callApi(stepName, {
@@ -3056,8 +3118,9 @@ var WorkflowContext = class {
3056
3118
  *
3057
3119
  * ```ts
3058
3120
  * import { Client } from "@upstash/qstash"
3121
+ * import { serve } from "@upstash/workflow/nextjs"
3059
3122
  *
3060
- * export const POST = serve(
3123
+ * export const { POST } = serve(
3061
3124
  * async (context) => {
3062
3125
  * ...
3063
3126
  * },
@@ -3082,7 +3145,7 @@ var WorkflowContext = class {
3082
3145
  * Can be overwritten by passing a `url` parameter in `serve`:
3083
3146
  *
3084
3147
  * ```ts
3085
- * export const POST = serve(
3148
+ * export const { POST } = serve(
3086
3149
  * async (context) => {
3087
3150
  * ...
3088
3151
  * },
@@ -3100,7 +3163,7 @@ var WorkflowContext = class {
3100
3163
  *
3101
3164
  * ```ts
3102
3165
  * // set requestPayload type to MyPayload:
3103
- * export const POST = serve<MyPayload>(
3166
+ * export const { POST } = serve<MyPayload>(
3104
3167
  * async (context) => {
3105
3168
  * ...
3106
3169
  * }
@@ -3112,7 +3175,7 @@ var WorkflowContext = class {
3112
3175
  * the `initialPayloadParser` parameter:
3113
3176
  *
3114
3177
  * ```ts
3115
- * export const POST = serve<MyPayload>(
3178
+ * export const { POST } = serve<MyPayload>(
3116
3179
  * async (context) => {
3117
3180
  * ...
3118
3181
  * },
@@ -3121,6 +3184,13 @@ var WorkflowContext = class {
3121
3184
  * }
3122
3185
  * )
3123
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
3124
3194
  */
3125
3195
  requestPayload;
3126
3196
  /**
@@ -3133,7 +3203,7 @@ var WorkflowContext = class {
3133
3203
  * Can be set using the `env` option of serve:
3134
3204
  *
3135
3205
  * ```ts
3136
- * export const POST = serve<MyPayload>(
3206
+ * export const { POST } = serve<MyPayload>(
3137
3207
  * async (context) => {
3138
3208
  * const key = context.env["API_KEY"];
3139
3209
  * },
@@ -3299,18 +3369,24 @@ var WorkflowContext = class {
3299
3369
  * )
3300
3370
  * ```
3301
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
+ *
3302
3376
  * @param stepName name of the step
3303
3377
  * @param stepFunction step function to be executed
3304
3378
  * @param stepSettings step-level settings for this step
3305
3379
  * @returns result of the step function
3380
+ * @see node_modules/@upstash/workflow/docs/steps/run.mdx
3306
3381
  */
3307
3382
  async run(stepName, stepFunction, stepSettings) {
3383
+ const normalizedSettings = normalizeStepSettings(stepSettings);
3308
3384
  if (stepSettings) {
3309
3385
  validateFlowControl(stepSettings.flowControl);
3310
3386
  }
3311
3387
  const wrappedStepFunction = (() => this.executor.wrapStep(stepName, stepFunction));
3312
3388
  return await this.addStep(
3313
- new LazyFunctionStep(this, stepName, wrappedStepFunction, stepSettings)
3389
+ new LazyFunctionStep(this, stepName, wrappedStepFunction, normalizedSettings)
3314
3390
  );
3315
3391
  }
3316
3392
  /**
@@ -3321,8 +3397,9 @@ var WorkflowContext = class {
3321
3397
  * ```
3322
3398
  *
3323
3399
  * @param stepName
3324
- * @param duration sleep duration in seconds
3400
+ * @param duration sleep duration in seconds, or a duration string such as "10m"
3325
3401
  * @returns undefined
3402
+ * @see node_modules/@upstash/workflow/docs/steps/sleep.mdx
3326
3403
  */
3327
3404
  async sleep(stepName, duration) {
3328
3405
  await this.addStep(new LazySleepStep(this, stepName, duration));
@@ -3336,8 +3413,11 @@ var WorkflowContext = class {
3336
3413
  *
3337
3414
  * @param stepName
3338
3415
  * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
3339
- * 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.
3340
3419
  * @returns undefined
3420
+ * @see node_modules/@upstash/workflow/docs/steps/sleepUntil.mdx
3341
3421
  */
3342
3422
  async sleepUntil(stepName, datetime) {
3343
3423
  let time;
@@ -3388,7 +3468,7 @@ var WorkflowContext = class {
3388
3468
  * Pauses workflow execution until a specific event occurs or a timeout is reached.
3389
3469
  *
3390
3470
  *```ts
3391
- * const result = await workflow.waitForEvent("payment-confirmed", "payment.confirmed", {
3471
+ * const result = await context.waitForEvent("payment-confirmed", "payment.confirmed", {
3392
3472
  * timeout: "5m"
3393
3473
  * });
3394
3474
  *```
@@ -3412,11 +3492,14 @@ var WorkflowContext = class {
3412
3492
  * Alternatively, you can use the `context.notify` method.
3413
3493
  *
3414
3494
  * @param stepName
3415
- * @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.
3416
3498
  * @param options - Configuration options.
3417
3499
  * @returns `{ timeout: boolean, eventData: TEventData }`.
3418
3500
  * The `timeout` property specifies if the workflow has timed out. The `eventData`
3419
3501
  * is the data passed when notifying this workflow of an event.
3502
+ * @see node_modules/@upstash/workflow/docs/steps/waitForEvent.mdx
3420
3503
  */
3421
3504
  async waitForEvent(stepName, eventId, options = {}) {
3422
3505
  const { timeout = "7d" } = options;
@@ -3438,28 +3521,31 @@ var WorkflowContext = class {
3438
3521
  * will receive the given event data and resume execution.
3439
3522
  *
3440
3523
  * The response includes the same eventId and eventData. Additionally, there is
3441
- * a notifyResponse field which contains a list of `Waiter` objects, each corresponding
3442
- * to a notified workflow run.
3443
- *
3444
- * Optionally, you can pass a workflowRunId to enable lookback functionality:
3445
- *
3446
- * ```ts
3447
- * const { eventId, eventData, notifyResponse } = await context.notify(
3448
- * "notify step", "event-id", "event-data", "wfr_123"
3449
- * );
3450
- * ```
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`.
3451
3526
  *
3452
3527
  * @param stepName
3453
- * @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.
3454
3531
  * @param eventData event data to notify with
3455
- * @param workflowRunId optional workflow run id for lookback support
3456
- * @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
3457
3538
  */
3458
3539
  async notify(stepName, eventId, eventData, workflowRunId) {
3459
3540
  return await this.addStep(
3460
3541
  new LazyNotifyStep(this, stepName, eventId, eventData, this.qstashClient.http, workflowRunId)
3461
3542
  );
3462
3543
  }
3544
+ /**
3545
+ * Starts another workflow run and waits for its result.
3546
+ *
3547
+ * @see node_modules/@upstash/workflow/docs/steps/invoke.mdx
3548
+ */
3463
3549
  async invoke(stepName, settings) {
3464
3550
  validateLabel(settings.label);
3465
3551
  validateFlowControl(settings.flowControl);
@@ -3467,9 +3553,15 @@ var WorkflowContext = class {
3467
3553
  new LazyInvokeStep(this, stepName, settings)
3468
3554
  );
3469
3555
  }
3556
+ /**
3557
+ * @see node_modules/@upstash/workflow/docs/steps/createWebhook.mdx
3558
+ */
3470
3559
  async createWebhook(stepName) {
3471
3560
  return await this.addStep(new LazyCreateWebhookStep(this, stepName));
3472
3561
  }
3562
+ /**
3563
+ * @see node_modules/@upstash/workflow/docs/steps/waitForWebhook.mdx
3564
+ */
3473
3565
  async waitForWebhook(stepName, webhook, timeout) {
3474
3566
  return await this.addStep(new LazyWaitForWebhookStep(this, stepName, webhook, timeout));
3475
3567
  }
@@ -3478,6 +3570,8 @@ var WorkflowContext = class {
3478
3570
  *
3479
3571
  * Will throw WorkflowCancelAbort to stop workflow execution.
3480
3572
  * Shouldn't be inside try/catch.
3573
+ *
3574
+ * @see node_modules/@upstash/workflow/docs/steps/cancel.mdx
3481
3575
  */
3482
3576
  async cancel() {
3483
3577
  throw new WorkflowCancelAbort();
@@ -3496,6 +3590,11 @@ var WorkflowContext = class {
3496
3590
  throw error;
3497
3591
  }
3498
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
+ */
3499
3598
  get api() {
3500
3599
  return new WorkflowApi({
3501
3600
  context: this
@@ -4281,7 +4380,8 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
4281
4380
  const invokeCount = Number(request.headers.get(WORKFLOW_INVOKE_COUNT_HEADER) ?? "0");
4282
4381
  const retried = Number(request.headers.get(WORKFLOW_RETRIED_HEADER) ?? "0");
4283
4382
  const label = request.headers.get(WORKFLOW_LABEL_HEADER) ?? void 0;
4284
- const workflowRunCreatedAt = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
4383
+ const workflowRunCreatedAtHeader = request.headers.get(WORKFLOW_CREATED_AT_HEADER);
4384
+ const workflowRunCreatedAt = workflowRunCreatedAtHeader ? Number(workflowRunCreatedAtHeader) : isFirstInvocation ? Date.now() : 0;
4285
4385
  const effectiveConfig = getEffectiveConfig(request.headers);
4286
4386
  const workflowContext = new WorkflowContext({
4287
4387
  qstashClient: regionalClient,
@@ -4296,7 +4396,7 @@ var serveBase = (routeFunction, telemetry, options, internalOptions) => {
4296
4396
  invokeCount,
4297
4397
  label,
4298
4398
  retried,
4299
- workflowRunCreatedAt: Number(workflowRunCreatedAt),
4399
+ workflowRunCreatedAt,
4300
4400
  middlewareManager
4301
4401
  });
4302
4402
  const authCheck = await DisabledWorkflowContext.tryAuthentication(
package/cloudflare.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as RouteFunction, d as WorkflowServeOptions, I as InvokableWorkflow } from './types-ffLPVG5_.mjs';
2
- import { s as serveManyBase } from './serve-many-CbIV7145.mjs';
1
+ import { c as RouteFunction, d as WorkflowServeOptions, I as InvokableWorkflow } from './types-CrgK5P6p.mjs';
2
+ import { s as serveManyBase } from './serve-many-BKukvLNl.mjs';
3
3
  import '@upstash/qstash';
4
4
  import 'zod';
5
5
  import 'neverthrow';
@@ -27,14 +27,28 @@ type WorkersHandlerArgs = [Request, Record<string, string | undefined>];
27
27
  *
28
28
  * See for options https://upstash.com/docs/qstash/workflows/basics/serve
29
29
  *
30
+ * Code outside steps runs again on every request of the run. Anything it branches on or
31
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
32
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
33
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
34
+ * result.
35
+ *
30
36
  * @param routeFunction workflow function
31
37
  * @param options workflow options
32
38
  * @returns
39
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
40
+ * @see node_modules/@upstash/workflow/docs/quickstarts/cloudflare-workers.mdx
33
41
  */
34
42
  declare const serve: <TInitialPayload = unknown, TResult = unknown>(routeFunction: RouteFunction<TInitialPayload, TResult>, options?: WorkflowServeOptions<TInitialPayload, TResult>) => {
35
43
  fetch: (...args: PagesHandlerArgs | WorkersHandlerArgs) => Promise<Response>;
36
44
  };
45
+ /**
46
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
47
+ */
37
48
  declare const createWorkflow: <TInitialPayload, TResult>(...params: Parameters<typeof serve<TInitialPayload, TResult>>) => InvokableWorkflow<TInitialPayload, TResult>;
49
+ /**
50
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
51
+ */
38
52
  declare const serveMany: (workflows: Parameters<typeof serveManyBase>[0]["workflows"], options?: Parameters<typeof serveManyBase>[0]["options"]) => {
39
53
  fetch: (...params: PagesHandlerArgs | WorkersHandlerArgs) => Promise<any>;
40
54
  };
package/cloudflare.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as RouteFunction, d as WorkflowServeOptions, I as InvokableWorkflow } from './types-ffLPVG5_.js';
2
- import { s as serveManyBase } from './serve-many-BCtZg31b.js';
1
+ import { c as RouteFunction, d as WorkflowServeOptions, I as InvokableWorkflow } from './types-CrgK5P6p.js';
2
+ import { s as serveManyBase } from './serve-many-CrLKQpuZ.js';
3
3
  import '@upstash/qstash';
4
4
  import 'zod';
5
5
  import 'neverthrow';
@@ -27,14 +27,28 @@ type WorkersHandlerArgs = [Request, Record<string, string | undefined>];
27
27
  *
28
28
  * See for options https://upstash.com/docs/qstash/workflows/basics/serve
29
29
  *
30
+ * Code outside steps runs again on every request of the run. Anything it branches on or
31
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
32
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
33
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
34
+ * result.
35
+ *
30
36
  * @param routeFunction workflow function
31
37
  * @param options workflow options
32
38
  * @returns
39
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
40
+ * @see node_modules/@upstash/workflow/docs/quickstarts/cloudflare-workers.mdx
33
41
  */
34
42
  declare const serve: <TInitialPayload = unknown, TResult = unknown>(routeFunction: RouteFunction<TInitialPayload, TResult>, options?: WorkflowServeOptions<TInitialPayload, TResult>) => {
35
43
  fetch: (...args: PagesHandlerArgs | WorkersHandlerArgs) => Promise<Response>;
36
44
  };
45
+ /**
46
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
47
+ */
37
48
  declare const createWorkflow: <TInitialPayload, TResult>(...params: Parameters<typeof serve<TInitialPayload, TResult>>) => InvokableWorkflow<TInitialPayload, TResult>;
49
+ /**
50
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
51
+ */
38
52
  declare const serveMany: (workflows: Parameters<typeof serveManyBase>[0]["workflows"], options?: Parameters<typeof serveManyBase>[0]["options"]) => {
39
53
  fetch: (...params: PagesHandlerArgs | WorkersHandlerArgs) => Promise<any>;
40
54
  };