@upstash/workflow 1.4.0 → 1.5.1-canary.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 +375 -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 +575 -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 +114 -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 +2946 -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/solidjs.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  SDK_TELEMETRY,
3
3
  serveBase
4
- } from "./chunk-DRHEHWMS.mjs";
4
+ } from "./chunk-J3PXPHSB.mjs";
5
5
 
6
6
  // platforms/solidjs.ts
7
7
  import { startDevServer } from "@upstash/qstash";
@@ -0,0 +1,84 @@
1
+ import type { APIContext, APIRoute } from "astro";
2
+
3
+ import { InvokableWorkflow, WorkflowServeOptions, Telemetry, WorkflowContext } from "../src";
4
+ import { serveBase } from "../src/serve";
5
+ import { SDK_TELEMETRY } from "../src/constants";
6
+ import { serveManyBase } from "../src/serve/serve-many";
7
+ import { startDevServer } from "@upstash/qstash";
8
+
9
+ const telemetry: Telemetry = {
10
+ sdk: SDK_TELEMETRY,
11
+ framework: "astro",
12
+ runtime: process.versions.bun
13
+ ? `bun@${process.versions.bun}/node@${process.version}`
14
+ : `node@${process.version}`,
15
+ };
16
+
17
+ /**
18
+ * Code outside steps runs again on every request of the run. Anything it branches on or
19
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
20
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
21
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
22
+ * result.
23
+ *
24
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
25
+ * @see node_modules/@upstash/workflow/docs/quickstarts/astro.mdx
26
+ */
27
+ export function serve<TInitialPayload = unknown, TResult = unknown>(
28
+ routeFunction: (
29
+ workflowContext: WorkflowContext<TInitialPayload>,
30
+ apiContext: APIContext
31
+ ) => Promise<TResult>,
32
+ options?: WorkflowServeOptions<TInitialPayload, TResult>
33
+ ) {
34
+ void startDevServer();
35
+
36
+ const POST: APIRoute = (apiContext) => {
37
+ const { handler } = serveBase<TInitialPayload, Request, Response, TResult>(
38
+ (workflowContext) => routeFunction(workflowContext, apiContext),
39
+ telemetry,
40
+ options
41
+ );
42
+
43
+ return handler(apiContext.request);
44
+ };
45
+
46
+ return { POST };
47
+ }
48
+
49
+ /**
50
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
51
+ */
52
+ export const createWorkflow = <TInitialPayload, TResult>(
53
+ ...params: Parameters<typeof serve<TInitialPayload, TResult>>
54
+ ): InvokableWorkflow<TInitialPayload, TResult> => {
55
+ const [routeFunction, options = {}] = params;
56
+ return {
57
+ workflowId: undefined,
58
+ // @ts-expect-error because astro route function has another parameter,
59
+ // the RouteFunction type can't cover this. We need to make RouteFunction
60
+ // accept more variables than simply the context. Until then, ignoring the
61
+ // error here. Tested the usage in astro project and it's fine. TODO.
62
+ routeFunction,
63
+ options,
64
+ };
65
+ };
66
+
67
+ /**
68
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
69
+ */
70
+ export const serveMany = (
71
+ workflows: Parameters<typeof serveManyBase>[0]["workflows"],
72
+ options?: Parameters<typeof serveManyBase>[0]["options"]
73
+ ) => {
74
+ return {
75
+ POST: serveManyBase<ReturnType<typeof serve>["POST"]>({
76
+ workflows: workflows,
77
+ getUrl(...params) {
78
+ return params[0].request.url;
79
+ },
80
+ serveMethod: (...params: Parameters<typeof serve>) => serve(...params).POST,
81
+ options,
82
+ }).handler,
83
+ };
84
+ };
@@ -0,0 +1,127 @@
1
+ import type { InvokableWorkflow, WorkflowServeOptions, RouteFunction, Telemetry } from "../src";
2
+ import { SDK_TELEMETRY } from "../src/constants";
3
+ import { serveBase } from "../src/serve";
4
+ import { serveManyBase } from "../src/serve/serve-many";
5
+ import { startDevServer } from "@upstash/qstash";
6
+
7
+ export type WorkflowBindings = {
8
+ QSTASH_TOKEN: string;
9
+ QSTASH_URL?: string;
10
+ QSTASH_CURRENT_SIGNING_KEY?: string;
11
+ QSTASH_NEXT_SIGNING_KEY?: string;
12
+ UPSTASH_WORKFLOW_URL?: string;
13
+ };
14
+
15
+ /**
16
+ * Cloudflare Pages Function arguments
17
+ */
18
+ export type PagesHandlerArgs = [{ request: Request; env: Record<string, string | undefined> }];
19
+
20
+ /**
21
+ * Cloudflare Worker arguments
22
+ */
23
+ export type WorkersHandlerArgs = [Request, Record<string, string | undefined>];
24
+
25
+ /**
26
+ * Support both Cloudflare Pages Functions and Cloudflare Workers
27
+ */
28
+ const getArgs = (
29
+ args: PagesHandlerArgs | WorkersHandlerArgs
30
+ ): { request: Request; env: Record<string, string | undefined> } => {
31
+ // @ts-expect-error types of args don't allow length 0, but want to sanity check
32
+ if (!Array.isArray(args) || args.length === 0) {
33
+ throw new Error("No arguments passed to serve handler");
34
+ }
35
+
36
+ if (typeof args[0] === "object" && "request" in args[0] && "env" in args[0]) {
37
+ return {
38
+ request: args[0].request,
39
+ env: args[0].env,
40
+ };
41
+ }
42
+
43
+ if (args.length > 1 && typeof args[1] === "object") {
44
+ return {
45
+ request: args[0],
46
+ env: args[1],
47
+ };
48
+ }
49
+
50
+ throw new Error("Could not derive handler arguments from input. Please check how serve is used.");
51
+ };
52
+
53
+ const telemetry: Telemetry = {
54
+ sdk: SDK_TELEMETRY,
55
+ framework: "cloudflare",
56
+ };
57
+
58
+ /**
59
+ * Serve method to serve a Upstash Workflow in a Cloudflare project
60
+ *
61
+ * See for options https://upstash.com/docs/qstash/workflows/basics/serve
62
+ *
63
+ * Code outside steps runs again on every request of the run. Anything it branches on or
64
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
65
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
66
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
67
+ * result.
68
+ *
69
+ * @param routeFunction workflow function
70
+ * @param options workflow options
71
+ * @returns
72
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
73
+ * @see node_modules/@upstash/workflow/docs/quickstarts/cloudflare-workers.mdx
74
+ */
75
+ export const serve = <TInitialPayload = unknown, TResult = unknown>(
76
+ routeFunction: RouteFunction<TInitialPayload, TResult>,
77
+ options?: WorkflowServeOptions<TInitialPayload, TResult>
78
+ ): {
79
+ fetch: (...args: PagesHandlerArgs | WorkersHandlerArgs) => Promise<Response>;
80
+ } => {
81
+ void startDevServer();
82
+
83
+ const fetch = async (...args: PagesHandlerArgs | WorkersHandlerArgs) => {
84
+ const { request, env } = getArgs(args);
85
+ const { handler: serveHandler } = serveBase(routeFunction, telemetry, {
86
+ env,
87
+ ...options,
88
+ });
89
+ return await serveHandler(request);
90
+ };
91
+
92
+ return { fetch };
93
+ };
94
+
95
+ /**
96
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
97
+ */
98
+ export const createWorkflow = <TInitialPayload, TResult>(
99
+ ...params: Parameters<typeof serve<TInitialPayload, TResult>>
100
+ ): InvokableWorkflow<TInitialPayload, TResult> => {
101
+ const [routeFunction, options = {}] = params;
102
+ return {
103
+ workflowId: undefined,
104
+ routeFunction,
105
+ options,
106
+ };
107
+ };
108
+
109
+ /**
110
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
111
+ */
112
+ export const serveMany = (
113
+ workflows: Parameters<typeof serveManyBase>[0]["workflows"],
114
+ options?: Parameters<typeof serveManyBase>[0]["options"]
115
+ ) => {
116
+ return {
117
+ fetch: serveManyBase<ReturnType<typeof serve>["fetch"]>({
118
+ workflows: workflows,
119
+ getUrl(...params) {
120
+ const { request } = getArgs(params);
121
+ return request.url;
122
+ },
123
+ options,
124
+ serveMethod: (...params: Parameters<typeof serve>) => serve(...params).fetch,
125
+ }).handler,
126
+ };
127
+ };
@@ -0,0 +1,147 @@
1
+ import type { WorkflowServeOptions, RouteFunction, Telemetry, InvokableWorkflow } from "../src";
2
+ import { SDK_TELEMETRY } from "../src/constants";
3
+ import { serveBase } from "../src/serve";
4
+ import {
5
+ Request as ExpressRequest,
6
+ Response as ExpressResponse,
7
+ Router,
8
+ RequestHandler,
9
+ } from "express";
10
+ import { serveManyBase } from "../src/serve/serve-many";
11
+ import { startDevServer } from "@upstash/qstash";
12
+
13
+ const isEmptyRequest = (req: ExpressRequest) => {
14
+ return (
15
+ req.headers["content-type"] === "application/json" && req.headers["content-length"] === "0"
16
+ );
17
+ };
18
+
19
+ const telemetry: Telemetry = {
20
+ sdk: SDK_TELEMETRY,
21
+ framework: "express",
22
+ runtime: process.versions.bun
23
+ ? `bun@${process.versions.bun}/node@${process.version}`
24
+ : `node@${process.version}`,
25
+ };
26
+
27
+ function createExpressHandler<TInitialPayload = unknown, TResult = unknown>(
28
+ params: Parameters<typeof serve<TInitialPayload, TResult>>
29
+ ): RequestHandler {
30
+ const [routeFunction, options] = params;
31
+ return async (request_: ExpressRequest, res: ExpressResponse) => {
32
+ // only allow POST requests
33
+ if (request_.method.toUpperCase() !== "POST") {
34
+ res.status(405).json("Only POST requests are allowed in workflows");
35
+ return;
36
+ }
37
+
38
+ let requestBody: string;
39
+ if (isEmptyRequest(request_)) {
40
+ requestBody = "";
41
+ } else if (request_.headers["content-type"]?.includes("text/plain")) {
42
+ requestBody = request_.body;
43
+ } else if (request_.headers["content-type"]?.includes("application/json")) {
44
+ requestBody = JSON.stringify(request_.body);
45
+ } else {
46
+ requestBody =
47
+ typeof request_.body === "string" ? request_.body : JSON.stringify(request_.body);
48
+ }
49
+
50
+ // create Request
51
+ const protocol = request_.protocol;
52
+ const host = request_.get("host") || "localhost";
53
+ const url = `${protocol}://${host}${request_.originalUrl}`;
54
+
55
+ const webRequest = new Request(url, {
56
+ method: request_.method,
57
+ headers: new Headers(request_.headers as Record<string, string>),
58
+ body: requestBody,
59
+ });
60
+
61
+ // create handler
62
+ const { handler: serveHandler } = serveBase<TInitialPayload, Request, Response, TResult>(
63
+ routeFunction,
64
+ telemetry,
65
+ options,
66
+ {
67
+ useJSONContent: true,
68
+ }
69
+ );
70
+
71
+ const response = await serveHandler(webRequest);
72
+
73
+ // set headers
74
+ for (const [key, value] of response.headers.entries()) {
75
+ res.setHeader(key, value);
76
+ }
77
+
78
+ const responseData = await response.json();
79
+ res.status(response.status).json(responseData);
80
+ };
81
+ }
82
+
83
+ /**
84
+ * Code outside steps runs again on every request of the run. Anything it branches on or
85
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
86
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
87
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
88
+ * result.
89
+ *
90
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
91
+ * @see node_modules/@upstash/workflow/docs/quickstarts/express.mdx
92
+ */
93
+ export function serve<TInitialPayload = unknown, TResult = unknown>(
94
+ routeFunction: RouteFunction<TInitialPayload, TResult>,
95
+ options?: WorkflowServeOptions<TInitialPayload, TResult>
96
+ ): Router {
97
+ void startDevServer();
98
+
99
+ const router = Router();
100
+
101
+ const handler: RequestHandler = createExpressHandler([routeFunction, options]);
102
+
103
+ router.all(/(.*)/, handler);
104
+
105
+ return router;
106
+ }
107
+
108
+ /**
109
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
110
+ */
111
+ export const createWorkflow = <TInitialPayload, TResult>(
112
+ ...params: Parameters<typeof serve<TInitialPayload, TResult>>
113
+ ): InvokableWorkflow<TInitialPayload, TResult> => {
114
+ const [routeFunction, options = {}] = params;
115
+ return {
116
+ routeFunction,
117
+ options,
118
+ workflowId: undefined,
119
+ useJSONContent: true,
120
+ };
121
+ };
122
+
123
+ /**
124
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
125
+ */
126
+ export const serveMany = (
127
+ workflows: Parameters<typeof serveManyBase>[0]["workflows"],
128
+ options?: Parameters<typeof serveManyBase>[0]["options"]
129
+ ) => {
130
+ // serveMany's serveMethod uses createExpressHandler (not serve), so start the
131
+ // dev server here too. No-op unless QSTASH_DEV is set.
132
+ void startDevServer();
133
+
134
+ const router = Router();
135
+
136
+ const { handler } = serveManyBase<ReturnType<typeof createExpressHandler>>({
137
+ workflows: workflows,
138
+ getUrl(...params) {
139
+ return params[0].url;
140
+ },
141
+ serveMethod: (...params: Parameters<typeof serve>) => createExpressHandler(params),
142
+ options,
143
+ });
144
+
145
+ router.all(/(.*)/, handler);
146
+ return router;
147
+ };
@@ -0,0 +1,105 @@
1
+ import { defineEventHandler, readRawBody } from "h3";
2
+
3
+ import type { InvokableWorkflow, WorkflowServeOptions, RouteFunction, Telemetry } from "../src";
4
+ import { serveBase } from "../src/serve";
5
+ import type { IncomingHttpHeaders } from "node:http";
6
+ import { SDK_TELEMETRY } from "../src/constants";
7
+ import { serveManyBase } from "../src/serve/serve-many";
8
+ import { startDevServer } from "@upstash/qstash";
9
+
10
+ function transformHeaders(headers: IncomingHttpHeaders): [string, string][] {
11
+ const formattedHeaders = Object.entries(headers).map(([key, value]) => [
12
+ key,
13
+ Array.isArray(value) ? value.join(", ") : (value ?? ""),
14
+ ]);
15
+ return formattedHeaders as [string, string][];
16
+ }
17
+
18
+ function getUrl(event: Parameters<Parameters<typeof defineEventHandler>[0]>[0]) {
19
+ const request_ = event.node.req;
20
+ const protocol = request_.headers["x-forwarded-proto"];
21
+ const host = request_.headers.host;
22
+ const url = `${protocol}://${host}${event.path}`;
23
+ return url;
24
+ }
25
+
26
+ const telemetry: Telemetry = {
27
+ sdk: SDK_TELEMETRY,
28
+ framework: "h3",
29
+ runtime: process.versions.bun
30
+ ? `bun@${process.versions.bun}/node@${process.version}`
31
+ : `node@${process.version}`,
32
+ };
33
+
34
+ /**
35
+ * Code outside steps runs again on every request of the run. Anything it branches on or
36
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
37
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
38
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
39
+ * result.
40
+ *
41
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
42
+ * @see node_modules/@upstash/workflow/docs/quickstarts/nuxt.mdx
43
+ */
44
+ export const serve = <TInitialPayload = unknown, TResult = unknown>(
45
+ routeFunction: RouteFunction<TInitialPayload, TResult>,
46
+ options?: WorkflowServeOptions<TInitialPayload, TResult>
47
+ ) => {
48
+ void startDevServer();
49
+
50
+ const handler = defineEventHandler(async (event) => {
51
+ const method = event.node.req.method;
52
+ if (method?.toUpperCase() !== "POST") {
53
+ return new Response("Only POST requests are allowed in worklfows", {
54
+ status: 405,
55
+ });
56
+ }
57
+
58
+ const url = getUrl(event);
59
+ const headers = transformHeaders(event.node.req.headers);
60
+
61
+ const request = new Request(url, {
62
+ headers: headers,
63
+ body: await readRawBody(event),
64
+ method: "POST",
65
+ });
66
+
67
+ const { handler: serveHandler } = serveBase<TInitialPayload, Request, Response, TResult>(
68
+ routeFunction,
69
+ telemetry,
70
+ options
71
+ );
72
+ return await serveHandler(request);
73
+ });
74
+
75
+ return { handler };
76
+ };
77
+
78
+ /**
79
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
80
+ */
81
+ export const createWorkflow = <TInitialPayload, TResult>(
82
+ ...params: Parameters<typeof serve<TInitialPayload, TResult>>
83
+ ): InvokableWorkflow<TInitialPayload, TResult> => {
84
+ const [routeFunction, options = {}] = params;
85
+ return {
86
+ routeFunction,
87
+ options,
88
+ workflowId: undefined,
89
+ };
90
+ };
91
+
92
+ /**
93
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
94
+ */
95
+ export const serveMany = (
96
+ workflows: Parameters<typeof serveManyBase>[0]["workflows"],
97
+ options?: Parameters<typeof serveManyBase>[0]["options"]
98
+ ) => {
99
+ return serveManyBase<ReturnType<typeof serve>["handler"]>({
100
+ workflows: workflows,
101
+ getUrl,
102
+ serveMethod: (...params: Parameters<typeof serve>) => serve(...params).handler,
103
+ options,
104
+ });
105
+ };
@@ -0,0 +1,103 @@
1
+ import type { Context } from "hono";
2
+ import type { InvokableWorkflow, WorkflowServeOptions, RouteFunction, Telemetry } from "../src";
3
+ import { serveBase } from "../src/serve";
4
+ import { Variables } from "hono/types";
5
+ import { SDK_TELEMETRY } from "../src/constants";
6
+ import { serveManyBase } from "../src/serve/serve-many";
7
+ import { startDevServer } from "@upstash/qstash";
8
+
9
+ export type WorkflowBindings = {
10
+ QSTASH_TOKEN: string;
11
+ QSTASH_URL?: string;
12
+ QSTASH_CURRENT_SIGNING_KEY?: string;
13
+ QSTASH_NEXT_SIGNING_KEY?: string;
14
+ UPSTASH_WORKFLOW_URL?: string;
15
+ };
16
+
17
+ const telemetry: Telemetry = {
18
+ sdk: SDK_TELEMETRY,
19
+ framework: "hono",
20
+ };
21
+
22
+ /**
23
+ * Serve method to serve a Upstash Workflow in a Hono project
24
+ *
25
+ * See for options https://upstash.com/docs/qstash/workflows/basics/serve
26
+ *
27
+ * Code outside steps runs again on every request of the run. Anything it branches on or
28
+ * returns early on (Date.now(), database rows, random values) must give the same answer on
29
+ * every request, or later requests fail with "Incompatible step name" or "Failed to
30
+ * authenticate Workflow request". Read such values inside `context.run` and branch on its
31
+ * result.
32
+ *
33
+ * @param routeFunction workflow function
34
+ * @param options workflow options
35
+ * @returns
36
+ * @see node_modules/@upstash/workflow/docs/basics/serve.mdx
37
+ * @see node_modules/@upstash/workflow/docs/quickstarts/hono.mdx
38
+ */
39
+ export const serve = <
40
+ TInitialPayload = unknown,
41
+ TBindings extends WorkflowBindings = WorkflowBindings,
42
+ TVariables extends Variables = Variables,
43
+ TResult = unknown,
44
+ >(
45
+ routeFunction: RouteFunction<TInitialPayload, TResult>,
46
+ options?: WorkflowServeOptions<TInitialPayload, TResult>
47
+ ): ((context: Context<{ Bindings: TBindings; Variables: TVariables }>) => Promise<Response>) => {
48
+ void startDevServer();
49
+
50
+ const handler = async (context: Context<{ Bindings: TBindings; Variables: TVariables }>) => {
51
+ const environment = context.env
52
+ ? context.env
53
+ : typeof process === "undefined"
54
+ ? ({} as Record<string, string>)
55
+ : process.env;
56
+ const request = context.req.raw;
57
+
58
+ const { handler: serveHandler } = serveBase(routeFunction, telemetry, {
59
+ // when hono is used without cf workers, it sends a DebugHTTPServer
60
+ // object in `context.env`. don't pass env if this is the case:
61
+ env: "QSTASH_TOKEN" in environment ? environment : undefined,
62
+ ...options,
63
+ });
64
+ return await serveHandler(request);
65
+ };
66
+ return handler;
67
+ };
68
+
69
+ /**
70
+ * @see node_modules/@upstash/workflow/docs/features/invoke.mdx
71
+ */
72
+ export const createWorkflow = <
73
+ TInitialPayload = unknown,
74
+ TResult = unknown,
75
+ TBindings extends WorkflowBindings = WorkflowBindings,
76
+ TVariables extends Variables = Variables,
77
+ >(
78
+ ...params: Parameters<typeof serve<TInitialPayload, TBindings, TVariables, TResult>>
79
+ ): InvokableWorkflow<TInitialPayload, TResult> => {
80
+ const [routeFunction, options = {}] = params;
81
+ return {
82
+ routeFunction,
83
+ options,
84
+ workflowId: undefined,
85
+ };
86
+ };
87
+
88
+ /**
89
+ * @see node_modules/@upstash/workflow/docs/features/invoke/serveMany.mdx
90
+ */
91
+ export const serveMany = (
92
+ workflows: Parameters<typeof serveManyBase>[0]["workflows"],
93
+ options?: Parameters<typeof serveManyBase>[0]["options"]
94
+ ) => {
95
+ return serveManyBase<ReturnType<typeof serve>>({
96
+ workflows: workflows,
97
+ getUrl(params) {
98
+ return params.req.url;
99
+ },
100
+ serveMethod: (...params: Parameters<typeof serve>) => serve(...params),
101
+ options,
102
+ }).handler;
103
+ };