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