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