@upstash/qstash 2.7.9 → 2.8.0-canary

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 (54) hide show
  1. package/{chunk-QK55BUNQ.mjs → dist/chunk-KWSSCN6R.mjs} +30 -0
  2. package/{chunk-UPFTIDSI.mjs → dist/chunk-XLCNEVA2.mjs} +1 -1
  3. package/dist/cloudflare.js +2973 -0
  4. package/{cloudflare.mjs → dist/cloudflare.mjs} +1 -1
  5. package/dist/h3.js +3338 -0
  6. package/{h3.mjs → dist/h3.mjs} +2 -2
  7. package/{chunk-R5CZPV7H.js → dist/hono.js} +245 -239
  8. package/{hono.mjs → dist/hono.mjs} +1 -1
  9. package/dist/index.js +1639 -0
  10. package/{index.mjs → dist/index.mjs} +1 -1
  11. package/dist/nextjs.js +4742 -0
  12. package/dist/nextjs.mjs +1802 -0
  13. package/dist/nuxt.js +832 -0
  14. package/{nuxt.mjs → dist/nuxt.mjs} +2 -2
  15. package/dist/solidjs.js +2991 -0
  16. package/{solidjs.mjs → dist/solidjs.mjs} +1 -1
  17. package/dist/svelte.js +2988 -0
  18. package/{svelte.mjs → dist/svelte.mjs} +1 -1
  19. package/dist/workflow.js +2954 -0
  20. package/{workflow.mjs → dist/workflow.mjs} +1 -1
  21. package/package.json +1 -1
  22. package/chunk-VN7YQ2UN.js +0 -1
  23. package/chunk-YBZBGHDQ.js +0 -403
  24. package/cloudflare.js +0 -37
  25. package/h3.js +0 -10
  26. package/hono.js +0 -22
  27. package/index.js +0 -43
  28. package/nextjs.js +0 -178
  29. package/nextjs.mjs +0 -178
  30. package/nuxt.js +0 -11
  31. package/solidjs.js +0 -56
  32. package/svelte.js +0 -53
  33. package/workflow.js +0 -18
  34. /package/{chunk-CIVGPRQN.mjs → dist/chunk-CIVGPRQN.mjs} +0 -0
  35. /package/{client-DkrYCqaq.d.mts → dist/client-DkrYCqaq.d.mts} +0 -0
  36. /package/{client-DkrYCqaq.d.ts → dist/client-DkrYCqaq.d.ts} +0 -0
  37. /package/{cloudflare.d.mts → dist/cloudflare.d.mts} +0 -0
  38. /package/{cloudflare.d.ts → dist/cloudflare.d.ts} +0 -0
  39. /package/{h3.d.mts → dist/h3.d.mts} +0 -0
  40. /package/{h3.d.ts → dist/h3.d.ts} +0 -0
  41. /package/{hono.d.mts → dist/hono.d.mts} +0 -0
  42. /package/{hono.d.ts → dist/hono.d.ts} +0 -0
  43. /package/{index.d.mts → dist/index.d.mts} +0 -0
  44. /package/{index.d.ts → dist/index.d.ts} +0 -0
  45. /package/{nextjs.d.mts → dist/nextjs.d.mts} +0 -0
  46. /package/{nextjs.d.ts → dist/nextjs.d.ts} +0 -0
  47. /package/{nuxt.d.mts → dist/nuxt.d.mts} +0 -0
  48. /package/{nuxt.d.ts → dist/nuxt.d.ts} +0 -0
  49. /package/{solidjs.d.mts → dist/solidjs.d.mts} +0 -0
  50. /package/{solidjs.d.ts → dist/solidjs.d.ts} +0 -0
  51. /package/{svelte.d.mts → dist/svelte.d.mts} +0 -0
  52. /package/{svelte.d.ts → dist/svelte.d.ts} +0 -0
  53. /package/{workflow.d.mts → dist/workflow.d.mts} +0 -0
  54. /package/{workflow.d.ts → dist/workflow.d.ts} +0 -0
@@ -0,0 +1,2973 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // platforms/cloudflare.ts
31
+ var cloudflare_exports = {};
32
+ __export(cloudflare_exports, {
33
+ serve: () => serve2
34
+ });
35
+ module.exports = __toCommonJS(cloudflare_exports);
36
+
37
+ // src/receiver.ts
38
+ var jose = __toESM(require("jose"));
39
+ var import_crypto_js = __toESM(require("crypto-js"));
40
+ var SignatureError = class extends Error {
41
+ constructor(message) {
42
+ super(message);
43
+ this.name = "SignatureError";
44
+ }
45
+ };
46
+ var Receiver = class {
47
+ currentSigningKey;
48
+ nextSigningKey;
49
+ constructor(config) {
50
+ this.currentSigningKey = config.currentSigningKey;
51
+ this.nextSigningKey = config.nextSigningKey;
52
+ }
53
+ /**
54
+ * Verify the signature of a request.
55
+ *
56
+ * Tries to verify the signature with the current signing key.
57
+ * If that fails, maybe because you have rotated the keys recently, it will
58
+ * try to verify the signature with the next signing key.
59
+ *
60
+ * If that fails, the signature is invalid and a `SignatureError` is thrown.
61
+ */
62
+ async verify(request) {
63
+ const isValid = await this.verifyWithKey(this.currentSigningKey, request);
64
+ if (isValid) {
65
+ return true;
66
+ }
67
+ return this.verifyWithKey(this.nextSigningKey, request);
68
+ }
69
+ /**
70
+ * Verify signature with a specific signing key
71
+ */
72
+ async verifyWithKey(key, request) {
73
+ const jwt = await jose.jwtVerify(request.signature, new TextEncoder().encode(key), {
74
+ issuer: "Upstash",
75
+ clockTolerance: request.clockTolerance
76
+ }).catch((error) => {
77
+ throw new SignatureError(error.message);
78
+ });
79
+ const p = jwt.payload;
80
+ if (request.url !== void 0 && p.sub !== request.url) {
81
+ throw new SignatureError(`invalid subject: ${p.sub}, want: ${request.url}`);
82
+ }
83
+ const bodyHash = import_crypto_js.default.SHA256(request.body).toString(import_crypto_js.default.enc.Base64url);
84
+ const padding = new RegExp(/=+$/);
85
+ if (p.body.replace(padding, "") !== bodyHash.replace(padding, "")) {
86
+ throw new SignatureError(`body hash does not match, want: ${p.body}, got: ${bodyHash}`);
87
+ }
88
+ return true;
89
+ }
90
+ };
91
+
92
+ // src/client/dlq.ts
93
+ var DLQ = class {
94
+ http;
95
+ constructor(http) {
96
+ this.http = http;
97
+ }
98
+ /**
99
+ * List messages in the dlq
100
+ */
101
+ async listMessages(options) {
102
+ const filterPayload = {
103
+ ...options?.filter,
104
+ topicName: options?.filter?.urlGroup
105
+ };
106
+ const messagesPayload = await this.http.request({
107
+ method: "GET",
108
+ path: ["v2", "dlq"],
109
+ query: {
110
+ cursor: options?.cursor,
111
+ count: options?.count,
112
+ ...filterPayload
113
+ }
114
+ });
115
+ return {
116
+ messages: messagesPayload.messages.map((message) => {
117
+ return {
118
+ ...message,
119
+ urlGroup: message.topicName
120
+ };
121
+ }),
122
+ cursor: messagesPayload.cursor
123
+ };
124
+ }
125
+ /**
126
+ * Remove a message from the dlq using it's `dlqId`
127
+ */
128
+ async delete(dlqMessageId) {
129
+ return await this.http.request({
130
+ method: "DELETE",
131
+ path: ["v2", "dlq", dlqMessageId],
132
+ parseResponseAsJson: false
133
+ // there is no response
134
+ });
135
+ }
136
+ /**
137
+ * Remove multiple messages from the dlq using their `dlqId`s
138
+ */
139
+ async deleteMany(request) {
140
+ return await this.http.request({
141
+ method: "DELETE",
142
+ path: ["v2", "dlq"],
143
+ headers: { "Content-Type": "application/json" },
144
+ body: JSON.stringify({ dlqIds: request.dlqIds })
145
+ });
146
+ }
147
+ };
148
+
149
+ // src/client/error.ts
150
+ var QstashError = class extends Error {
151
+ constructor(message) {
152
+ super(message);
153
+ this.name = "QstashError";
154
+ }
155
+ };
156
+ var QstashRatelimitError = class extends QstashError {
157
+ limit;
158
+ remaining;
159
+ reset;
160
+ constructor(args) {
161
+ super(`Exceeded burst rate limit. ${JSON.stringify(args)} `);
162
+ this.name = "QstashRatelimitError";
163
+ this.limit = args.limit;
164
+ this.remaining = args.remaining;
165
+ this.reset = args.reset;
166
+ }
167
+ };
168
+ var QstashChatRatelimitError = class extends QstashError {
169
+ limitRequests;
170
+ limitTokens;
171
+ remainingRequests;
172
+ remainingTokens;
173
+ resetRequests;
174
+ resetTokens;
175
+ constructor(args) {
176
+ super(`Exceeded chat rate limit. ${JSON.stringify(args)} `);
177
+ this.limitRequests = args["limit-requests"];
178
+ this.limitTokens = args["limit-tokens"];
179
+ this.remainingRequests = args["remaining-requests"];
180
+ this.remainingTokens = args["remaining-tokens"];
181
+ this.resetRequests = args["reset-requests"];
182
+ this.resetTokens = args["reset-tokens"];
183
+ }
184
+ };
185
+ var QstashDailyRatelimitError = class extends QstashError {
186
+ limit;
187
+ remaining;
188
+ reset;
189
+ constructor(args) {
190
+ super(`Exceeded daily rate limit. ${JSON.stringify(args)} `);
191
+ this.limit = args.limit;
192
+ this.remaining = args.remaining;
193
+ this.reset = args.reset;
194
+ this.name = "QstashChatRatelimitError";
195
+ }
196
+ };
197
+ var QStashWorkflowError = class extends QstashError {
198
+ constructor(message) {
199
+ super(message);
200
+ this.name = "QStashWorkflowError";
201
+ }
202
+ };
203
+ var QStashWorkflowAbort = class extends Error {
204
+ stepInfo;
205
+ stepName;
206
+ constructor(stepName, stepInfo) {
207
+ super(
208
+ `This is an QStash Workflow error thrown after a step executes. It is expected to be raised. Make sure that you await for each step. Also, if you are using try/catch blocks, you should not wrap context.run/sleep/sleepUntil/call methods with try/catch. Aborting workflow after executing step '${stepName}'.`
209
+ );
210
+ this.name = "QStashWorkflowAbort";
211
+ this.stepName = stepName;
212
+ this.stepInfo = stepInfo;
213
+ }
214
+ };
215
+ var formatWorkflowError = (error) => {
216
+ return error instanceof Error ? {
217
+ error: error.name,
218
+ message: error.message
219
+ } : {
220
+ error: "Error",
221
+ message: "An error occured while executing workflow."
222
+ };
223
+ };
224
+
225
+ // src/client/http.ts
226
+ var HttpClient = class {
227
+ baseUrl;
228
+ authorization;
229
+ options;
230
+ retry;
231
+ constructor(config) {
232
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
233
+ this.authorization = config.authorization;
234
+ this.retry = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
235
+ typeof config.retry === "boolean" && !config.retry ? {
236
+ attempts: 1,
237
+ backoff: () => 0
238
+ } : {
239
+ attempts: config.retry?.retries ? config.retry.retries + 1 : 5,
240
+ backoff: config.retry?.backoff ?? ((retryCount) => Math.exp(retryCount) * 50)
241
+ };
242
+ }
243
+ async request(request) {
244
+ const { response } = await this.requestWithBackoff(request);
245
+ if (request.parseResponseAsJson === false) {
246
+ return void 0;
247
+ }
248
+ return await response.json();
249
+ }
250
+ async *requestStream(request) {
251
+ const { response } = await this.requestWithBackoff(request);
252
+ if (!response.body) {
253
+ throw new Error("No response body");
254
+ }
255
+ const body = response.body;
256
+ const reader = body.getReader();
257
+ const decoder = new TextDecoder();
258
+ try {
259
+ while (true) {
260
+ const { done, value } = await reader.read();
261
+ if (done) {
262
+ break;
263
+ }
264
+ const chunkText = decoder.decode(value, { stream: true });
265
+ const chunks = chunkText.split("\n").filter(Boolean);
266
+ for (const chunk of chunks) {
267
+ if (chunk.startsWith("data: ")) {
268
+ const data = chunk.slice(6);
269
+ if (data === "[DONE]") {
270
+ break;
271
+ }
272
+ yield JSON.parse(data);
273
+ }
274
+ }
275
+ }
276
+ } finally {
277
+ await reader.cancel();
278
+ }
279
+ }
280
+ requestWithBackoff = async (request) => {
281
+ const [url, requestOptions] = this.processRequest(request);
282
+ let response = void 0;
283
+ let error = void 0;
284
+ for (let index = 0; index < this.retry.attempts; index++) {
285
+ try {
286
+ response = await fetch(url.toString(), requestOptions);
287
+ break;
288
+ } catch (error_) {
289
+ error = error_;
290
+ await new Promise((r) => setTimeout(r, this.retry.backoff(index)));
291
+ }
292
+ }
293
+ if (!response) {
294
+ throw error ?? new Error("Exhausted all retries");
295
+ }
296
+ await this.checkResponse(response);
297
+ return {
298
+ response,
299
+ error
300
+ };
301
+ };
302
+ processRequest = (request) => {
303
+ const headers = new Headers(request.headers);
304
+ if (!headers.has("Authorization")) {
305
+ headers.set("Authorization", this.authorization);
306
+ }
307
+ const requestOptions = {
308
+ method: request.method,
309
+ headers,
310
+ body: request.body,
311
+ keepalive: request.keepalive
312
+ };
313
+ const url = new URL([request.baseUrl ?? this.baseUrl, ...request.path].join("/"));
314
+ if (request.query) {
315
+ for (const [key, value] of Object.entries(request.query)) {
316
+ if (value !== void 0) {
317
+ url.searchParams.set(key, value.toString());
318
+ }
319
+ }
320
+ }
321
+ return [url.toString(), requestOptions];
322
+ };
323
+ async checkResponse(response) {
324
+ if (response.status === 429) {
325
+ if (response.headers.get("x-ratelimit-limit-requests")) {
326
+ throw new QstashChatRatelimitError({
327
+ "limit-requests": response.headers.get("x-ratelimit-limit-requests"),
328
+ "limit-tokens": response.headers.get("x-ratelimit-limit-tokens"),
329
+ "remaining-requests": response.headers.get("x-ratelimit-remaining-requests"),
330
+ "remaining-tokens": response.headers.get("x-ratelimit-remaining-tokens"),
331
+ "reset-requests": response.headers.get("x-ratelimit-reset-requests"),
332
+ "reset-tokens": response.headers.get("x-ratelimit-reset-tokens")
333
+ });
334
+ } else if (response.headers.get("RateLimit-Limit")) {
335
+ throw new QstashDailyRatelimitError({
336
+ limit: response.headers.get("RateLimit-Limit"),
337
+ remaining: response.headers.get("RateLimit-Remaining"),
338
+ reset: response.headers.get("RateLimit-Reset")
339
+ });
340
+ }
341
+ throw new QstashRatelimitError({
342
+ limit: response.headers.get("Burst-RateLimit-Limit"),
343
+ remaining: response.headers.get("Burst-RateLimit-Remaining"),
344
+ reset: response.headers.get("Burst-RateLimit-Reset")
345
+ });
346
+ }
347
+ if (response.status < 200 || response.status >= 300) {
348
+ const body = await response.text();
349
+ throw new QstashError(body.length > 0 ? body : `Error: status=${response.status}`);
350
+ }
351
+ }
352
+ };
353
+
354
+ // src/client/llm/providers.ts
355
+ var setupAnalytics = (analytics, providerApiKey, providerBaseUrl, provider) => {
356
+ if (!analytics)
357
+ return {};
358
+ switch (analytics.name) {
359
+ case "helicone": {
360
+ switch (provider) {
361
+ case "upstash": {
362
+ return {
363
+ baseURL: "https://qstash.helicone.ai/llm/v1/chat/completions",
364
+ defaultHeaders: {
365
+ "Helicone-Auth": `Bearer ${analytics.token}`,
366
+ Authorization: `Bearer ${providerApiKey}`
367
+ }
368
+ };
369
+ }
370
+ default: {
371
+ return {
372
+ baseURL: "https://gateway.helicone.ai/v1/chat/completions",
373
+ defaultHeaders: {
374
+ "Helicone-Auth": `Bearer ${analytics.token}`,
375
+ "Helicone-Target-Url": providerBaseUrl,
376
+ Authorization: `Bearer ${providerApiKey}`
377
+ }
378
+ };
379
+ }
380
+ }
381
+ }
382
+ default: {
383
+ throw new Error("Unknown analytics provider");
384
+ }
385
+ }
386
+ };
387
+
388
+ // src/client/llm/chat.ts
389
+ var Chat = class _Chat {
390
+ http;
391
+ token;
392
+ constructor(http, token) {
393
+ this.http = http;
394
+ this.token = token;
395
+ }
396
+ static toChatRequest(request) {
397
+ const messages = [];
398
+ messages.push(
399
+ { role: "system", content: request.system },
400
+ { role: "user", content: request.user }
401
+ );
402
+ const chatRequest = { ...request, messages };
403
+ return chatRequest;
404
+ }
405
+ /**
406
+ * Calls the Upstash completions api given a ChatRequest.
407
+ *
408
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
409
+ * if stream is enabled.
410
+ *
411
+ * @param request ChatRequest with messages
412
+ * @returns Chat completion or stream
413
+ */
414
+ create = async (request) => {
415
+ if (request.provider.owner != "upstash")
416
+ return this.createThirdParty(request);
417
+ const body = JSON.stringify(request);
418
+ let baseUrl = void 0;
419
+ let headers = {
420
+ "Content-Type": "application/json",
421
+ Authorization: `Bearer ${this.token}`,
422
+ ..."stream" in request && request.stream ? {
423
+ Connection: "keep-alive",
424
+ Accept: "text/event-stream",
425
+ "Cache-Control": "no-cache"
426
+ } : {}
427
+ };
428
+ if (request.analytics) {
429
+ const { baseURL, defaultHeaders } = setupAnalytics(
430
+ { name: "helicone", token: request.analytics.token },
431
+ this.getAuthorizationToken(),
432
+ request.provider.baseUrl,
433
+ "upstash"
434
+ );
435
+ headers = { ...headers, ...defaultHeaders };
436
+ baseUrl = baseURL;
437
+ }
438
+ const path = request.analytics ? [] : ["llm", "v1", "chat", "completions"];
439
+ return "stream" in request && request.stream ? this.http.requestStream({
440
+ path,
441
+ method: "POST",
442
+ headers,
443
+ baseUrl,
444
+ body
445
+ }) : this.http.request({
446
+ path,
447
+ method: "POST",
448
+ headers,
449
+ baseUrl,
450
+ body
451
+ });
452
+ };
453
+ /**
454
+ * Calls the Upstash completions api given a ChatRequest.
455
+ *
456
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
457
+ * if stream is enabled.
458
+ *
459
+ * @param request ChatRequest with messages
460
+ * @returns Chat completion or stream
461
+ */
462
+ // eslint-disable-next-line @typescript-eslint/require-await
463
+ createThirdParty = async (request) => {
464
+ const { baseUrl, token, owner } = request.provider;
465
+ if (owner === "upstash")
466
+ throw new Error("Upstash is not 3rd party provider!");
467
+ delete request.provider;
468
+ delete request.system;
469
+ const analytics = request.analytics;
470
+ delete request.analytics;
471
+ const body = JSON.stringify(request);
472
+ const isAnalyticsEnabled = analytics?.name && analytics.token;
473
+ const analyticsConfig = analytics?.name && analytics.token ? setupAnalytics({ name: analytics.name, token: analytics.token }, token, baseUrl, owner) : { defaultHeaders: void 0, baseURL: baseUrl };
474
+ const isStream = "stream" in request && request.stream;
475
+ const headers = {
476
+ "Content-Type": "application/json",
477
+ Authorization: `Bearer ${token}`,
478
+ ...isStream ? {
479
+ Connection: "keep-alive",
480
+ Accept: "text/event-stream",
481
+ "Cache-Control": "no-cache"
482
+ } : {},
483
+ ...analyticsConfig.defaultHeaders
484
+ };
485
+ const response = await this.http[isStream ? "requestStream" : "request"]({
486
+ path: isAnalyticsEnabled ? [] : ["v1", "chat", "completions"],
487
+ method: "POST",
488
+ headers,
489
+ body,
490
+ baseUrl: analyticsConfig.baseURL
491
+ });
492
+ return response;
493
+ };
494
+ // Helper method to get the authorization token
495
+ getAuthorizationToken() {
496
+ const authHeader = String(this.http.authorization);
497
+ const match = /Bearer (.+)/.exec(authHeader);
498
+ if (!match) {
499
+ throw new Error("Invalid authorization header format");
500
+ }
501
+ return match[1];
502
+ }
503
+ /**
504
+ * Calls the Upstash completions api given a PromptRequest.
505
+ *
506
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
507
+ * if stream is enabled.
508
+ *
509
+ * @param request PromptRequest with system and user messages.
510
+ * Note that system parameter shouldn't be passed in the case of
511
+ * mistralai/Mistral-7B-Instruct-v0.2 model.
512
+ * @returns Chat completion or stream
513
+ */
514
+ prompt = async (request) => {
515
+ const chatRequest = _Chat.toChatRequest(request);
516
+ return this.create(chatRequest);
517
+ };
518
+ };
519
+
520
+ // src/client/llm/utils.ts
521
+ function appendLLMOptionsIfNeeded(request, headers, http) {
522
+ if (!request.api)
523
+ return;
524
+ const provider = request.api.provider;
525
+ const analytics = request.api.analytics;
526
+ if (provider?.owner === "upstash") {
527
+ handleUpstashProvider(request, headers, http, analytics);
528
+ return;
529
+ }
530
+ if (!("provider" in request.api))
531
+ return;
532
+ const { baseUrl, token } = validateProviderConfig(provider);
533
+ const analyticsConfig = analytics ? setupAnalytics({ name: analytics.name, token: analytics.token }, token, baseUrl, "custom") : void 0;
534
+ if (analyticsConfig) {
535
+ setAnalyticsHeaders(headers, analyticsConfig);
536
+ request.url = analyticsConfig.baseURL;
537
+ } else {
538
+ request.url = `${baseUrl}/v1/chat/completions`;
539
+ headers.set("Authorization", `Bearer ${token}`);
540
+ }
541
+ }
542
+ function handleUpstashProvider(request, headers, http, analytics) {
543
+ if (analytics) {
544
+ const analyticsConfig = setupAnalytics(
545
+ { name: analytics.name, token: analytics.token },
546
+ //@ts-expect-error hacky way to get bearer token
547
+ String(http.authorization).split("Bearer ")[1],
548
+ request.api?.provider?.baseUrl,
549
+ "upstash"
550
+ );
551
+ setAnalyticsHeaders(headers, analyticsConfig);
552
+ request.url = analyticsConfig.baseURL;
553
+ } else {
554
+ request.api = { name: "llm" };
555
+ }
556
+ }
557
+ function validateProviderConfig(provider) {
558
+ if (!provider?.baseUrl)
559
+ throw new Error("baseUrl cannot be empty or undefined!");
560
+ if (!provider.token)
561
+ throw new Error("token cannot be empty or undefined!");
562
+ return { baseUrl: provider.baseUrl, token: provider.token };
563
+ }
564
+ function setAnalyticsHeaders(headers, analyticsConfig) {
565
+ headers.set("Helicone-Auth", analyticsConfig.defaultHeaders?.["Helicone-Auth"] ?? "");
566
+ headers.set("Authorization", analyticsConfig.defaultHeaders?.Authorization ?? "");
567
+ if (analyticsConfig.defaultHeaders?.["Helicone-Target-Url"]) {
568
+ headers.set("Helicone-Target-Url", analyticsConfig.defaultHeaders["Helicone-Target-Url"]);
569
+ }
570
+ }
571
+ function ensureCallbackPresent(request) {
572
+ if (request.api?.name === "llm" && !request.callback) {
573
+ throw new TypeError("Callback cannot be undefined when using LLM");
574
+ }
575
+ }
576
+
577
+ // src/client/messages.ts
578
+ var Messages = class {
579
+ http;
580
+ constructor(http) {
581
+ this.http = http;
582
+ }
583
+ /**
584
+ * Get a message
585
+ */
586
+ async get(messageId) {
587
+ const messagePayload = await this.http.request({
588
+ method: "GET",
589
+ path: ["v2", "messages", messageId]
590
+ });
591
+ const message = {
592
+ ...messagePayload,
593
+ urlGroup: messagePayload.topicName
594
+ };
595
+ return message;
596
+ }
597
+ /**
598
+ * Cancel a message
599
+ */
600
+ async delete(messageId) {
601
+ return await this.http.request({
602
+ method: "DELETE",
603
+ path: ["v2", "messages", messageId],
604
+ parseResponseAsJson: false
605
+ });
606
+ }
607
+ async deleteMany(messageIds) {
608
+ const result = await this.http.request({
609
+ method: "DELETE",
610
+ path: ["v2", "messages"],
611
+ headers: { "Content-Type": "application/json" },
612
+ body: JSON.stringify({ messageIds })
613
+ });
614
+ return result.cancelled;
615
+ }
616
+ async deleteAll() {
617
+ const result = await this.http.request({
618
+ method: "DELETE",
619
+ path: ["v2", "messages"]
620
+ });
621
+ return result.cancelled;
622
+ }
623
+ };
624
+
625
+ // src/client/utils.ts
626
+ var isIgnoredHeader = (header) => {
627
+ const lowerCaseHeader = header.toLowerCase();
628
+ return lowerCaseHeader.startsWith("content-type") || lowerCaseHeader.startsWith("upstash-");
629
+ };
630
+ function prefixHeaders(headers) {
631
+ const keysToBePrefixed = [...headers.keys()].filter((key) => !isIgnoredHeader(key));
632
+ for (const key of keysToBePrefixed) {
633
+ const value = headers.get(key);
634
+ if (value !== null) {
635
+ headers.set(`Upstash-Forward-${key}`, value);
636
+ }
637
+ headers.delete(key);
638
+ }
639
+ return headers;
640
+ }
641
+ function processHeaders(request) {
642
+ const headers = prefixHeaders(new Headers(request.headers));
643
+ headers.set("Upstash-Method", request.method ?? "POST");
644
+ if (request.delay !== void 0) {
645
+ if (typeof request.delay === "string") {
646
+ headers.set("Upstash-Delay", request.delay);
647
+ } else {
648
+ headers.set("Upstash-Delay", `${request.delay.toFixed(0)}s`);
649
+ }
650
+ }
651
+ if (request.notBefore !== void 0) {
652
+ headers.set("Upstash-Not-Before", request.notBefore.toFixed(0));
653
+ }
654
+ if (request.deduplicationId !== void 0) {
655
+ headers.set("Upstash-Deduplication-Id", request.deduplicationId);
656
+ }
657
+ if (request.contentBasedDeduplication !== void 0) {
658
+ headers.set("Upstash-Content-Based-Deduplication", "true");
659
+ }
660
+ if (request.retries !== void 0) {
661
+ headers.set("Upstash-Retries", request.retries.toFixed(0));
662
+ }
663
+ if (request.callback !== void 0) {
664
+ headers.set("Upstash-Callback", request.callback);
665
+ }
666
+ if (request.failureCallback !== void 0) {
667
+ headers.set("Upstash-Failure-Callback", request.failureCallback);
668
+ }
669
+ if (request.timeout !== void 0) {
670
+ if (typeof request.timeout === "string") {
671
+ headers.set("Upstash-Timeout", request.timeout);
672
+ } else {
673
+ headers.set("Upstash-Timeout", `${request.timeout}s`);
674
+ }
675
+ }
676
+ return headers;
677
+ }
678
+ function getRequestPath(request) {
679
+ return request.url ?? request.urlGroup ?? request.topic ?? `api/${request.api?.name}`;
680
+ }
681
+ var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
682
+ var NANOID_LENGTH = 21;
683
+ function nanoid() {
684
+ return [...crypto.getRandomValues(new Uint8Array(NANOID_LENGTH))].map((x) => NANOID_CHARS[x % NANOID_CHARS.length]).join("");
685
+ }
686
+ function decodeBase64(base64) {
687
+ try {
688
+ const binString = atob(base64);
689
+ const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
690
+ return new TextDecoder().decode(intArray);
691
+ } catch (error) {
692
+ console.warn(
693
+ `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. Error: ${error}`
694
+ );
695
+ return atob(base64);
696
+ }
697
+ }
698
+
699
+ // src/client/queue.ts
700
+ var Queue = class {
701
+ http;
702
+ queueName;
703
+ constructor(http, queueName) {
704
+ this.http = http;
705
+ this.queueName = queueName;
706
+ }
707
+ /**
708
+ * Create or update the queue
709
+ */
710
+ async upsert(request) {
711
+ if (!this.queueName) {
712
+ throw new Error("Please provide a queue name to the Queue constructor");
713
+ }
714
+ const body = {
715
+ queueName: this.queueName,
716
+ parallelism: request.parallelism ?? 1,
717
+ paused: request.paused ?? false
718
+ };
719
+ await this.http.request({
720
+ method: "POST",
721
+ path: ["v2", "queues"],
722
+ headers: {
723
+ "Content-Type": "application/json"
724
+ },
725
+ body: JSON.stringify(body),
726
+ parseResponseAsJson: false
727
+ });
728
+ }
729
+ /**
730
+ * Get the queue details
731
+ */
732
+ async get() {
733
+ if (!this.queueName) {
734
+ throw new Error("Please provide a queue name to the Queue constructor");
735
+ }
736
+ return await this.http.request({
737
+ method: "GET",
738
+ path: ["v2", "queues", this.queueName]
739
+ });
740
+ }
741
+ /**
742
+ * List queues
743
+ */
744
+ async list() {
745
+ return await this.http.request({
746
+ method: "GET",
747
+ path: ["v2", "queues"]
748
+ });
749
+ }
750
+ /**
751
+ * Delete the queue
752
+ */
753
+ async delete() {
754
+ if (!this.queueName) {
755
+ throw new Error("Please provide a queue name to the Queue constructor");
756
+ }
757
+ await this.http.request({
758
+ method: "DELETE",
759
+ path: ["v2", "queues", this.queueName],
760
+ parseResponseAsJson: false
761
+ });
762
+ }
763
+ /**
764
+ * Enqueue a message to a queue.
765
+ */
766
+ async enqueue(request) {
767
+ if (!this.queueName) {
768
+ throw new Error("Please provide a queue name to the Queue constructor");
769
+ }
770
+ const headers = processHeaders(request);
771
+ const destination = getRequestPath(request);
772
+ const response = await this.http.request({
773
+ path: ["v2", "enqueue", this.queueName, destination],
774
+ body: request.body,
775
+ headers,
776
+ method: "POST"
777
+ });
778
+ return response;
779
+ }
780
+ /**
781
+ * Enqueue a message to a queue, serializing the body to JSON.
782
+ */
783
+ async enqueueJSON(request) {
784
+ const headers = prefixHeaders(new Headers(request.headers));
785
+ headers.set("Content-Type", "application/json");
786
+ ensureCallbackPresent(request);
787
+ appendLLMOptionsIfNeeded(request, headers, this.http);
788
+ const response = await this.enqueue({
789
+ ...request,
790
+ body: JSON.stringify(request.body),
791
+ headers
792
+ });
793
+ return response;
794
+ }
795
+ /**
796
+ * Pauses the queue.
797
+ *
798
+ * A paused queue will not deliver messages until
799
+ * it is resumed.
800
+ */
801
+ async pause() {
802
+ if (!this.queueName) {
803
+ throw new Error("Please provide a queue name to the Queue constructor");
804
+ }
805
+ await this.http.request({
806
+ method: "POST",
807
+ path: ["v2", "queues", this.queueName, "pause"],
808
+ parseResponseAsJson: false
809
+ });
810
+ }
811
+ /**
812
+ * Resumes the queue.
813
+ */
814
+ async resume() {
815
+ if (!this.queueName) {
816
+ throw new Error("Please provide a queue name to the Queue constructor");
817
+ }
818
+ await this.http.request({
819
+ method: "POST",
820
+ path: ["v2", "queues", this.queueName, "resume"],
821
+ parseResponseAsJson: false
822
+ });
823
+ }
824
+ };
825
+
826
+ // src/client/schedules.ts
827
+ var Schedules = class {
828
+ http;
829
+ constructor(http) {
830
+ this.http = http;
831
+ }
832
+ /**
833
+ * Create a schedule
834
+ */
835
+ async create(request) {
836
+ const headers = prefixHeaders(new Headers(request.headers));
837
+ if (!headers.has("Content-Type")) {
838
+ headers.set("Content-Type", "application/json");
839
+ }
840
+ headers.set("Upstash-Cron", request.cron);
841
+ if (request.method !== void 0) {
842
+ headers.set("Upstash-Method", request.method);
843
+ }
844
+ if (request.delay !== void 0) {
845
+ if (typeof request.delay === "string") {
846
+ headers.set("Upstash-Delay", request.delay);
847
+ } else {
848
+ headers.set("Upstash-Delay", `${request.delay.toFixed(0)}s`);
849
+ }
850
+ }
851
+ if (request.retries !== void 0) {
852
+ headers.set("Upstash-Retries", request.retries.toFixed(0));
853
+ }
854
+ if (request.callback !== void 0) {
855
+ headers.set("Upstash-Callback", request.callback);
856
+ }
857
+ if (request.failureCallback !== void 0) {
858
+ headers.set("Upstash-Failure-Callback", request.failureCallback);
859
+ }
860
+ if (request.timeout !== void 0) {
861
+ if (typeof request.timeout === "string") {
862
+ headers.set("Upstash-Timeout", request.timeout);
863
+ } else {
864
+ headers.set("Upstash-Timeout", `${request.timeout}s`);
865
+ }
866
+ }
867
+ if (request.scheduleId !== void 0) {
868
+ headers.set("Upstash-Schedule-Id", request.scheduleId);
869
+ }
870
+ return await this.http.request({
871
+ method: "POST",
872
+ headers,
873
+ path: ["v2", "schedules", request.destination],
874
+ body: request.body
875
+ });
876
+ }
877
+ /**
878
+ * Get a schedule
879
+ */
880
+ async get(scheduleId) {
881
+ return await this.http.request({
882
+ method: "GET",
883
+ path: ["v2", "schedules", scheduleId]
884
+ });
885
+ }
886
+ /**
887
+ * List your schedules
888
+ */
889
+ async list() {
890
+ return await this.http.request({
891
+ method: "GET",
892
+ path: ["v2", "schedules"]
893
+ });
894
+ }
895
+ /**
896
+ * Delete a schedule
897
+ */
898
+ async delete(scheduleId) {
899
+ return await this.http.request({
900
+ method: "DELETE",
901
+ path: ["v2", "schedules", scheduleId],
902
+ parseResponseAsJson: false
903
+ });
904
+ }
905
+ /**
906
+ * Pauses the schedule.
907
+ *
908
+ * A paused schedule will not deliver messages until
909
+ * it is resumed.
910
+ */
911
+ async pause({ schedule }) {
912
+ await this.http.request({
913
+ method: "PATCH",
914
+ path: ["v2", "schedules", schedule, "pause"],
915
+ parseResponseAsJson: false
916
+ });
917
+ }
918
+ /**
919
+ * Resumes the schedule.
920
+ */
921
+ async resume({ schedule }) {
922
+ await this.http.request({
923
+ method: "PATCH",
924
+ path: ["v2", "schedules", schedule, "resume"],
925
+ parseResponseAsJson: false
926
+ });
927
+ }
928
+ };
929
+
930
+ // src/client/url-groups.ts
931
+ var UrlGroups = class {
932
+ http;
933
+ constructor(http) {
934
+ this.http = http;
935
+ }
936
+ /**
937
+ * Create a new url group with the given name and endpoints
938
+ */
939
+ async addEndpoints(request) {
940
+ await this.http.request({
941
+ method: "POST",
942
+ path: ["v2", "topics", request.name, "endpoints"],
943
+ headers: { "Content-Type": "application/json" },
944
+ body: JSON.stringify({ endpoints: request.endpoints }),
945
+ parseResponseAsJson: false
946
+ });
947
+ }
948
+ /**
949
+ * Remove endpoints from a url group.
950
+ */
951
+ async removeEndpoints(request) {
952
+ await this.http.request({
953
+ method: "DELETE",
954
+ path: ["v2", "topics", request.name, "endpoints"],
955
+ headers: { "Content-Type": "application/json" },
956
+ body: JSON.stringify({ endpoints: request.endpoints }),
957
+ parseResponseAsJson: false
958
+ });
959
+ }
960
+ /**
961
+ * Get a list of all url groups.
962
+ */
963
+ async list() {
964
+ return await this.http.request({
965
+ method: "GET",
966
+ path: ["v2", "topics"]
967
+ });
968
+ }
969
+ /**
970
+ * Get a single url group
971
+ */
972
+ async get(name) {
973
+ return await this.http.request({
974
+ method: "GET",
975
+ path: ["v2", "topics", name]
976
+ });
977
+ }
978
+ /**
979
+ * Delete a url group
980
+ */
981
+ async delete(name) {
982
+ return await this.http.request({
983
+ method: "DELETE",
984
+ path: ["v2", "topics", name],
985
+ parseResponseAsJson: false
986
+ });
987
+ }
988
+ };
989
+
990
+ // src/client/client.ts
991
+ var Client = class {
992
+ http;
993
+ token;
994
+ constructor(config) {
995
+ this.http = new HttpClient({
996
+ retry: config.retry,
997
+ baseUrl: config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "https://qstash.upstash.io",
998
+ authorization: `Bearer ${config.token}`
999
+ });
1000
+ this.token = config.token;
1001
+ }
1002
+ /**
1003
+ * Access the urlGroup API.
1004
+ *
1005
+ * Create, read, update or delete urlGroups.
1006
+ */
1007
+ get urlGroups() {
1008
+ return new UrlGroups(this.http);
1009
+ }
1010
+ /**
1011
+ * Deprecated. Use urlGroups instead.
1012
+ *
1013
+ * Access the topic API.
1014
+ *
1015
+ * Create, read, update or delete topics.
1016
+ */
1017
+ get topics() {
1018
+ return this.urlGroups;
1019
+ }
1020
+ /**
1021
+ * Access the dlq API.
1022
+ *
1023
+ * List or remove messages from the DLQ.
1024
+ */
1025
+ get dlq() {
1026
+ return new DLQ(this.http);
1027
+ }
1028
+ /**
1029
+ * Access the message API.
1030
+ *
1031
+ * Read or cancel messages.
1032
+ */
1033
+ get messages() {
1034
+ return new Messages(this.http);
1035
+ }
1036
+ /**
1037
+ * Access the schedule API.
1038
+ *
1039
+ * Create, read or delete schedules.
1040
+ */
1041
+ get schedules() {
1042
+ return new Schedules(this.http);
1043
+ }
1044
+ /**
1045
+ * Access the workflow API.
1046
+ *
1047
+ * cancel workflows.
1048
+ */
1049
+ get workflow() {
1050
+ return new Workflow(this.http);
1051
+ }
1052
+ /**
1053
+ * Access the queue API.
1054
+ *
1055
+ * Create, read, update or delete queues.
1056
+ */
1057
+ queue(request) {
1058
+ return new Queue(this.http, request?.queueName);
1059
+ }
1060
+ /**
1061
+ * Access the Chat API
1062
+ *
1063
+ * Call the create or prompt methods
1064
+ */
1065
+ chat() {
1066
+ return new Chat(this.http, this.token);
1067
+ }
1068
+ async publish(request) {
1069
+ const headers = processHeaders(request);
1070
+ const response = await this.http.request({
1071
+ path: ["v2", "publish", getRequestPath(request)],
1072
+ body: request.body,
1073
+ headers,
1074
+ method: "POST"
1075
+ });
1076
+ return response;
1077
+ }
1078
+ /**
1079
+ * publishJSON is a utility wrapper around `publish` that automatically serializes the body
1080
+ * and sets the `Content-Type` header to `application/json`.
1081
+ */
1082
+ async publishJSON(request) {
1083
+ const headers = prefixHeaders(new Headers(request.headers));
1084
+ headers.set("Content-Type", "application/json");
1085
+ ensureCallbackPresent(request);
1086
+ appendLLMOptionsIfNeeded(request, headers, this.http);
1087
+ const response = await this.publish({
1088
+ ...request,
1089
+ headers,
1090
+ body: JSON.stringify(request.body)
1091
+ });
1092
+ return response;
1093
+ }
1094
+ /**
1095
+ * Batch publish messages to QStash.
1096
+ */
1097
+ async batch(request) {
1098
+ const messages = [];
1099
+ for (const message of request) {
1100
+ const headers = processHeaders(message);
1101
+ const headerEntries = Object.fromEntries(headers.entries());
1102
+ messages.push({
1103
+ destination: getRequestPath(message),
1104
+ headers: headerEntries,
1105
+ body: message.body,
1106
+ ...message.queueName && { queue: message.queueName }
1107
+ });
1108
+ }
1109
+ const response = await this.http.request({
1110
+ path: ["v2", "batch"],
1111
+ body: JSON.stringify(messages),
1112
+ headers: {
1113
+ "Content-Type": "application/json"
1114
+ },
1115
+ method: "POST"
1116
+ });
1117
+ const arrayResposne = Array.isArray(response) ? response : [response];
1118
+ return arrayResposne;
1119
+ }
1120
+ /**
1121
+ * Batch publish messages to QStash, serializing each body to JSON.
1122
+ */
1123
+ async batchJSON(request) {
1124
+ for (const message of request) {
1125
+ if ("body" in message) {
1126
+ message.body = JSON.stringify(message.body);
1127
+ }
1128
+ message.headers = new Headers(message.headers);
1129
+ ensureCallbackPresent(message);
1130
+ appendLLMOptionsIfNeeded(message, message.headers, this.http);
1131
+ message.headers.set("Content-Type", "application/json");
1132
+ }
1133
+ const response = await this.batch(request);
1134
+ return response;
1135
+ }
1136
+ /**
1137
+ * Retrieve your logs.
1138
+ *
1139
+ * The logs endpoint is paginated and returns only 100 logs at a time.
1140
+ * If you want to receive more logs, you can use the cursor to paginate.
1141
+ *
1142
+ * The cursor is a unix timestamp with millisecond precision
1143
+ *
1144
+ * @example
1145
+ * ```ts
1146
+ * let cursor = Date.now()
1147
+ * const logs: Log[] = []
1148
+ * while (cursor > 0) {
1149
+ * const res = await qstash.logs({ cursor })
1150
+ * logs.push(...res.logs)
1151
+ * cursor = res.cursor ?? 0
1152
+ * }
1153
+ * ```
1154
+ */
1155
+ async events(request) {
1156
+ const query = {};
1157
+ if (typeof request?.cursor === "number" && request.cursor > 0) {
1158
+ query.cursor = request.cursor.toString();
1159
+ } else if (typeof request?.cursor === "string" && request.cursor !== "") {
1160
+ query.cursor = request.cursor;
1161
+ }
1162
+ for (const [key, value] of Object.entries(request?.filter ?? {})) {
1163
+ if (typeof value === "number" && value < 0) {
1164
+ continue;
1165
+ }
1166
+ if (key === "urlGroup") {
1167
+ query.topicName = value.toString();
1168
+ } else if (typeof value !== "undefined") {
1169
+ query[key] = value.toString();
1170
+ }
1171
+ }
1172
+ const responsePayload = await this.http.request({
1173
+ path: ["v2", "events"],
1174
+ method: "GET",
1175
+ query
1176
+ });
1177
+ return {
1178
+ cursor: responsePayload.cursor,
1179
+ events: responsePayload.events.map((event) => {
1180
+ return {
1181
+ ...event,
1182
+ urlGroup: event.topicName
1183
+ };
1184
+ })
1185
+ };
1186
+ }
1187
+ };
1188
+
1189
+ // src/client/workflow/constants.ts
1190
+ var WORKFLOW_ID_HEADER = "Upstash-Workflow-RunId";
1191
+ var WORKFLOW_INIT_HEADER = "Upstash-Workflow-Init";
1192
+ var WORKFLOW_URL_HEADER = "Upstash-Workflow-Url";
1193
+ var WORKFLOW_FAILURE_HEADER = "Upstash-Workflow-Is-Failure";
1194
+ var WORKFLOW_PROTOCOL_VERSION = "1";
1195
+ var WORKFLOW_PROTOCOL_VERSION_HEADER = "Upstash-Workflow-Sdk-Version";
1196
+ var DEFAULT_CONTENT_TYPE = "application/json";
1197
+ var NO_CONCURRENCY = 1;
1198
+ var DEFAULT_RETRIES = 3;
1199
+
1200
+ // node_modules/neverthrow/dist/index.es.js
1201
+ var defaultErrorConfig = {
1202
+ withStackTrace: false
1203
+ };
1204
+ var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
1205
+ const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
1206
+ const maybeStack = config.withStackTrace ? new Error().stack : void 0;
1207
+ return {
1208
+ data,
1209
+ message,
1210
+ stack: maybeStack
1211
+ };
1212
+ };
1213
+ function __awaiter(thisArg, _arguments, P, generator) {
1214
+ function adopt(value) {
1215
+ return value instanceof P ? value : new P(function(resolve) {
1216
+ resolve(value);
1217
+ });
1218
+ }
1219
+ return new (P || (P = Promise))(function(resolve, reject) {
1220
+ function fulfilled(value) {
1221
+ try {
1222
+ step(generator.next(value));
1223
+ } catch (e) {
1224
+ reject(e);
1225
+ }
1226
+ }
1227
+ function rejected(value) {
1228
+ try {
1229
+ step(generator["throw"](value));
1230
+ } catch (e) {
1231
+ reject(e);
1232
+ }
1233
+ }
1234
+ function step(result) {
1235
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1236
+ }
1237
+ step((generator = generator.apply(thisArg, [])).next());
1238
+ });
1239
+ }
1240
+ function __values(o) {
1241
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
1242
+ if (m)
1243
+ return m.call(o);
1244
+ if (o && typeof o.length === "number")
1245
+ return {
1246
+ next: function() {
1247
+ if (o && i >= o.length)
1248
+ o = void 0;
1249
+ return { value: o && o[i++], done: !o };
1250
+ }
1251
+ };
1252
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
1253
+ }
1254
+ function __await(v) {
1255
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
1256
+ }
1257
+ function __asyncGenerator(thisArg, _arguments, generator) {
1258
+ if (!Symbol.asyncIterator)
1259
+ throw new TypeError("Symbol.asyncIterator is not defined.");
1260
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
1261
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
1262
+ return this;
1263
+ }, i;
1264
+ function verb(n) {
1265
+ if (g[n])
1266
+ i[n] = function(v) {
1267
+ return new Promise(function(a, b) {
1268
+ q.push([n, v, a, b]) > 1 || resume(n, v);
1269
+ });
1270
+ };
1271
+ }
1272
+ function resume(n, v) {
1273
+ try {
1274
+ step(g[n](v));
1275
+ } catch (e) {
1276
+ settle(q[0][3], e);
1277
+ }
1278
+ }
1279
+ function step(r) {
1280
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
1281
+ }
1282
+ function fulfill(value) {
1283
+ resume("next", value);
1284
+ }
1285
+ function reject(value) {
1286
+ resume("throw", value);
1287
+ }
1288
+ function settle(f, v) {
1289
+ if (f(v), q.shift(), q.length)
1290
+ resume(q[0][0], q[0][1]);
1291
+ }
1292
+ }
1293
+ function __asyncDelegator(o) {
1294
+ var i, p;
1295
+ return i = {}, verb("next"), verb("throw", function(e) {
1296
+ throw e;
1297
+ }), verb("return"), i[Symbol.iterator] = function() {
1298
+ return this;
1299
+ }, i;
1300
+ function verb(n, f) {
1301
+ i[n] = o[n] ? function(v) {
1302
+ return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
1303
+ } : f;
1304
+ }
1305
+ }
1306
+ function __asyncValues(o) {
1307
+ if (!Symbol.asyncIterator)
1308
+ throw new TypeError("Symbol.asyncIterator is not defined.");
1309
+ var m = o[Symbol.asyncIterator], i;
1310
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
1311
+ return this;
1312
+ }, i);
1313
+ function verb(n) {
1314
+ i[n] = o[n] && function(v) {
1315
+ return new Promise(function(resolve, reject) {
1316
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
1317
+ });
1318
+ };
1319
+ }
1320
+ function settle(resolve, reject, d, v) {
1321
+ Promise.resolve(v).then(function(v2) {
1322
+ resolve({ value: v2, done: d });
1323
+ }, reject);
1324
+ }
1325
+ }
1326
+ var ResultAsync = class _ResultAsync {
1327
+ constructor(res) {
1328
+ this._promise = res;
1329
+ }
1330
+ static fromSafePromise(promise) {
1331
+ const newPromise = promise.then((value) => new Ok(value));
1332
+ return new _ResultAsync(newPromise);
1333
+ }
1334
+ static fromPromise(promise, errorFn) {
1335
+ const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
1336
+ return new _ResultAsync(newPromise);
1337
+ }
1338
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1339
+ static fromThrowable(fn, errorFn) {
1340
+ return (...args) => {
1341
+ return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
1342
+ try {
1343
+ return new Ok(yield fn(...args));
1344
+ } catch (error) {
1345
+ return new Err(errorFn ? errorFn(error) : error);
1346
+ }
1347
+ }))());
1348
+ };
1349
+ }
1350
+ static combine(asyncResultList) {
1351
+ return combineResultAsyncList(asyncResultList);
1352
+ }
1353
+ static combineWithAllErrors(asyncResultList) {
1354
+ return combineResultAsyncListWithAllErrors(asyncResultList);
1355
+ }
1356
+ map(f) {
1357
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
1358
+ if (res.isErr()) {
1359
+ return new Err(res.error);
1360
+ }
1361
+ return new Ok(yield f(res.value));
1362
+ })));
1363
+ }
1364
+ mapErr(f) {
1365
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
1366
+ if (res.isOk()) {
1367
+ return new Ok(res.value);
1368
+ }
1369
+ return new Err(yield f(res.error));
1370
+ })));
1371
+ }
1372
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1373
+ andThen(f) {
1374
+ return new _ResultAsync(this._promise.then((res) => {
1375
+ if (res.isErr()) {
1376
+ return new Err(res.error);
1377
+ }
1378
+ const newValue = f(res.value);
1379
+ return newValue instanceof _ResultAsync ? newValue._promise : newValue;
1380
+ }));
1381
+ }
1382
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1383
+ orElse(f) {
1384
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
1385
+ if (res.isErr()) {
1386
+ return f(res.error);
1387
+ }
1388
+ return new Ok(res.value);
1389
+ })));
1390
+ }
1391
+ match(ok2, _err) {
1392
+ return this._promise.then((res) => res.match(ok2, _err));
1393
+ }
1394
+ unwrapOr(t) {
1395
+ return this._promise.then((res) => res.unwrapOr(t));
1396
+ }
1397
+ /**
1398
+ * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
1399
+ */
1400
+ safeUnwrap() {
1401
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
1402
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
1403
+ });
1404
+ }
1405
+ // Makes ResultAsync implement PromiseLike<Result>
1406
+ then(successCallback, failureCallback) {
1407
+ return this._promise.then(successCallback, failureCallback);
1408
+ }
1409
+ };
1410
+ var errAsync = (err2) => new ResultAsync(Promise.resolve(new Err(err2)));
1411
+ var fromPromise = ResultAsync.fromPromise;
1412
+ var fromSafePromise = ResultAsync.fromSafePromise;
1413
+ var fromAsyncThrowable = ResultAsync.fromThrowable;
1414
+ var combineResultList = (resultList) => {
1415
+ let acc = ok([]);
1416
+ for (const result of resultList) {
1417
+ if (result.isErr()) {
1418
+ acc = err(result.error);
1419
+ break;
1420
+ } else {
1421
+ acc.map((list) => list.push(result.value));
1422
+ }
1423
+ }
1424
+ return acc;
1425
+ };
1426
+ var combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
1427
+ var combineResultListWithAllErrors = (resultList) => {
1428
+ let acc = ok([]);
1429
+ for (const result of resultList) {
1430
+ if (result.isErr() && acc.isErr()) {
1431
+ acc.error.push(result.error);
1432
+ } else if (result.isErr() && acc.isOk()) {
1433
+ acc = err([result.error]);
1434
+ } else if (result.isOk() && acc.isOk()) {
1435
+ acc.value.push(result.value);
1436
+ }
1437
+ }
1438
+ return acc;
1439
+ };
1440
+ var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
1441
+ var Result;
1442
+ (function(Result2) {
1443
+ function fromThrowable2(fn, errorFn) {
1444
+ return (...args) => {
1445
+ try {
1446
+ const result = fn(...args);
1447
+ return ok(result);
1448
+ } catch (e) {
1449
+ return err(errorFn ? errorFn(e) : e);
1450
+ }
1451
+ };
1452
+ }
1453
+ Result2.fromThrowable = fromThrowable2;
1454
+ function combine(resultList) {
1455
+ return combineResultList(resultList);
1456
+ }
1457
+ Result2.combine = combine;
1458
+ function combineWithAllErrors(resultList) {
1459
+ return combineResultListWithAllErrors(resultList);
1460
+ }
1461
+ Result2.combineWithAllErrors = combineWithAllErrors;
1462
+ })(Result || (Result = {}));
1463
+ var ok = (value) => new Ok(value);
1464
+ var err = (err2) => new Err(err2);
1465
+ var Ok = class {
1466
+ constructor(value) {
1467
+ this.value = value;
1468
+ }
1469
+ isOk() {
1470
+ return true;
1471
+ }
1472
+ isErr() {
1473
+ return !this.isOk();
1474
+ }
1475
+ map(f) {
1476
+ return ok(f(this.value));
1477
+ }
1478
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1479
+ mapErr(_f) {
1480
+ return ok(this.value);
1481
+ }
1482
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1483
+ andThen(f) {
1484
+ return f(this.value);
1485
+ }
1486
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1487
+ orElse(_f) {
1488
+ return ok(this.value);
1489
+ }
1490
+ asyncAndThen(f) {
1491
+ return f(this.value);
1492
+ }
1493
+ asyncMap(f) {
1494
+ return ResultAsync.fromSafePromise(f(this.value));
1495
+ }
1496
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1497
+ unwrapOr(_v) {
1498
+ return this.value;
1499
+ }
1500
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1501
+ match(ok2, _err) {
1502
+ return ok2(this.value);
1503
+ }
1504
+ safeUnwrap() {
1505
+ const value = this.value;
1506
+ return function* () {
1507
+ return value;
1508
+ }();
1509
+ }
1510
+ _unsafeUnwrap(_) {
1511
+ return this.value;
1512
+ }
1513
+ _unsafeUnwrapErr(config) {
1514
+ throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
1515
+ }
1516
+ };
1517
+ var Err = class {
1518
+ constructor(error) {
1519
+ this.error = error;
1520
+ }
1521
+ isOk() {
1522
+ return false;
1523
+ }
1524
+ isErr() {
1525
+ return !this.isOk();
1526
+ }
1527
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1528
+ map(_f) {
1529
+ return err(this.error);
1530
+ }
1531
+ mapErr(f) {
1532
+ return err(f(this.error));
1533
+ }
1534
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1535
+ andThen(_f) {
1536
+ return err(this.error);
1537
+ }
1538
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1539
+ orElse(f) {
1540
+ return f(this.error);
1541
+ }
1542
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1543
+ asyncAndThen(_f) {
1544
+ return errAsync(this.error);
1545
+ }
1546
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1547
+ asyncMap(_f) {
1548
+ return errAsync(this.error);
1549
+ }
1550
+ unwrapOr(v) {
1551
+ return v;
1552
+ }
1553
+ match(_ok, err2) {
1554
+ return err2(this.error);
1555
+ }
1556
+ safeUnwrap() {
1557
+ const error = this.error;
1558
+ return function* () {
1559
+ yield err(error);
1560
+ throw new Error("Do not use this generator out of `safeTry`");
1561
+ }();
1562
+ }
1563
+ _unsafeUnwrap(config) {
1564
+ throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
1565
+ }
1566
+ _unsafeUnwrapErr(_) {
1567
+ return this.error;
1568
+ }
1569
+ };
1570
+ var fromThrowable = Result.fromThrowable;
1571
+
1572
+ // src/client/workflow/types.ts
1573
+ var StepTypes = ["Initial", "Run", "SleepFor", "SleepUntil", "Call"];
1574
+
1575
+ // src/client/workflow/workflow-requests.ts
1576
+ var triggerFirstInvocation = async (workflowContext, retries, debug) => {
1577
+ const headers = getHeaders(
1578
+ "true",
1579
+ workflowContext.workflowRunId,
1580
+ workflowContext.url,
1581
+ workflowContext.headers,
1582
+ void 0,
1583
+ workflowContext.failureUrl,
1584
+ retries
1585
+ );
1586
+ await debug?.log("SUBMIT", "SUBMIT_FIRST_INVOCATION", {
1587
+ headers,
1588
+ requestPayload: workflowContext.requestPayload,
1589
+ url: workflowContext.url
1590
+ });
1591
+ try {
1592
+ await workflowContext.qstashClient.publishJSON({
1593
+ headers,
1594
+ method: "POST",
1595
+ body: workflowContext.requestPayload,
1596
+ url: workflowContext.url
1597
+ });
1598
+ return ok("success");
1599
+ } catch (error) {
1600
+ const error_ = error;
1601
+ return err(error_);
1602
+ }
1603
+ };
1604
+ var triggerRouteFunction = async ({
1605
+ onCleanup,
1606
+ onStep
1607
+ }) => {
1608
+ try {
1609
+ await onStep();
1610
+ await onCleanup();
1611
+ return ok("workflow-finished");
1612
+ } catch (error) {
1613
+ const error_ = error;
1614
+ return error_ instanceof QStashWorkflowAbort ? ok("step-finished") : err(error_);
1615
+ }
1616
+ };
1617
+ var triggerWorkflowDelete = async (workflowContext, debug, cancel = false) => {
1618
+ await debug?.log("SUBMIT", "SUBMIT_CLEANUP", {
1619
+ deletedWorkflowRunId: workflowContext.workflowRunId
1620
+ });
1621
+ const result = await workflowContext.qstashClient.http.request({
1622
+ path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
1623
+ method: "DELETE",
1624
+ parseResponseAsJson: false
1625
+ });
1626
+ await debug?.log("SUBMIT", "SUBMIT_CLEANUP", result);
1627
+ };
1628
+ var recreateUserHeaders = (headers) => {
1629
+ const filteredHeaders = new Headers();
1630
+ const pairs = headers.entries();
1631
+ for (const [header, value] of pairs) {
1632
+ const headerLowerCase = header.toLowerCase();
1633
+ if (!headerLowerCase.startsWith("upstash-workflow-") && !headerLowerCase.startsWith("x-vercel-") && !headerLowerCase.startsWith("x-forwarded-") && headerLowerCase !== "cf-connecting-ip") {
1634
+ filteredHeaders.append(header, value);
1635
+ }
1636
+ }
1637
+ return filteredHeaders;
1638
+ };
1639
+ var handleThirdPartyCallResult = async (request, requestPayload, client, workflowUrl, failureUrl, retries, debug) => {
1640
+ try {
1641
+ if (request.headers.get("Upstash-Workflow-Callback")) {
1642
+ const callbackMessage = JSON.parse(requestPayload);
1643
+ if (!(callbackMessage.status >= 200 && callbackMessage.status < 300)) {
1644
+ await debug?.log("WARN", "SUBMIT_THIRD_PARTY_RESULT", {
1645
+ status: callbackMessage.status,
1646
+ body: decodeBase64(callbackMessage.body)
1647
+ });
1648
+ console.warn(
1649
+ `Workflow Warning: "context.call" failed with status ${callbackMessage.status} and will retry (if there are retries remaining). Error Message:
1650
+ ${decodeBase64(callbackMessage.body)}`
1651
+ );
1652
+ return ok("call-will-retry");
1653
+ }
1654
+ const workflowRunId = request.headers.get(WORKFLOW_ID_HEADER);
1655
+ const stepIdString = request.headers.get("Upstash-Workflow-StepId");
1656
+ const stepName = request.headers.get("Upstash-Workflow-StepName");
1657
+ const stepType = request.headers.get("Upstash-Workflow-StepType");
1658
+ const concurrentString = request.headers.get("Upstash-Workflow-Concurrent");
1659
+ const contentType = request.headers.get("Upstash-Workflow-ContentType");
1660
+ if (!(workflowRunId && stepIdString && stepName && StepTypes.includes(stepType) && concurrentString && contentType)) {
1661
+ throw new Error(
1662
+ `Missing info in callback message source header: ${JSON.stringify({
1663
+ workflowRunId,
1664
+ stepIdString,
1665
+ stepName,
1666
+ stepType,
1667
+ concurrentString,
1668
+ contentType
1669
+ })}`
1670
+ );
1671
+ }
1672
+ const userHeaders = recreateUserHeaders(request.headers);
1673
+ const requestHeaders = getHeaders(
1674
+ "false",
1675
+ workflowRunId,
1676
+ workflowUrl,
1677
+ userHeaders,
1678
+ void 0,
1679
+ failureUrl,
1680
+ retries
1681
+ );
1682
+ const callResultStep = {
1683
+ stepId: Number(stepIdString),
1684
+ stepName,
1685
+ stepType,
1686
+ out: decodeBase64(callbackMessage.body),
1687
+ concurrent: Number(concurrentString)
1688
+ };
1689
+ await debug?.log("SUBMIT", "SUBMIT_THIRD_PARTY_RESULT", {
1690
+ step: callResultStep,
1691
+ headers: requestHeaders,
1692
+ url: workflowUrl
1693
+ });
1694
+ const result = await client.publishJSON({
1695
+ headers: requestHeaders,
1696
+ method: "POST",
1697
+ body: callResultStep,
1698
+ url: workflowUrl
1699
+ });
1700
+ await debug?.log("SUBMIT", "SUBMIT_THIRD_PARTY_RESULT", {
1701
+ messageId: result.messageId
1702
+ });
1703
+ return ok("is-call-return");
1704
+ } else {
1705
+ return ok("continue-workflow");
1706
+ }
1707
+ } catch (error) {
1708
+ const isCallReturn = request.headers.get("Upstash-Workflow-Callback");
1709
+ return err(
1710
+ new QStashWorkflowError(
1711
+ `Error when handling call return (isCallReturn=${isCallReturn}): ${error}`
1712
+ )
1713
+ );
1714
+ }
1715
+ };
1716
+ var getHeaders = (initHeaderValue, workflowRunId, workflowUrl, userHeaders, step, failureUrl, retries) => {
1717
+ const baseHeaders = {
1718
+ [WORKFLOW_INIT_HEADER]: initHeaderValue,
1719
+ [WORKFLOW_ID_HEADER]: workflowRunId,
1720
+ [WORKFLOW_URL_HEADER]: workflowUrl,
1721
+ [`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`]: WORKFLOW_PROTOCOL_VERSION,
1722
+ ...failureUrl ? {
1723
+ [`Upstash-Failure-Callback-Forward-${WORKFLOW_FAILURE_HEADER}`]: "true",
1724
+ "Upstash-Failure-Callback": failureUrl
1725
+ } : {},
1726
+ ...retries === void 0 ? {} : {
1727
+ "Upstash-Retries": retries.toString()
1728
+ }
1729
+ };
1730
+ if (userHeaders) {
1731
+ for (const header of userHeaders.keys()) {
1732
+ if (step?.callHeaders) {
1733
+ baseHeaders[`Upstash-Callback-Forward-${header}`] = userHeaders.get(header);
1734
+ } else {
1735
+ baseHeaders[`Upstash-Forward-${header}`] = userHeaders.get(header);
1736
+ }
1737
+ }
1738
+ }
1739
+ if (step?.callHeaders) {
1740
+ const forwardedHeaders = Object.fromEntries(
1741
+ Object.entries(step.callHeaders).map(([header, value]) => [
1742
+ `Upstash-Forward-${header}`,
1743
+ value
1744
+ ])
1745
+ );
1746
+ const contentType = step.callHeaders["Content-Type"];
1747
+ return {
1748
+ ...baseHeaders,
1749
+ ...forwardedHeaders,
1750
+ "Upstash-Callback": workflowUrl,
1751
+ "Upstash-Callback-Workflow-RunId": workflowRunId,
1752
+ "Upstash-Callback-Workflow-CallType": "fromCallback",
1753
+ "Upstash-Callback-Workflow-Init": "false",
1754
+ "Upstash-Callback-Workflow-Url": workflowUrl,
1755
+ "Upstash-Callback-Forward-Upstash-Workflow-Callback": "true",
1756
+ "Upstash-Callback-Forward-Upstash-Workflow-StepId": step.stepId.toString(),
1757
+ "Upstash-Callback-Forward-Upstash-Workflow-StepName": step.stepName,
1758
+ "Upstash-Callback-Forward-Upstash-Workflow-StepType": step.stepType,
1759
+ "Upstash-Callback-Forward-Upstash-Workflow-Concurrent": step.concurrent.toString(),
1760
+ "Upstash-Callback-Forward-Upstash-Workflow-ContentType": contentType ?? DEFAULT_CONTENT_TYPE,
1761
+ "Upstash-Workflow-CallType": "toCallback"
1762
+ };
1763
+ }
1764
+ return baseHeaders;
1765
+ };
1766
+ var verifyRequest = async (body, signature, verifier) => {
1767
+ if (!verifier) {
1768
+ return;
1769
+ }
1770
+ try {
1771
+ if (!signature) {
1772
+ throw new Error("`Upstash-Signature` header is not passed.");
1773
+ }
1774
+ const isValid = await verifier.verify({
1775
+ body,
1776
+ signature
1777
+ });
1778
+ if (!isValid) {
1779
+ throw new Error("Signature in `Upstash-Signature` header is not valid");
1780
+ }
1781
+ } catch (error) {
1782
+ throw new QStashWorkflowError(
1783
+ `Failed to verify that the Workflow request comes from QStash: ${error}
1784
+
1785
+ If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
1786
+
1787
+ If you want to disable QStash Verification, you should clear env variables QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY`
1788
+ );
1789
+ }
1790
+ };
1791
+
1792
+ // src/client/workflow/auto-executor.ts
1793
+ var AutoExecutor = class _AutoExecutor {
1794
+ context;
1795
+ promises = /* @__PURE__ */ new WeakMap();
1796
+ activeLazyStepList;
1797
+ debug;
1798
+ nonPlanStepCount;
1799
+ steps;
1800
+ indexInCurrentList = 0;
1801
+ stepCount = 0;
1802
+ planStepCount = 0;
1803
+ executingStep = false;
1804
+ constructor(context, steps, debug) {
1805
+ this.context = context;
1806
+ this.debug = debug;
1807
+ this.steps = steps;
1808
+ this.nonPlanStepCount = this.steps.filter((step) => !step.targetStep).length;
1809
+ }
1810
+ /**
1811
+ * Adds the step function to the list of step functions to run in
1812
+ * parallel. After adding the function, defers the execution, so
1813
+ * that if there is another step function to be added, it's also
1814
+ * added.
1815
+ *
1816
+ * After all functions are added, list of functions are executed.
1817
+ * If there is a single function, it's executed by itself. If there
1818
+ * are multiple, they are run in parallel.
1819
+ *
1820
+ * If a function is already executing (this.executingStep), this
1821
+ * means that there is a nested step which is not allowed. In this
1822
+ * case, addStep throws QStashWorkflowError.
1823
+ *
1824
+ * @param stepInfo step plan to add
1825
+ * @returns result of the step function
1826
+ */
1827
+ async addStep(stepInfo) {
1828
+ if (this.executingStep) {
1829
+ throw new QStashWorkflowError(
1830
+ `A step can not be run inside another step. Tried to run '${stepInfo.stepName}' inside '${this.executingStep}'`
1831
+ );
1832
+ }
1833
+ this.stepCount += 1;
1834
+ const lazyStepList = this.activeLazyStepList ?? [];
1835
+ if (!this.activeLazyStepList) {
1836
+ this.activeLazyStepList = lazyStepList;
1837
+ this.indexInCurrentList = 0;
1838
+ }
1839
+ lazyStepList.push(stepInfo);
1840
+ const index = this.indexInCurrentList++;
1841
+ const requestComplete = this.deferExecution().then(async () => {
1842
+ if (!this.promises.has(lazyStepList)) {
1843
+ const promise2 = this.getExecutionPromise(lazyStepList);
1844
+ this.promises.set(lazyStepList, promise2);
1845
+ this.activeLazyStepList = void 0;
1846
+ this.planStepCount += lazyStepList.length > 1 ? lazyStepList.length : 0;
1847
+ }
1848
+ const promise = this.promises.get(lazyStepList);
1849
+ return promise;
1850
+ });
1851
+ const result = await requestComplete;
1852
+ return _AutoExecutor.getResult(lazyStepList, result, index);
1853
+ }
1854
+ /**
1855
+ * Wraps a step function to set this.executingStep to step name
1856
+ * before running and set this.executingStep to False after execution
1857
+ * ends.
1858
+ *
1859
+ * this.executingStep allows us to detect nested steps which are not
1860
+ * allowed.
1861
+ *
1862
+ * @param stepName name of the step being wrapped
1863
+ * @param stepFunction step function to wrap
1864
+ * @returns wrapped step function
1865
+ */
1866
+ wrapStep(stepName, stepFunction) {
1867
+ this.executingStep = stepName;
1868
+ const result = stepFunction();
1869
+ this.executingStep = false;
1870
+ return result;
1871
+ }
1872
+ /**
1873
+ * Executes a step:
1874
+ * - If the step result is available in the steps, returns the result
1875
+ * - If the result is not avaiable, runs the function
1876
+ * - Sends the result to QStash
1877
+ *
1878
+ * @param lazyStep lazy step to execute
1879
+ * @returns step result
1880
+ */
1881
+ async runSingle(lazyStep) {
1882
+ if (this.stepCount < this.nonPlanStepCount) {
1883
+ const step = this.steps[this.stepCount + this.planStepCount];
1884
+ validateStep(lazyStep, step);
1885
+ await this.debug?.log("INFO", "RUN_SINGLE", {
1886
+ fromRequest: true,
1887
+ step,
1888
+ stepCount: this.stepCount
1889
+ });
1890
+ return step.out;
1891
+ }
1892
+ const resultStep = await lazyStep.getResultStep(NO_CONCURRENCY, this.stepCount);
1893
+ await this.debug?.log("INFO", "RUN_SINGLE", {
1894
+ fromRequest: false,
1895
+ step: resultStep,
1896
+ stepCount: this.stepCount
1897
+ });
1898
+ await this.submitStepsToQStash([resultStep]);
1899
+ return resultStep.out;
1900
+ }
1901
+ /**
1902
+ * Runs steps in parallel.
1903
+ *
1904
+ * @param stepName parallel step name
1905
+ * @param stepFunctions list of async functions to run in parallel
1906
+ * @returns results of the functions run in parallel
1907
+ */
1908
+ async runParallel(parallelSteps) {
1909
+ const initialStepCount = this.stepCount - (parallelSteps.length - 1);
1910
+ const parallelCallState = this.getParallelCallState(parallelSteps.length, initialStepCount);
1911
+ const sortedSteps = sortSteps(this.steps);
1912
+ const plannedParallelStepCount = sortedSteps[initialStepCount + this.planStepCount]?.concurrent;
1913
+ if (parallelCallState !== "first" && plannedParallelStepCount !== parallelSteps.length) {
1914
+ throw new QStashWorkflowError(
1915
+ `Incompatible number of parallel steps when call state was '${parallelCallState}'. Expected ${parallelSteps.length}, got ${plannedParallelStepCount} from the request.`
1916
+ );
1917
+ }
1918
+ await this.debug?.log("INFO", "RUN_PARALLEL", {
1919
+ parallelCallState,
1920
+ initialStepCount,
1921
+ plannedParallelStepCount,
1922
+ stepCount: this.stepCount,
1923
+ planStepCount: this.planStepCount
1924
+ });
1925
+ switch (parallelCallState) {
1926
+ case "first": {
1927
+ const planSteps = parallelSteps.map(
1928
+ (parallelStep, index) => parallelStep.getPlanStep(parallelSteps.length, initialStepCount + index)
1929
+ );
1930
+ await this.submitStepsToQStash(planSteps);
1931
+ break;
1932
+ }
1933
+ case "partial": {
1934
+ const planStep = this.steps.at(-1);
1935
+ if (!planStep || planStep.targetStep === void 0) {
1936
+ throw new QStashWorkflowError(
1937
+ `There must be a last step and it should have targetStep larger than 0.Received: ${JSON.stringify(planStep)}`
1938
+ );
1939
+ }
1940
+ const stepIndex = planStep.targetStep - initialStepCount;
1941
+ validateStep(parallelSteps[stepIndex], planStep);
1942
+ try {
1943
+ const resultStep = await parallelSteps[stepIndex].getResultStep(
1944
+ parallelSteps.length,
1945
+ planStep.targetStep
1946
+ );
1947
+ await this.submitStepsToQStash([resultStep]);
1948
+ } catch (error) {
1949
+ if (error instanceof QStashWorkflowAbort) {
1950
+ throw error;
1951
+ }
1952
+ throw new QStashWorkflowError(
1953
+ `Error submitting steps to QStash in partial parallel step execution: ${error}`
1954
+ );
1955
+ }
1956
+ break;
1957
+ }
1958
+ case "discard": {
1959
+ throw new QStashWorkflowAbort("discarded parallel");
1960
+ }
1961
+ case "last": {
1962
+ const parallelResultSteps = sortedSteps.filter((step) => step.stepId >= initialStepCount).slice(0, parallelSteps.length);
1963
+ validateParallelSteps(parallelSteps, parallelResultSteps);
1964
+ return parallelResultSteps.map((step) => step.out);
1965
+ }
1966
+ }
1967
+ const fillValue = void 0;
1968
+ return Array.from({ length: parallelSteps.length }).fill(fillValue);
1969
+ }
1970
+ /**
1971
+ * Determines the parallel call state
1972
+ *
1973
+ * First filters the steps to get the steps which are after `initialStepCount` parameter.
1974
+ *
1975
+ * Depending on the remaining steps, decides the parallel state:
1976
+ * - "first": If there are no steps
1977
+ * - "last" If there are equal to or more than `2 * parallelStepCount`. We multiply by two
1978
+ * because each step in a parallel execution will have 2 steps: a plan step and a result
1979
+ * step.
1980
+ * - "partial": If the last step is a plan step
1981
+ * - "discard": If the last step is not a plan step. This means that the parallel execution
1982
+ * is in progress (there are still steps to run) and one step has finished and submitted
1983
+ * its result to QStash
1984
+ *
1985
+ * @param parallelStepCount number of steps to run in parallel
1986
+ * @param initialStepCount steps after the parallel invocation
1987
+ * @returns parallel call state
1988
+ */
1989
+ getParallelCallState(parallelStepCount, initialStepCount) {
1990
+ const remainingSteps = this.steps.filter(
1991
+ (step) => (step.targetStep ?? step.stepId) >= initialStepCount
1992
+ );
1993
+ if (remainingSteps.length === 0) {
1994
+ return "first";
1995
+ } else if (remainingSteps.length >= 2 * parallelStepCount) {
1996
+ return "last";
1997
+ } else if (remainingSteps.at(-1)?.targetStep) {
1998
+ return "partial";
1999
+ } else {
2000
+ return "discard";
2001
+ }
2002
+ }
2003
+ /**
2004
+ * sends the steps to QStash as batch
2005
+ *
2006
+ * @param steps steps to send
2007
+ */
2008
+ async submitStepsToQStash(steps) {
2009
+ if (steps.length === 0) {
2010
+ throw new QStashWorkflowError(
2011
+ `Unable to submit steps to QStash. Provided list is empty. Current step: ${this.stepCount}`
2012
+ );
2013
+ }
2014
+ await this.debug?.log("SUBMIT", "SUBMIT_STEP", { length: steps.length, steps });
2015
+ const result = await this.context.qstashClient.batchJSON(
2016
+ steps.map((singleStep) => {
2017
+ const headers = getHeaders(
2018
+ "false",
2019
+ this.context.workflowRunId,
2020
+ this.context.url,
2021
+ this.context.headers,
2022
+ singleStep,
2023
+ this.context.failureUrl,
2024
+ this.context.retries
2025
+ );
2026
+ const willWait = singleStep.concurrent === NO_CONCURRENCY || singleStep.stepId === 0;
2027
+ return singleStep.callUrl ? (
2028
+ // if the step is a third party call, we call the third party
2029
+ // url (singleStep.callUrl) and pass information about the workflow
2030
+ // in the headers (handled in getHeaders). QStash makes the request
2031
+ // to callUrl and returns the result to Workflow endpoint.
2032
+ // handleThirdPartyCallResult method sends the result of the third
2033
+ // party call to QStash.
2034
+ {
2035
+ headers,
2036
+ method: singleStep.callMethod,
2037
+ body: singleStep.callBody,
2038
+ url: singleStep.callUrl
2039
+ }
2040
+ ) : (
2041
+ // if the step is not a third party call, we use workflow
2042
+ // endpoint (context.url) as URL when calling QStash. QStash
2043
+ // calls us back with the updated steps list.
2044
+ {
2045
+ headers,
2046
+ method: "POST",
2047
+ body: singleStep,
2048
+ url: this.context.url,
2049
+ notBefore: willWait ? singleStep.sleepUntil : void 0,
2050
+ delay: willWait ? singleStep.sleepFor : void 0
2051
+ }
2052
+ );
2053
+ })
2054
+ );
2055
+ await this.debug?.log("INFO", "SUBMIT_STEP", {
2056
+ messageIds: result.map((message) => {
2057
+ return {
2058
+ message: message.messageId
2059
+ };
2060
+ })
2061
+ });
2062
+ throw new QStashWorkflowAbort(steps[0].stepName, steps[0]);
2063
+ }
2064
+ /**
2065
+ * Get the promise by executing the lazt steps list. If there is a single
2066
+ * step, we call `runSingle`. Otherwise `runParallel` is called.
2067
+ *
2068
+ * @param lazyStepList steps list to execute
2069
+ * @returns promise corresponding to the execution
2070
+ */
2071
+ getExecutionPromise(lazyStepList) {
2072
+ return lazyStepList.length === 1 ? this.runSingle(lazyStepList[0]) : this.runParallel(lazyStepList);
2073
+ }
2074
+ /**
2075
+ * @param lazyStepList steps we executed
2076
+ * @param result result of the promise from `getExecutionPromise`
2077
+ * @param index index of the current step
2078
+ * @returns result[index] if lazyStepList > 1, otherwise result
2079
+ */
2080
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2081
+ static getResult(lazyStepList, result, index) {
2082
+ if (lazyStepList.length === 1) {
2083
+ return result;
2084
+ } else if (Array.isArray(result) && lazyStepList.length === result.length && index < lazyStepList.length) {
2085
+ return result[index];
2086
+ } else {
2087
+ throw new QStashWorkflowError(
2088
+ `Unexpected parallel call result while executing step ${index}: '${result}'. Expected ${lazyStepList.length} many items`
2089
+ );
2090
+ }
2091
+ }
2092
+ async deferExecution() {
2093
+ await Promise.resolve();
2094
+ await Promise.resolve();
2095
+ }
2096
+ };
2097
+ var validateStep = (lazyStep, stepFromRequest) => {
2098
+ if (lazyStep.stepName !== stepFromRequest.stepName) {
2099
+ throw new QStashWorkflowError(
2100
+ `Incompatible step name. Expected '${lazyStep.stepName}', got '${stepFromRequest.stepName}' from the request`
2101
+ );
2102
+ }
2103
+ if (lazyStep.stepType !== stepFromRequest.stepType) {
2104
+ throw new QStashWorkflowError(
2105
+ `Incompatible step type. Expected '${lazyStep.stepType}', got '${stepFromRequest.stepType}' from the request`
2106
+ );
2107
+ }
2108
+ };
2109
+ var validateParallelSteps = (lazySteps, stepsFromRequest) => {
2110
+ try {
2111
+ for (const [index, stepFromRequest] of stepsFromRequest.entries()) {
2112
+ validateStep(lazySteps[index], stepFromRequest);
2113
+ }
2114
+ } catch (error) {
2115
+ if (error instanceof QStashWorkflowError) {
2116
+ const lazyStepNames = lazySteps.map((lazyStep) => lazyStep.stepName);
2117
+ const lazyStepTypes = lazySteps.map((lazyStep) => lazyStep.stepType);
2118
+ const requestStepNames = stepsFromRequest.map((step) => step.stepName);
2119
+ const requestStepTypes = stepsFromRequest.map((step) => step.stepType);
2120
+ throw new QStashWorkflowError(
2121
+ `Incompatible steps detected in parallel execution: ${error.message}
2122
+ > Step Names from the request: ${JSON.stringify(requestStepNames)}
2123
+ Step Types from the request: ${JSON.stringify(requestStepTypes)}
2124
+ > Step Names expected: ${JSON.stringify(lazyStepNames)}
2125
+ Step Types expected: ${JSON.stringify(lazyStepTypes)}`
2126
+ );
2127
+ }
2128
+ throw error;
2129
+ }
2130
+ };
2131
+ var sortSteps = (steps) => {
2132
+ const getStepId = (step) => step.targetStep ?? step.stepId;
2133
+ return steps.toSorted((step, stepOther) => getStepId(step) - getStepId(stepOther));
2134
+ };
2135
+
2136
+ // src/client/workflow/steps.ts
2137
+ var BaseLazyStep = class {
2138
+ stepName;
2139
+ // will be set in the subclasses
2140
+ constructor(stepName) {
2141
+ this.stepName = stepName;
2142
+ }
2143
+ };
2144
+ var LazyFunctionStep = class extends BaseLazyStep {
2145
+ stepFunction;
2146
+ stepType = "Run";
2147
+ constructor(stepName, stepFunction) {
2148
+ super(stepName);
2149
+ this.stepFunction = stepFunction;
2150
+ }
2151
+ getPlanStep(concurrent, targetStep) {
2152
+ {
2153
+ return {
2154
+ stepId: 0,
2155
+ stepName: this.stepName,
2156
+ stepType: this.stepType,
2157
+ concurrent,
2158
+ targetStep
2159
+ };
2160
+ }
2161
+ }
2162
+ async getResultStep(concurrent, stepId) {
2163
+ let result = this.stepFunction();
2164
+ if (result instanceof Promise) {
2165
+ result = await result;
2166
+ }
2167
+ return {
2168
+ stepId,
2169
+ stepName: this.stepName,
2170
+ stepType: this.stepType,
2171
+ out: result,
2172
+ concurrent
2173
+ };
2174
+ }
2175
+ };
2176
+ var LazySleepStep = class extends BaseLazyStep {
2177
+ sleep;
2178
+ stepType = "SleepFor";
2179
+ constructor(stepName, sleep) {
2180
+ super(stepName);
2181
+ this.sleep = sleep;
2182
+ }
2183
+ getPlanStep(concurrent, targetStep) {
2184
+ {
2185
+ return {
2186
+ stepId: 0,
2187
+ stepName: this.stepName,
2188
+ stepType: this.stepType,
2189
+ sleepFor: this.sleep,
2190
+ concurrent,
2191
+ targetStep
2192
+ };
2193
+ }
2194
+ }
2195
+ async getResultStep(concurrent, stepId) {
2196
+ return await Promise.resolve({
2197
+ stepId,
2198
+ stepName: this.stepName,
2199
+ stepType: this.stepType,
2200
+ sleepFor: this.sleep,
2201
+ concurrent
2202
+ });
2203
+ }
2204
+ };
2205
+ var LazySleepUntilStep = class extends BaseLazyStep {
2206
+ sleepUntil;
2207
+ stepType = "SleepUntil";
2208
+ constructor(stepName, sleepUntil) {
2209
+ super(stepName);
2210
+ this.sleepUntil = sleepUntil;
2211
+ }
2212
+ getPlanStep(concurrent, targetStep) {
2213
+ {
2214
+ return {
2215
+ stepId: 0,
2216
+ stepName: this.stepName,
2217
+ stepType: this.stepType,
2218
+ sleepUntil: this.sleepUntil,
2219
+ concurrent,
2220
+ targetStep
2221
+ };
2222
+ }
2223
+ }
2224
+ async getResultStep(concurrent, stepId) {
2225
+ return await Promise.resolve({
2226
+ stepId,
2227
+ stepName: this.stepName,
2228
+ stepType: this.stepType,
2229
+ sleepUntil: this.sleepUntil,
2230
+ concurrent
2231
+ });
2232
+ }
2233
+ };
2234
+ var LazyCallStep = class extends BaseLazyStep {
2235
+ url;
2236
+ method;
2237
+ body;
2238
+ headers;
2239
+ stepType = "Call";
2240
+ constructor(stepName, url, method, body, headers) {
2241
+ super(stepName);
2242
+ this.url = url;
2243
+ this.method = method;
2244
+ this.body = body;
2245
+ this.headers = headers;
2246
+ }
2247
+ getPlanStep(concurrent, targetStep) {
2248
+ {
2249
+ return {
2250
+ stepId: 0,
2251
+ stepName: this.stepName,
2252
+ stepType: this.stepType,
2253
+ concurrent,
2254
+ targetStep
2255
+ };
2256
+ }
2257
+ }
2258
+ async getResultStep(concurrent, stepId) {
2259
+ return await Promise.resolve({
2260
+ stepId,
2261
+ stepName: this.stepName,
2262
+ stepType: this.stepType,
2263
+ concurrent,
2264
+ callUrl: this.url,
2265
+ callMethod: this.method,
2266
+ callBody: this.body,
2267
+ callHeaders: this.headers
2268
+ });
2269
+ }
2270
+ };
2271
+
2272
+ // src/client/workflow/context.ts
2273
+ var WorkflowContext = class {
2274
+ executor;
2275
+ steps;
2276
+ /**
2277
+ * QStash client of the workflow
2278
+ *
2279
+ * Can be overwritten by passing `qstashClient` parameter in `serve`:
2280
+ *
2281
+ * ```ts
2282
+ * import { Client } from "@upstash/qstash"
2283
+ *
2284
+ * export const POST = serve(
2285
+ * async (context) => {
2286
+ * ...
2287
+ * },
2288
+ * {
2289
+ * qstashClient: new Client({...})
2290
+ * }
2291
+ * )
2292
+ * ```
2293
+ */
2294
+ qstashClient;
2295
+ /**
2296
+ * Run id of the workflow
2297
+ */
2298
+ workflowRunId;
2299
+ /**
2300
+ * URL of the workflow
2301
+ *
2302
+ * Can be overwritten by passing a `url` parameter in `serve`:
2303
+ *
2304
+ * ```ts
2305
+ * export const POST = serve(
2306
+ * async (context) => {
2307
+ * ...
2308
+ * },
2309
+ * {
2310
+ * url: "new-url-value"
2311
+ * }
2312
+ * )
2313
+ * ```
2314
+ */
2315
+ url;
2316
+ /**
2317
+ * URL to call in case of workflow failure with QStash failure callback
2318
+ *
2319
+ * https://upstash.com/docs/qstash/features/callbacks#what-is-a-failure-callback
2320
+ *
2321
+ * Can be overwritten by passing a `failureUrl` parameter in `serve`:
2322
+ *
2323
+ * ```ts
2324
+ * export const POST = serve(
2325
+ * async (context) => {
2326
+ * ...
2327
+ * },
2328
+ * {
2329
+ * failureUrl: "new-url-value"
2330
+ * }
2331
+ * )
2332
+ * ```
2333
+ */
2334
+ failureUrl;
2335
+ /**
2336
+ * Payload of the request which started the workflow.
2337
+ *
2338
+ * To specify its type, you can define `serve` as follows:
2339
+ *
2340
+ * ```ts
2341
+ * // set requestPayload type to MyPayload:
2342
+ * export const POST = serve<MyPayload>(
2343
+ * async (context) => {
2344
+ * ...
2345
+ * }
2346
+ * )
2347
+ * ```
2348
+ *
2349
+ * By default, `serve` tries to apply `JSON.parse` to the request payload.
2350
+ * If your payload is encoded in a format other than JSON, you can utilize
2351
+ * the `initialPayloadParser` parameter:
2352
+ *
2353
+ * ```ts
2354
+ * export const POST = serve<MyPayload>(
2355
+ * async (context) => {
2356
+ * ...
2357
+ * },
2358
+ * {
2359
+ * initialPayloadParser: (initialPayload) => {return doSomething(initialPayload)}
2360
+ * }
2361
+ * )
2362
+ * ```
2363
+ */
2364
+ requestPayload;
2365
+ /**
2366
+ * headers of the initial request
2367
+ */
2368
+ headers;
2369
+ /**
2370
+ * initial payload as a raw string
2371
+ */
2372
+ rawInitialPayload;
2373
+ /**
2374
+ * Map of environment variables and their values.
2375
+ *
2376
+ * Can be set using the `env` option of serve:
2377
+ *
2378
+ * ```ts
2379
+ * export const POST = serve<MyPayload>(
2380
+ * async (context) => {
2381
+ * const key = context.env["API_KEY"];
2382
+ * },
2383
+ * {
2384
+ * env: {
2385
+ * "API_KEY": "*****";
2386
+ * }
2387
+ * }
2388
+ * )
2389
+ * ```
2390
+ *
2391
+ * Default value is set to `process.env`.
2392
+ */
2393
+ env;
2394
+ /**
2395
+ * Number of retries
2396
+ */
2397
+ retries;
2398
+ constructor({
2399
+ qstashClient,
2400
+ workflowRunId,
2401
+ headers,
2402
+ steps,
2403
+ url,
2404
+ failureUrl,
2405
+ debug,
2406
+ initialPayload,
2407
+ rawInitialPayload,
2408
+ env,
2409
+ retries
2410
+ }) {
2411
+ this.qstashClient = qstashClient;
2412
+ this.workflowRunId = workflowRunId;
2413
+ this.steps = steps;
2414
+ this.url = url;
2415
+ this.failureUrl = failureUrl;
2416
+ this.headers = headers;
2417
+ this.requestPayload = initialPayload;
2418
+ this.rawInitialPayload = rawInitialPayload ?? JSON.stringify(this.requestPayload);
2419
+ this.env = env ?? {};
2420
+ this.retries = retries ?? DEFAULT_RETRIES;
2421
+ this.executor = new AutoExecutor(this, this.steps, debug);
2422
+ }
2423
+ /**
2424
+ * Executes a workflow step
2425
+ *
2426
+ * ```typescript
2427
+ * const result = await context.run("step 1", () => {
2428
+ * return "result"
2429
+ * })
2430
+ * ```
2431
+ *
2432
+ * Can also be called in parallel and the steps will be executed
2433
+ * simulatenously:
2434
+ *
2435
+ * ```typescript
2436
+ * const [result1, result2] = await Promise.all([
2437
+ * context.run("step 1", () => {
2438
+ * return "result1"
2439
+ * })
2440
+ * context.run("step 2", async () => {
2441
+ * return await fetchResults()
2442
+ * })
2443
+ * ])
2444
+ * ```
2445
+ *
2446
+ * @param stepName name of the step
2447
+ * @param stepFunction step function to be executed
2448
+ * @returns result of the step function
2449
+ */
2450
+ async run(stepName, stepFunction) {
2451
+ const wrappedStepFunction = () => this.executor.wrapStep(stepName, stepFunction);
2452
+ return this.addStep(new LazyFunctionStep(stepName, wrappedStepFunction));
2453
+ }
2454
+ /**
2455
+ * Stops the execution for the duration provided.
2456
+ *
2457
+ * @param stepName
2458
+ * @param duration sleep duration in seconds
2459
+ * @returns undefined
2460
+ */
2461
+ async sleep(stepName, duration) {
2462
+ await this.addStep(new LazySleepStep(stepName, duration));
2463
+ }
2464
+ /**
2465
+ * Stops the execution until the date time provided.
2466
+ *
2467
+ * @param stepName
2468
+ * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
2469
+ * as a Date object or a string (passed to `new Date(datetimeString)`)
2470
+ * @returns undefined
2471
+ */
2472
+ async sleepUntil(stepName, datetime) {
2473
+ let time;
2474
+ if (typeof datetime === "number") {
2475
+ time = datetime;
2476
+ } else {
2477
+ datetime = typeof datetime === "string" ? new Date(datetime) : datetime;
2478
+ time = Math.round(datetime.getTime() / 1e3);
2479
+ }
2480
+ await this.addStep(new LazySleepUntilStep(stepName, time));
2481
+ }
2482
+ /**
2483
+ * Makes a third party call through QStash in order to make a
2484
+ * network call without consuming any runtime.
2485
+ *
2486
+ * ```ts
2487
+ * const postResult = await context.call<string>(
2488
+ * "post call step",
2489
+ * `https://www.some-endpoint.com/api`,
2490
+ * "POST",
2491
+ * "my-payload"
2492
+ * );
2493
+ * ```
2494
+ *
2495
+ * tries to parse the result of the request as JSON. If it's
2496
+ * not a JSON which can be parsed, simply returns the response
2497
+ * body as it is.
2498
+ *
2499
+ * @param stepName
2500
+ * @param url url to call
2501
+ * @param method call method
2502
+ * @param body call body
2503
+ * @param headers call headers
2504
+ * @returns call result (parsed as JSON if possible)
2505
+ */
2506
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
2507
+ async call(stepName, url, method, body, headers) {
2508
+ const result = await this.addStep(
2509
+ new LazyCallStep(stepName, url, method, body, headers ?? {})
2510
+ );
2511
+ try {
2512
+ return JSON.parse(result);
2513
+ } catch {
2514
+ return result;
2515
+ }
2516
+ }
2517
+ /**
2518
+ * Adds steps to the executor. Needed so that it can be overwritten in
2519
+ * DisabledWorkflowContext.
2520
+ */
2521
+ async addStep(step) {
2522
+ return await this.executor.addStep(step);
2523
+ }
2524
+ };
2525
+ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowContext {
2526
+ static disabledMessage = "disabled-qstash-worklfow-run";
2527
+ /**
2528
+ * overwrite the WorkflowContext.addStep method to always raise QStashWorkflowAbort
2529
+ * error in order to stop the execution whenever we encounter a step.
2530
+ *
2531
+ * @param _step
2532
+ */
2533
+ // eslint-disable-next-line @typescript-eslint/require-await
2534
+ async addStep(_step) {
2535
+ throw new QStashWorkflowAbort(_DisabledWorkflowContext.disabledMessage);
2536
+ }
2537
+ /**
2538
+ * copies the passed context to create a DisabledWorkflowContext. Then, runs the
2539
+ * route function with the new context.
2540
+ *
2541
+ * - returns "run-ended" if there are no steps found or
2542
+ * if the auth failed and user called `return`
2543
+ * - returns "step-found" if DisabledWorkflowContext.addStep is called.
2544
+ * - if there is another error, returns the error.
2545
+ *
2546
+ * @param routeFunction
2547
+ */
2548
+ static async tryAuthentication(routeFunction, context) {
2549
+ const disabledContext = new _DisabledWorkflowContext({
2550
+ qstashClient: new Client({ baseUrl: "disabled-client", token: "disabled-client" }),
2551
+ workflowRunId: context.workflowRunId,
2552
+ headers: context.headers,
2553
+ steps: [],
2554
+ url: context.url,
2555
+ failureUrl: context.failureUrl,
2556
+ initialPayload: context.requestPayload,
2557
+ rawInitialPayload: context.rawInitialPayload,
2558
+ env: context.env,
2559
+ retries: context.retries
2560
+ });
2561
+ try {
2562
+ await routeFunction(disabledContext);
2563
+ } catch (error) {
2564
+ if (error instanceof QStashWorkflowAbort && error.stepName === this.disabledMessage) {
2565
+ return ok("step-found");
2566
+ }
2567
+ return err(error);
2568
+ }
2569
+ return ok("run-ended");
2570
+ }
2571
+ };
2572
+
2573
+ // src/client/workflow/logger.ts
2574
+ var LOG_LEVELS = ["DEBUG", "INFO", "SUBMIT", "WARN", "ERROR"];
2575
+ var WorkflowLogger = class _WorkflowLogger {
2576
+ logs = [];
2577
+ options;
2578
+ workflowRunId = void 0;
2579
+ constructor(options) {
2580
+ this.options = options;
2581
+ }
2582
+ async log(level, eventType, details) {
2583
+ if (this.shouldLog(level)) {
2584
+ const timestamp = Date.now();
2585
+ const logEntry = {
2586
+ timestamp,
2587
+ workflowRunId: this.workflowRunId ?? "",
2588
+ logLevel: level,
2589
+ eventType,
2590
+ details
2591
+ };
2592
+ this.logs.push(logEntry);
2593
+ if (this.options.logOutput === "console") {
2594
+ this.writeToConsole(logEntry);
2595
+ }
2596
+ await new Promise((resolve) => setTimeout(resolve, 100));
2597
+ }
2598
+ }
2599
+ setWorkflowRunId(workflowRunId) {
2600
+ this.workflowRunId = workflowRunId;
2601
+ }
2602
+ writeToConsole(logEntry) {
2603
+ const JSON_SPACING = 2;
2604
+ console.log(JSON.stringify(logEntry, void 0, JSON_SPACING));
2605
+ }
2606
+ shouldLog(level) {
2607
+ return LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(this.options.logLevel);
2608
+ }
2609
+ static getLogger(verbose) {
2610
+ if (typeof verbose === "object") {
2611
+ return verbose;
2612
+ } else {
2613
+ return verbose ? new _WorkflowLogger({
2614
+ logLevel: "INFO",
2615
+ logOutput: "console"
2616
+ }) : void 0;
2617
+ }
2618
+ }
2619
+ };
2620
+
2621
+ // src/client/workflow/workflow-parser.ts
2622
+ var getPayload = async (request) => {
2623
+ try {
2624
+ return await request.text();
2625
+ } catch {
2626
+ return;
2627
+ }
2628
+ };
2629
+ var parsePayload = (rawPayload) => {
2630
+ const [encodedInitialPayload, ...encodedSteps] = JSON.parse(rawPayload);
2631
+ const rawInitialPayload = decodeBase64(encodedInitialPayload.body);
2632
+ const initialStep = {
2633
+ stepId: 0,
2634
+ stepName: "init",
2635
+ stepType: "Initial",
2636
+ out: rawInitialPayload,
2637
+ concurrent: NO_CONCURRENCY
2638
+ };
2639
+ const stepsToDecode = encodedSteps.filter((step) => step.callType === "step");
2640
+ const otherSteps = stepsToDecode.map((rawStep) => {
2641
+ return JSON.parse(decodeBase64(rawStep.body));
2642
+ });
2643
+ const steps = [initialStep, ...otherSteps];
2644
+ return {
2645
+ rawInitialPayload,
2646
+ steps
2647
+ };
2648
+ };
2649
+ var deduplicateSteps = (steps) => {
2650
+ const targetStepIds = [];
2651
+ const stepIds = [];
2652
+ const deduplicatedSteps = [];
2653
+ for (const step of steps) {
2654
+ if (step.stepId === 0) {
2655
+ if (!targetStepIds.includes(step.targetStep ?? 0)) {
2656
+ deduplicatedSteps.push(step);
2657
+ targetStepIds.push(step.targetStep ?? 0);
2658
+ }
2659
+ } else {
2660
+ if (!stepIds.includes(step.stepId)) {
2661
+ deduplicatedSteps.push(step);
2662
+ stepIds.push(step.stepId);
2663
+ }
2664
+ }
2665
+ }
2666
+ return deduplicatedSteps;
2667
+ };
2668
+ var checkIfLastOneIsDuplicate = async (steps, debug) => {
2669
+ if (steps.length < 2) {
2670
+ return false;
2671
+ }
2672
+ const lastStep = steps.at(-1);
2673
+ const lastStepId = lastStep.stepId;
2674
+ const lastTargetStepId = lastStep.targetStep;
2675
+ for (let index = 0; index < steps.length - 1; index++) {
2676
+ const step = steps[index];
2677
+ if (step.stepId === lastStepId && step.targetStep === lastTargetStepId) {
2678
+ const message = `QStash Workflow: The step '${step.stepName}' with id '${step.stepId}' has run twice during workflow execution. Rest of the workflow will continue running as usual.`;
2679
+ await debug?.log("WARN", "RESPONSE_DEFAULT", message);
2680
+ console.warn(message);
2681
+ return true;
2682
+ }
2683
+ }
2684
+ return false;
2685
+ };
2686
+ var validateRequest = (request) => {
2687
+ const versionHeader = request.headers.get(WORKFLOW_PROTOCOL_VERSION_HEADER);
2688
+ const isFirstInvocation = !versionHeader;
2689
+ if (!isFirstInvocation && versionHeader !== WORKFLOW_PROTOCOL_VERSION) {
2690
+ throw new QStashWorkflowError(
2691
+ `Incompatible workflow sdk protocol version. Expected ${WORKFLOW_PROTOCOL_VERSION}, got ${versionHeader} from the request.`
2692
+ );
2693
+ }
2694
+ const workflowRunId = isFirstInvocation ? `wfr_${nanoid()}` : request.headers.get(WORKFLOW_ID_HEADER) ?? "";
2695
+ if (workflowRunId.length === 0) {
2696
+ throw new QStashWorkflowError("Couldn't get workflow id from header");
2697
+ }
2698
+ return {
2699
+ isFirstInvocation,
2700
+ workflowRunId
2701
+ };
2702
+ };
2703
+ var parseRequest = async (requestPayload, isFirstInvocation, debug) => {
2704
+ if (isFirstInvocation) {
2705
+ return {
2706
+ rawInitialPayload: requestPayload ?? "",
2707
+ steps: [],
2708
+ isLastDuplicate: false
2709
+ };
2710
+ } else {
2711
+ if (!requestPayload) {
2712
+ throw new QStashWorkflowError("Only first call can have an empty body");
2713
+ }
2714
+ const { rawInitialPayload, steps } = parsePayload(requestPayload);
2715
+ const isLastDuplicate = await checkIfLastOneIsDuplicate(steps, debug);
2716
+ const deduplicatedSteps = deduplicateSteps(steps);
2717
+ return {
2718
+ rawInitialPayload,
2719
+ steps: deduplicatedSteps,
2720
+ isLastDuplicate
2721
+ };
2722
+ }
2723
+ };
2724
+ var handleFailure = async (request, requestPayload, qstashClient, initialPayloadParser, failureFunction, debug) => {
2725
+ if (request.headers.get(WORKFLOW_FAILURE_HEADER) !== "true") {
2726
+ return ok("not-failure-callback");
2727
+ }
2728
+ if (!failureFunction) {
2729
+ return err(
2730
+ new QStashWorkflowError(
2731
+ "Workflow endpoint is called to handle a failure, but a failureFunction is not provided in serve options. Either provide a failureUrl or a failureFunction."
2732
+ )
2733
+ );
2734
+ }
2735
+ try {
2736
+ const { status, header, body, url, sourceHeader, sourceBody, workflowRunId } = JSON.parse(
2737
+ requestPayload
2738
+ );
2739
+ const decodedBody = body ? decodeBase64(body) : "{}";
2740
+ const errorPayload = JSON.parse(decodedBody);
2741
+ const {
2742
+ rawInitialPayload,
2743
+ steps,
2744
+ isLastDuplicate: _isLastDuplicate
2745
+ } = await parseRequest(decodeBase64(sourceBody), false, debug);
2746
+ const workflowContext = new WorkflowContext({
2747
+ qstashClient,
2748
+ workflowRunId,
2749
+ initialPayload: initialPayloadParser(rawInitialPayload),
2750
+ rawInitialPayload,
2751
+ headers: recreateUserHeaders(new Headers(sourceHeader)),
2752
+ steps,
2753
+ url,
2754
+ failureUrl: url,
2755
+ debug
2756
+ });
2757
+ await failureFunction(workflowContext, status, errorPayload.message, header);
2758
+ } catch (error) {
2759
+ return err(error);
2760
+ }
2761
+ return ok("is-failure-callback");
2762
+ };
2763
+
2764
+ // src/client/workflow/serve.ts
2765
+ var processOptions = (options) => {
2766
+ const environment = options?.env ?? (typeof process === "undefined" ? {} : process.env);
2767
+ const receiverEnvironmentVariablesSet = Boolean(
2768
+ environment.QSTASH_CURRENT_SIGNING_KEY && environment.QSTASH_NEXT_SIGNING_KEY
2769
+ );
2770
+ return {
2771
+ qstashClient: new Client({
2772
+ baseUrl: environment.QSTASH_URL,
2773
+ token: environment.QSTASH_TOKEN
2774
+ }),
2775
+ onStepFinish: (workflowRunId, _finishCondition) => new Response(JSON.stringify({ workflowRunId }), {
2776
+ status: 200
2777
+ }),
2778
+ initialPayloadParser: (initialRequest) => {
2779
+ if (!initialRequest) {
2780
+ return void 0;
2781
+ }
2782
+ try {
2783
+ return JSON.parse(initialRequest);
2784
+ } catch (error) {
2785
+ if (error instanceof SyntaxError) {
2786
+ return initialRequest;
2787
+ }
2788
+ throw error;
2789
+ }
2790
+ },
2791
+ receiver: receiverEnvironmentVariablesSet ? new Receiver({
2792
+ currentSigningKey: environment.QSTASH_CURRENT_SIGNING_KEY,
2793
+ nextSigningKey: environment.QSTASH_NEXT_SIGNING_KEY
2794
+ }) : void 0,
2795
+ baseUrl: environment.UPSTASH_WORKFLOW_URL,
2796
+ env: environment,
2797
+ retries: DEFAULT_RETRIES,
2798
+ ...options
2799
+ };
2800
+ };
2801
+ var serve = (routeFunction, options) => {
2802
+ const {
2803
+ qstashClient,
2804
+ onStepFinish,
2805
+ initialPayloadParser,
2806
+ url,
2807
+ verbose,
2808
+ receiver,
2809
+ failureUrl,
2810
+ failureFunction,
2811
+ baseUrl,
2812
+ env,
2813
+ retries
2814
+ } = processOptions(options);
2815
+ const debug = WorkflowLogger.getLogger(verbose);
2816
+ const handler = async (request) => {
2817
+ const initialWorkflowUrl = url ?? request.url;
2818
+ const workflowUrl = baseUrl ? initialWorkflowUrl.replace(/^(https?:\/\/[^/]+)(\/.*)?$/, (_, matchedBaseUrl, path) => {
2819
+ return baseUrl + (path || "");
2820
+ }) : initialWorkflowUrl;
2821
+ if (workflowUrl !== initialWorkflowUrl) {
2822
+ await debug?.log("WARN", "ENDPOINT_START", {
2823
+ warning: `QStash Workflow: replacing the base of the url with "${baseUrl}" and using it as workflow endpoint.`,
2824
+ originalURL: initialWorkflowUrl,
2825
+ updatedURL: workflowUrl
2826
+ });
2827
+ }
2828
+ const workflowFailureUrl = failureFunction ? workflowUrl : failureUrl;
2829
+ const requestPayload = await getPayload(request) ?? "";
2830
+ await verifyRequest(requestPayload, request.headers.get("upstash-signature"), receiver);
2831
+ await debug?.log("INFO", "ENDPOINT_START");
2832
+ const failureCheck = await handleFailure(
2833
+ request,
2834
+ requestPayload,
2835
+ qstashClient,
2836
+ initialPayloadParser,
2837
+ failureFunction
2838
+ );
2839
+ if (failureCheck.isErr()) {
2840
+ throw failureCheck.error;
2841
+ } else if (failureCheck.value === "is-failure-callback") {
2842
+ await debug?.log("WARN", "RESPONSE_DEFAULT", "failureFunction executed");
2843
+ return onStepFinish("no-workflow-id", "failure-callback");
2844
+ }
2845
+ const { isFirstInvocation, workflowRunId } = validateRequest(request);
2846
+ debug?.setWorkflowRunId(workflowRunId);
2847
+ const { rawInitialPayload, steps, isLastDuplicate } = await parseRequest(
2848
+ requestPayload,
2849
+ isFirstInvocation,
2850
+ debug
2851
+ );
2852
+ if (isLastDuplicate) {
2853
+ return onStepFinish("no-workflow-id", "duplicate-step");
2854
+ }
2855
+ const workflowContext = new WorkflowContext({
2856
+ qstashClient,
2857
+ workflowRunId,
2858
+ initialPayload: initialPayloadParser(rawInitialPayload),
2859
+ rawInitialPayload,
2860
+ headers: recreateUserHeaders(request.headers),
2861
+ steps,
2862
+ url: workflowUrl,
2863
+ failureUrl: workflowFailureUrl,
2864
+ debug,
2865
+ env
2866
+ });
2867
+ const authCheck = await DisabledWorkflowContext.tryAuthentication(
2868
+ routeFunction,
2869
+ workflowContext
2870
+ );
2871
+ if (authCheck.isErr()) {
2872
+ await debug?.log("ERROR", "ERROR", { error: authCheck.error.message });
2873
+ throw authCheck.error;
2874
+ } else if (authCheck.value === "run-ended") {
2875
+ return onStepFinish("no-workflow-id", "auth-fail");
2876
+ }
2877
+ const callReturnCheck = await handleThirdPartyCallResult(
2878
+ request,
2879
+ rawInitialPayload,
2880
+ qstashClient,
2881
+ workflowUrl,
2882
+ workflowFailureUrl,
2883
+ retries,
2884
+ debug
2885
+ );
2886
+ if (callReturnCheck.isErr()) {
2887
+ await debug?.log("ERROR", "SUBMIT_THIRD_PARTY_RESULT", {
2888
+ error: callReturnCheck.error.message
2889
+ });
2890
+ throw callReturnCheck.error;
2891
+ } else if (callReturnCheck.value === "continue-workflow") {
2892
+ const result = isFirstInvocation ? await triggerFirstInvocation(workflowContext, retries, debug) : await triggerRouteFunction({
2893
+ onStep: async () => routeFunction(workflowContext),
2894
+ onCleanup: async () => {
2895
+ await triggerWorkflowDelete(workflowContext, debug);
2896
+ }
2897
+ });
2898
+ if (result.isErr()) {
2899
+ await debug?.log("ERROR", "ERROR", { error: result.error.message });
2900
+ throw result.error;
2901
+ }
2902
+ await debug?.log("INFO", "RESPONSE_WORKFLOW");
2903
+ return onStepFinish(workflowContext.workflowRunId, "success");
2904
+ }
2905
+ await debug?.log("INFO", "RESPONSE_DEFAULT");
2906
+ return onStepFinish("no-workflow-id", "fromCallback");
2907
+ };
2908
+ return async (request) => {
2909
+ try {
2910
+ return await handler(request);
2911
+ } catch (error) {
2912
+ console.error(error);
2913
+ return new Response(JSON.stringify(formatWorkflowError(error)), { status: 500 });
2914
+ }
2915
+ };
2916
+ };
2917
+
2918
+ // src/client/workflow/index.ts
2919
+ var Workflow = class {
2920
+ http;
2921
+ constructor(http) {
2922
+ this.http = http;
2923
+ }
2924
+ /**
2925
+ * Cancel an ongoing workflow
2926
+ *
2927
+ * @param workflowRunId run id of the workflow to delete
2928
+ * @returns true if workflow is succesfully deleted. Otherwise throws QStashError
2929
+ */
2930
+ async cancel(workflowRunId) {
2931
+ const result = await this.http.request({
2932
+ path: ["v2", "workflows", "runs", `${workflowRunId}?cancel=true`],
2933
+ method: "DELETE",
2934
+ parseResponseAsJson: false
2935
+ });
2936
+ return result ?? true;
2937
+ }
2938
+ };
2939
+
2940
+ // platforms/cloudflare.ts
2941
+ var getArgs = (args) => {
2942
+ if (!Array.isArray(args) || args.length === 0) {
2943
+ throw new Error("No arguments passed to serve handler");
2944
+ }
2945
+ if (typeof args[0] === "object" && "request" in args[0] && "env" in args[0]) {
2946
+ return {
2947
+ request: args[0].request,
2948
+ env: args[0].env
2949
+ };
2950
+ }
2951
+ if (args.length > 1 && typeof args[1] === "object") {
2952
+ return {
2953
+ request: args[0],
2954
+ env: args[1]
2955
+ };
2956
+ }
2957
+ throw new Error("Could not derive handler arguments from input. Please check how serve is used.");
2958
+ };
2959
+ var serve2 = (routeFunction, options) => {
2960
+ const handler = async (...args) => {
2961
+ const { request, env } = getArgs(args);
2962
+ const serveHandler = serve(routeFunction, {
2963
+ env,
2964
+ ...options
2965
+ });
2966
+ return await serveHandler(request);
2967
+ };
2968
+ return handler;
2969
+ };
2970
+ // Annotate the CommonJS export names for ESM import in node:
2971
+ 0 && (module.exports = {
2972
+ serve
2973
+ });