@upstash/workflow 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js ADDED
@@ -0,0 +1,2038 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ Client: () => Client3,
24
+ QStashWorkflowAbort: () => QStashWorkflowAbort,
25
+ QStashWorkflowError: () => QStashWorkflowError,
26
+ StepTypes: () => StepTypes,
27
+ WorkflowContext: () => WorkflowContext,
28
+ WorkflowLogger: () => WorkflowLogger,
29
+ serve: () => serve
30
+ });
31
+ module.exports = __toCommonJS(src_exports);
32
+
33
+ // src/error.ts
34
+ var import_qstash = require("@upstash/qstash");
35
+ var QStashWorkflowError = class extends import_qstash.QstashError {
36
+ constructor(message) {
37
+ super(message);
38
+ this.name = "QStashWorkflowError";
39
+ }
40
+ };
41
+ var QStashWorkflowAbort = class extends Error {
42
+ stepInfo;
43
+ stepName;
44
+ constructor(stepName, stepInfo) {
45
+ super(
46
+ `This is an Upstash 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}'.`
47
+ );
48
+ this.name = "QStashWorkflowAbort";
49
+ this.stepName = stepName;
50
+ this.stepInfo = stepInfo;
51
+ }
52
+ };
53
+ var formatWorkflowError = (error) => {
54
+ return error instanceof Error ? {
55
+ error: error.name,
56
+ message: error.message
57
+ } : {
58
+ error: "Error",
59
+ message: "An error occured while executing workflow."
60
+ };
61
+ };
62
+
63
+ // node_modules/neverthrow/dist/index.es.js
64
+ var defaultErrorConfig = {
65
+ withStackTrace: false
66
+ };
67
+ var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
68
+ const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
69
+ const maybeStack = config.withStackTrace ? new Error().stack : void 0;
70
+ return {
71
+ data,
72
+ message,
73
+ stack: maybeStack
74
+ };
75
+ };
76
+ function __awaiter(thisArg, _arguments, P, generator) {
77
+ function adopt(value) {
78
+ return value instanceof P ? value : new P(function(resolve) {
79
+ resolve(value);
80
+ });
81
+ }
82
+ return new (P || (P = Promise))(function(resolve, reject) {
83
+ function fulfilled(value) {
84
+ try {
85
+ step(generator.next(value));
86
+ } catch (e) {
87
+ reject(e);
88
+ }
89
+ }
90
+ function rejected(value) {
91
+ try {
92
+ step(generator["throw"](value));
93
+ } catch (e) {
94
+ reject(e);
95
+ }
96
+ }
97
+ function step(result) {
98
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
99
+ }
100
+ step((generator = generator.apply(thisArg, [])).next());
101
+ });
102
+ }
103
+ function __values(o) {
104
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
105
+ if (m) return m.call(o);
106
+ if (o && typeof o.length === "number") return {
107
+ next: function() {
108
+ if (o && i >= o.length) o = void 0;
109
+ return { value: o && o[i++], done: !o };
110
+ }
111
+ };
112
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
113
+ }
114
+ function __await(v) {
115
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
116
+ }
117
+ function __asyncGenerator(thisArg, _arguments, generator) {
118
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
119
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
120
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
121
+ return this;
122
+ }, i;
123
+ function verb(n) {
124
+ if (g[n]) i[n] = function(v) {
125
+ return new Promise(function(a, b) {
126
+ q.push([n, v, a, b]) > 1 || resume(n, v);
127
+ });
128
+ };
129
+ }
130
+ function resume(n, v) {
131
+ try {
132
+ step(g[n](v));
133
+ } catch (e) {
134
+ settle(q[0][3], e);
135
+ }
136
+ }
137
+ function step(r) {
138
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
139
+ }
140
+ function fulfill(value) {
141
+ resume("next", value);
142
+ }
143
+ function reject(value) {
144
+ resume("throw", value);
145
+ }
146
+ function settle(f, v) {
147
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
148
+ }
149
+ }
150
+ function __asyncDelegator(o) {
151
+ var i, p;
152
+ return i = {}, verb("next"), verb("throw", function(e) {
153
+ throw e;
154
+ }), verb("return"), i[Symbol.iterator] = function() {
155
+ return this;
156
+ }, i;
157
+ function verb(n, f) {
158
+ i[n] = o[n] ? function(v) {
159
+ return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
160
+ } : f;
161
+ }
162
+ }
163
+ function __asyncValues(o) {
164
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
165
+ var m = o[Symbol.asyncIterator], i;
166
+ 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() {
167
+ return this;
168
+ }, i);
169
+ function verb(n) {
170
+ i[n] = o[n] && function(v) {
171
+ return new Promise(function(resolve, reject) {
172
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
173
+ });
174
+ };
175
+ }
176
+ function settle(resolve, reject, d, v) {
177
+ Promise.resolve(v).then(function(v2) {
178
+ resolve({ value: v2, done: d });
179
+ }, reject);
180
+ }
181
+ }
182
+ var ResultAsync = class _ResultAsync {
183
+ constructor(res) {
184
+ this._promise = res;
185
+ }
186
+ static fromSafePromise(promise) {
187
+ const newPromise = promise.then((value) => new Ok(value));
188
+ return new _ResultAsync(newPromise);
189
+ }
190
+ static fromPromise(promise, errorFn) {
191
+ const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
192
+ return new _ResultAsync(newPromise);
193
+ }
194
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
195
+ static fromThrowable(fn, errorFn) {
196
+ return (...args) => {
197
+ return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
198
+ try {
199
+ return new Ok(yield fn(...args));
200
+ } catch (error) {
201
+ return new Err(errorFn ? errorFn(error) : error);
202
+ }
203
+ }))());
204
+ };
205
+ }
206
+ static combine(asyncResultList) {
207
+ return combineResultAsyncList(asyncResultList);
208
+ }
209
+ static combineWithAllErrors(asyncResultList) {
210
+ return combineResultAsyncListWithAllErrors(asyncResultList);
211
+ }
212
+ map(f) {
213
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
214
+ if (res.isErr()) {
215
+ return new Err(res.error);
216
+ }
217
+ return new Ok(yield f(res.value));
218
+ })));
219
+ }
220
+ andThrough(f) {
221
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
222
+ if (res.isErr()) {
223
+ return new Err(res.error);
224
+ }
225
+ const newRes = yield f(res.value);
226
+ if (newRes.isErr()) {
227
+ return new Err(newRes.error);
228
+ }
229
+ return new Ok(res.value);
230
+ })));
231
+ }
232
+ andTee(f) {
233
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
234
+ if (res.isErr()) {
235
+ return new Err(res.error);
236
+ }
237
+ try {
238
+ yield f(res.value);
239
+ } catch (e) {
240
+ }
241
+ return new Ok(res.value);
242
+ })));
243
+ }
244
+ mapErr(f) {
245
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
246
+ if (res.isOk()) {
247
+ return new Ok(res.value);
248
+ }
249
+ return new Err(yield f(res.error));
250
+ })));
251
+ }
252
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
253
+ andThen(f) {
254
+ return new _ResultAsync(this._promise.then((res) => {
255
+ if (res.isErr()) {
256
+ return new Err(res.error);
257
+ }
258
+ const newValue = f(res.value);
259
+ return newValue instanceof _ResultAsync ? newValue._promise : newValue;
260
+ }));
261
+ }
262
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
263
+ orElse(f) {
264
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
265
+ if (res.isErr()) {
266
+ return f(res.error);
267
+ }
268
+ return new Ok(res.value);
269
+ })));
270
+ }
271
+ match(ok2, _err) {
272
+ return this._promise.then((res) => res.match(ok2, _err));
273
+ }
274
+ unwrapOr(t) {
275
+ return this._promise.then((res) => res.unwrapOr(t));
276
+ }
277
+ /**
278
+ * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
279
+ */
280
+ safeUnwrap() {
281
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
282
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
283
+ });
284
+ }
285
+ // Makes ResultAsync implement PromiseLike<Result>
286
+ then(successCallback, failureCallback) {
287
+ return this._promise.then(successCallback, failureCallback);
288
+ }
289
+ };
290
+ var errAsync = (err2) => new ResultAsync(Promise.resolve(new Err(err2)));
291
+ var fromPromise = ResultAsync.fromPromise;
292
+ var fromSafePromise = ResultAsync.fromSafePromise;
293
+ var fromAsyncThrowable = ResultAsync.fromThrowable;
294
+ var combineResultList = (resultList) => {
295
+ let acc = ok([]);
296
+ for (const result of resultList) {
297
+ if (result.isErr()) {
298
+ acc = err(result.error);
299
+ break;
300
+ } else {
301
+ acc.map((list) => list.push(result.value));
302
+ }
303
+ }
304
+ return acc;
305
+ };
306
+ var combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
307
+ var combineResultListWithAllErrors = (resultList) => {
308
+ let acc = ok([]);
309
+ for (const result of resultList) {
310
+ if (result.isErr() && acc.isErr()) {
311
+ acc.error.push(result.error);
312
+ } else if (result.isErr() && acc.isOk()) {
313
+ acc = err([result.error]);
314
+ } else if (result.isOk() && acc.isOk()) {
315
+ acc.value.push(result.value);
316
+ }
317
+ }
318
+ return acc;
319
+ };
320
+ var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
321
+ var Result;
322
+ (function(Result2) {
323
+ function fromThrowable2(fn, errorFn) {
324
+ return (...args) => {
325
+ try {
326
+ const result = fn(...args);
327
+ return ok(result);
328
+ } catch (e) {
329
+ return err(errorFn ? errorFn(e) : e);
330
+ }
331
+ };
332
+ }
333
+ Result2.fromThrowable = fromThrowable2;
334
+ function combine(resultList) {
335
+ return combineResultList(resultList);
336
+ }
337
+ Result2.combine = combine;
338
+ function combineWithAllErrors(resultList) {
339
+ return combineResultListWithAllErrors(resultList);
340
+ }
341
+ Result2.combineWithAllErrors = combineWithAllErrors;
342
+ })(Result || (Result = {}));
343
+ var ok = (value) => new Ok(value);
344
+ function err(err2) {
345
+ return new Err(err2);
346
+ }
347
+ var Ok = class {
348
+ constructor(value) {
349
+ this.value = value;
350
+ }
351
+ isOk() {
352
+ return true;
353
+ }
354
+ isErr() {
355
+ return !this.isOk();
356
+ }
357
+ map(f) {
358
+ return ok(f(this.value));
359
+ }
360
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
361
+ mapErr(_f) {
362
+ return ok(this.value);
363
+ }
364
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
365
+ andThen(f) {
366
+ return f(this.value);
367
+ }
368
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
369
+ andThrough(f) {
370
+ return f(this.value).map((_value) => this.value);
371
+ }
372
+ andTee(f) {
373
+ try {
374
+ f(this.value);
375
+ } catch (e) {
376
+ }
377
+ return ok(this.value);
378
+ }
379
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
380
+ orElse(_f) {
381
+ return ok(this.value);
382
+ }
383
+ asyncAndThen(f) {
384
+ return f(this.value);
385
+ }
386
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
387
+ asyncAndThrough(f) {
388
+ return f(this.value).map(() => this.value);
389
+ }
390
+ asyncMap(f) {
391
+ return ResultAsync.fromSafePromise(f(this.value));
392
+ }
393
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
394
+ unwrapOr(_v) {
395
+ return this.value;
396
+ }
397
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
398
+ match(ok2, _err) {
399
+ return ok2(this.value);
400
+ }
401
+ safeUnwrap() {
402
+ const value = this.value;
403
+ return function* () {
404
+ return value;
405
+ }();
406
+ }
407
+ _unsafeUnwrap(_) {
408
+ return this.value;
409
+ }
410
+ _unsafeUnwrapErr(config) {
411
+ throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
412
+ }
413
+ };
414
+ var Err = class {
415
+ constructor(error) {
416
+ this.error = error;
417
+ }
418
+ isOk() {
419
+ return false;
420
+ }
421
+ isErr() {
422
+ return !this.isOk();
423
+ }
424
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
425
+ map(_f) {
426
+ return err(this.error);
427
+ }
428
+ mapErr(f) {
429
+ return err(f(this.error));
430
+ }
431
+ andThrough(_f) {
432
+ return err(this.error);
433
+ }
434
+ andTee(_f) {
435
+ return err(this.error);
436
+ }
437
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
438
+ andThen(_f) {
439
+ return err(this.error);
440
+ }
441
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
442
+ orElse(f) {
443
+ return f(this.error);
444
+ }
445
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
446
+ asyncAndThen(_f) {
447
+ return errAsync(this.error);
448
+ }
449
+ asyncAndThrough(_f) {
450
+ return errAsync(this.error);
451
+ }
452
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
453
+ asyncMap(_f) {
454
+ return errAsync(this.error);
455
+ }
456
+ unwrapOr(v) {
457
+ return v;
458
+ }
459
+ match(_ok, err2) {
460
+ return err2(this.error);
461
+ }
462
+ safeUnwrap() {
463
+ const error = this.error;
464
+ return function* () {
465
+ yield err(error);
466
+ throw new Error("Do not use this generator out of `safeTry`");
467
+ }();
468
+ }
469
+ _unsafeUnwrap(config) {
470
+ throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
471
+ }
472
+ _unsafeUnwrapErr(_) {
473
+ return this.error;
474
+ }
475
+ };
476
+ var fromThrowable = Result.fromThrowable;
477
+
478
+ // src/constants.ts
479
+ var WORKFLOW_ID_HEADER = "Upstash-Workflow-RunId";
480
+ var WORKFLOW_INIT_HEADER = "Upstash-Workflow-Init";
481
+ var WORKFLOW_URL_HEADER = "Upstash-Workflow-Url";
482
+ var WORKFLOW_FAILURE_HEADER = "Upstash-Workflow-Is-Failure";
483
+ var WORKFLOW_PROTOCOL_VERSION = "1";
484
+ var WORKFLOW_PROTOCOL_VERSION_HEADER = "Upstash-Workflow-Sdk-Version";
485
+ var DEFAULT_CONTENT_TYPE = "application/json";
486
+ var NO_CONCURRENCY = 1;
487
+ var DEFAULT_RETRIES = 3;
488
+
489
+ // src/types.ts
490
+ var StepTypes = [
491
+ "Initial",
492
+ "Run",
493
+ "SleepFor",
494
+ "SleepUntil",
495
+ "Call",
496
+ "Wait",
497
+ "Notify"
498
+ ];
499
+
500
+ // src/workflow-requests.ts
501
+ var triggerFirstInvocation = async (workflowContext, retries, debug) => {
502
+ const { headers } = getHeaders(
503
+ "true",
504
+ workflowContext.workflowRunId,
505
+ workflowContext.url,
506
+ workflowContext.headers,
507
+ void 0,
508
+ workflowContext.failureUrl,
509
+ retries
510
+ );
511
+ await debug?.log("SUBMIT", "SUBMIT_FIRST_INVOCATION", {
512
+ headers,
513
+ requestPayload: workflowContext.requestPayload,
514
+ url: workflowContext.url
515
+ });
516
+ try {
517
+ await workflowContext.qstashClient.publishJSON({
518
+ headers,
519
+ method: "POST",
520
+ body: workflowContext.requestPayload,
521
+ url: workflowContext.url
522
+ });
523
+ return ok("success");
524
+ } catch (error) {
525
+ const error_ = error;
526
+ return err(error_);
527
+ }
528
+ };
529
+ var triggerRouteFunction = async ({
530
+ onCleanup,
531
+ onStep
532
+ }) => {
533
+ try {
534
+ await onStep();
535
+ await onCleanup();
536
+ return ok("workflow-finished");
537
+ } catch (error) {
538
+ const error_ = error;
539
+ return error_ instanceof QStashWorkflowAbort ? ok("step-finished") : err(error_);
540
+ }
541
+ };
542
+ var triggerWorkflowDelete = async (workflowContext, debug, cancel = false) => {
543
+ await debug?.log("SUBMIT", "SUBMIT_CLEANUP", {
544
+ deletedWorkflowRunId: workflowContext.workflowRunId
545
+ });
546
+ const result = await workflowContext.qstashClient.http.request({
547
+ path: ["v2", "workflows", "runs", `${workflowContext.workflowRunId}?cancel=${cancel}`],
548
+ method: "DELETE",
549
+ parseResponseAsJson: false
550
+ });
551
+ await debug?.log("SUBMIT", "SUBMIT_CLEANUP", result);
552
+ };
553
+ var recreateUserHeaders = (headers) => {
554
+ const filteredHeaders = new Headers();
555
+ const pairs = headers.entries();
556
+ for (const [header, value] of pairs) {
557
+ const headerLowerCase = header.toLowerCase();
558
+ if (!headerLowerCase.startsWith("upstash-workflow-") && !headerLowerCase.startsWith("x-vercel-") && !headerLowerCase.startsWith("x-forwarded-") && headerLowerCase !== "cf-connecting-ip") {
559
+ filteredHeaders.append(header, value);
560
+ }
561
+ }
562
+ return filteredHeaders;
563
+ };
564
+ var handleThirdPartyCallResult = async (request, requestPayload, client, workflowUrl, failureUrl, retries, debug) => {
565
+ try {
566
+ if (request.headers.get("Upstash-Workflow-Callback")) {
567
+ const callbackMessage = JSON.parse(requestPayload);
568
+ if (!(callbackMessage.status >= 200 && callbackMessage.status < 300)) {
569
+ await debug?.log("WARN", "SUBMIT_THIRD_PARTY_RESULT", {
570
+ status: callbackMessage.status,
571
+ body: atob(callbackMessage.body)
572
+ });
573
+ console.warn(
574
+ `Workflow Warning: "context.call" failed with status ${callbackMessage.status} and will retry (if there are retries remaining). Error Message:
575
+ ${atob(callbackMessage.body)}`
576
+ );
577
+ return ok("call-will-retry");
578
+ }
579
+ const workflowRunId = request.headers.get(WORKFLOW_ID_HEADER);
580
+ const stepIdString = request.headers.get("Upstash-Workflow-StepId");
581
+ const stepName = request.headers.get("Upstash-Workflow-StepName");
582
+ const stepType = request.headers.get("Upstash-Workflow-StepType");
583
+ const concurrentString = request.headers.get("Upstash-Workflow-Concurrent");
584
+ const contentType = request.headers.get("Upstash-Workflow-ContentType");
585
+ if (!(workflowRunId && stepIdString && stepName && StepTypes.includes(stepType) && concurrentString && contentType)) {
586
+ throw new Error(
587
+ `Missing info in callback message source header: ${JSON.stringify({
588
+ workflowRunId,
589
+ stepIdString,
590
+ stepName,
591
+ stepType,
592
+ concurrentString,
593
+ contentType
594
+ })}`
595
+ );
596
+ }
597
+ const userHeaders = recreateUserHeaders(request.headers);
598
+ const { headers: requestHeaders } = getHeaders(
599
+ "false",
600
+ workflowRunId,
601
+ workflowUrl,
602
+ userHeaders,
603
+ void 0,
604
+ failureUrl,
605
+ retries
606
+ );
607
+ const callResultStep = {
608
+ stepId: Number(stepIdString),
609
+ stepName,
610
+ stepType,
611
+ out: atob(callbackMessage.body),
612
+ concurrent: Number(concurrentString)
613
+ };
614
+ await debug?.log("SUBMIT", "SUBMIT_THIRD_PARTY_RESULT", {
615
+ step: callResultStep,
616
+ headers: requestHeaders,
617
+ url: workflowUrl
618
+ });
619
+ const result = await client.publishJSON({
620
+ headers: requestHeaders,
621
+ method: "POST",
622
+ body: callResultStep,
623
+ url: workflowUrl
624
+ });
625
+ await debug?.log("SUBMIT", "SUBMIT_THIRD_PARTY_RESULT", {
626
+ messageId: result.messageId
627
+ });
628
+ return ok("is-call-return");
629
+ } else {
630
+ return ok("continue-workflow");
631
+ }
632
+ } catch (error) {
633
+ const isCallReturn = request.headers.get("Upstash-Workflow-Callback");
634
+ return err(
635
+ new QStashWorkflowError(
636
+ `Error when handling call return (isCallReturn=${isCallReturn}): ${error}`
637
+ )
638
+ );
639
+ }
640
+ };
641
+ var getHeaders = (initHeaderValue, workflowRunId, workflowUrl, userHeaders, step, failureUrl, retries) => {
642
+ const baseHeaders = {
643
+ [WORKFLOW_INIT_HEADER]: initHeaderValue,
644
+ [WORKFLOW_ID_HEADER]: workflowRunId,
645
+ [WORKFLOW_URL_HEADER]: workflowUrl,
646
+ [`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`]: WORKFLOW_PROTOCOL_VERSION,
647
+ ...failureUrl ? {
648
+ [`Upstash-Failure-Callback-Forward-${WORKFLOW_FAILURE_HEADER}`]: "true",
649
+ "Upstash-Failure-Callback": failureUrl
650
+ } : {},
651
+ ...retries === void 0 ? {} : {
652
+ "Upstash-Retries": retries.toString()
653
+ }
654
+ };
655
+ if (userHeaders) {
656
+ for (const header of userHeaders.keys()) {
657
+ if (step?.callHeaders) {
658
+ baseHeaders[`Upstash-Callback-Forward-${header}`] = userHeaders.get(header);
659
+ } else {
660
+ baseHeaders[`Upstash-Forward-${header}`] = userHeaders.get(header);
661
+ }
662
+ }
663
+ }
664
+ const contentType = (userHeaders ? userHeaders.get("Content-Type") : void 0) ?? DEFAULT_CONTENT_TYPE;
665
+ if (step?.callHeaders) {
666
+ const forwardedHeaders = Object.fromEntries(
667
+ Object.entries(step.callHeaders).map(([header, value]) => [
668
+ `Upstash-Forward-${header}`,
669
+ value
670
+ ])
671
+ );
672
+ return {
673
+ headers: {
674
+ ...baseHeaders,
675
+ ...forwardedHeaders,
676
+ "Upstash-Callback": workflowUrl,
677
+ "Upstash-Callback-Workflow-RunId": workflowRunId,
678
+ "Upstash-Callback-Workflow-CallType": "fromCallback",
679
+ "Upstash-Callback-Workflow-Init": "false",
680
+ "Upstash-Callback-Workflow-Url": workflowUrl,
681
+ "Upstash-Callback-Forward-Upstash-Workflow-Callback": "true",
682
+ "Upstash-Callback-Forward-Upstash-Workflow-StepId": step.stepId.toString(),
683
+ "Upstash-Callback-Forward-Upstash-Workflow-StepName": step.stepName,
684
+ "Upstash-Callback-Forward-Upstash-Workflow-StepType": step.stepType,
685
+ "Upstash-Callback-Forward-Upstash-Workflow-Concurrent": step.concurrent.toString(),
686
+ "Upstash-Callback-Forward-Upstash-Workflow-ContentType": contentType,
687
+ "Upstash-Workflow-CallType": "toCallback"
688
+ }
689
+ };
690
+ }
691
+ if (step?.waitEventId) {
692
+ return {
693
+ headers: {
694
+ ...baseHeaders,
695
+ "Upstash-Workflow-CallType": "step"
696
+ },
697
+ timeoutHeaders: {
698
+ // to include user headers:
699
+ ...Object.fromEntries(
700
+ Object.entries(baseHeaders).map(([header, value]) => [header, [value]])
701
+ ),
702
+ // note: using WORKFLOW_ID_HEADER doesn't work, because Runid -> RunId:
703
+ "Upstash-Workflow-Runid": [workflowRunId],
704
+ [WORKFLOW_INIT_HEADER]: ["false"],
705
+ [WORKFLOW_URL_HEADER]: [workflowUrl],
706
+ "Upstash-Workflow-CallType": ["step"],
707
+ "Content-Type": [contentType]
708
+ }
709
+ };
710
+ }
711
+ return { headers: baseHeaders };
712
+ };
713
+ var verifyRequest = async (body, signature, verifier) => {
714
+ if (!verifier) {
715
+ return;
716
+ }
717
+ try {
718
+ if (!signature) {
719
+ throw new Error("`Upstash-Signature` header is not passed.");
720
+ }
721
+ const isValid = await verifier.verify({
722
+ body,
723
+ signature
724
+ });
725
+ if (!isValid) {
726
+ throw new Error("Signature in `Upstash-Signature` header is not valid");
727
+ }
728
+ } catch (error) {
729
+ throw new QStashWorkflowError(
730
+ `Failed to verify that the Workflow request comes from QStash: ${error}
731
+
732
+ If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
733
+
734
+ If you want to disable QStash Verification, you should clear env variables QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY`
735
+ );
736
+ }
737
+ };
738
+
739
+ // src/context/auto-executor.ts
740
+ var AutoExecutor = class _AutoExecutor {
741
+ context;
742
+ promises = /* @__PURE__ */ new WeakMap();
743
+ activeLazyStepList;
744
+ debug;
745
+ nonPlanStepCount;
746
+ steps;
747
+ indexInCurrentList = 0;
748
+ stepCount = 0;
749
+ planStepCount = 0;
750
+ executingStep = false;
751
+ constructor(context, steps, debug) {
752
+ this.context = context;
753
+ this.debug = debug;
754
+ this.steps = steps;
755
+ this.nonPlanStepCount = this.steps.filter((step) => !step.targetStep).length;
756
+ }
757
+ /**
758
+ * Adds the step function to the list of step functions to run in
759
+ * parallel. After adding the function, defers the execution, so
760
+ * that if there is another step function to be added, it's also
761
+ * added.
762
+ *
763
+ * After all functions are added, list of functions are executed.
764
+ * If there is a single function, it's executed by itself. If there
765
+ * are multiple, they are run in parallel.
766
+ *
767
+ * If a function is already executing (this.executingStep), this
768
+ * means that there is a nested step which is not allowed. In this
769
+ * case, addStep throws QStashWorkflowError.
770
+ *
771
+ * @param stepInfo step plan to add
772
+ * @returns result of the step function
773
+ */
774
+ async addStep(stepInfo) {
775
+ if (this.executingStep) {
776
+ throw new QStashWorkflowError(
777
+ `A step can not be run inside another step. Tried to run '${stepInfo.stepName}' inside '${this.executingStep}'`
778
+ );
779
+ }
780
+ this.stepCount += 1;
781
+ const lazyStepList = this.activeLazyStepList ?? [];
782
+ if (!this.activeLazyStepList) {
783
+ this.activeLazyStepList = lazyStepList;
784
+ this.indexInCurrentList = 0;
785
+ }
786
+ lazyStepList.push(stepInfo);
787
+ const index = this.indexInCurrentList++;
788
+ const requestComplete = this.deferExecution().then(async () => {
789
+ if (!this.promises.has(lazyStepList)) {
790
+ const promise2 = this.getExecutionPromise(lazyStepList);
791
+ this.promises.set(lazyStepList, promise2);
792
+ this.activeLazyStepList = void 0;
793
+ this.planStepCount += lazyStepList.length > 1 ? lazyStepList.length : 0;
794
+ }
795
+ const promise = this.promises.get(lazyStepList);
796
+ return promise;
797
+ });
798
+ const result = await requestComplete;
799
+ return _AutoExecutor.getResult(lazyStepList, result, index);
800
+ }
801
+ /**
802
+ * Wraps a step function to set this.executingStep to step name
803
+ * before running and set this.executingStep to False after execution
804
+ * ends.
805
+ *
806
+ * this.executingStep allows us to detect nested steps which are not
807
+ * allowed.
808
+ *
809
+ * @param stepName name of the step being wrapped
810
+ * @param stepFunction step function to wrap
811
+ * @returns wrapped step function
812
+ */
813
+ wrapStep(stepName, stepFunction) {
814
+ this.executingStep = stepName;
815
+ const result = stepFunction();
816
+ this.executingStep = false;
817
+ return result;
818
+ }
819
+ /**
820
+ * Executes a step:
821
+ * - If the step result is available in the steps, returns the result
822
+ * - If the result is not avaiable, runs the function
823
+ * - Sends the result to QStash
824
+ *
825
+ * @param lazyStep lazy step to execute
826
+ * @returns step result
827
+ */
828
+ async runSingle(lazyStep) {
829
+ if (this.stepCount < this.nonPlanStepCount) {
830
+ const step = this.steps[this.stepCount + this.planStepCount];
831
+ validateStep(lazyStep, step);
832
+ await this.debug?.log("INFO", "RUN_SINGLE", {
833
+ fromRequest: true,
834
+ step,
835
+ stepCount: this.stepCount
836
+ });
837
+ return step.out;
838
+ }
839
+ const resultStep = await lazyStep.getResultStep(NO_CONCURRENCY, this.stepCount);
840
+ await this.debug?.log("INFO", "RUN_SINGLE", {
841
+ fromRequest: false,
842
+ step: resultStep,
843
+ stepCount: this.stepCount
844
+ });
845
+ await this.submitStepsToQStash([resultStep]);
846
+ return resultStep.out;
847
+ }
848
+ /**
849
+ * Runs steps in parallel.
850
+ *
851
+ * @param stepName parallel step name
852
+ * @param stepFunctions list of async functions to run in parallel
853
+ * @returns results of the functions run in parallel
854
+ */
855
+ async runParallel(parallelSteps) {
856
+ const initialStepCount = this.stepCount - (parallelSteps.length - 1);
857
+ const parallelCallState = this.getParallelCallState(parallelSteps.length, initialStepCount);
858
+ const sortedSteps = sortSteps(this.steps);
859
+ const plannedParallelStepCount = sortedSteps[initialStepCount + this.planStepCount]?.concurrent;
860
+ if (parallelCallState !== "first" && plannedParallelStepCount !== parallelSteps.length) {
861
+ throw new QStashWorkflowError(
862
+ `Incompatible number of parallel steps when call state was '${parallelCallState}'. Expected ${parallelSteps.length}, got ${plannedParallelStepCount} from the request.`
863
+ );
864
+ }
865
+ await this.debug?.log("INFO", "RUN_PARALLEL", {
866
+ parallelCallState,
867
+ initialStepCount,
868
+ plannedParallelStepCount,
869
+ stepCount: this.stepCount,
870
+ planStepCount: this.planStepCount
871
+ });
872
+ switch (parallelCallState) {
873
+ case "first": {
874
+ const planSteps = parallelSteps.map(
875
+ (parallelStep, index) => parallelStep.getPlanStep(parallelSteps.length, initialStepCount + index)
876
+ );
877
+ await this.submitStepsToQStash(planSteps);
878
+ break;
879
+ }
880
+ case "partial": {
881
+ const planStep = this.steps.at(-1);
882
+ if (!planStep || planStep.targetStep === void 0) {
883
+ throw new QStashWorkflowError(
884
+ `There must be a last step and it should have targetStep larger than 0.Received: ${JSON.stringify(planStep)}`
885
+ );
886
+ }
887
+ const stepIndex = planStep.targetStep - initialStepCount;
888
+ validateStep(parallelSteps[stepIndex], planStep);
889
+ try {
890
+ const resultStep = await parallelSteps[stepIndex].getResultStep(
891
+ parallelSteps.length,
892
+ planStep.targetStep
893
+ );
894
+ await this.submitStepsToQStash([resultStep]);
895
+ } catch (error) {
896
+ if (error instanceof QStashWorkflowAbort) {
897
+ throw error;
898
+ }
899
+ throw new QStashWorkflowError(
900
+ `Error submitting steps to QStash in partial parallel step execution: ${error}`
901
+ );
902
+ }
903
+ break;
904
+ }
905
+ case "discard": {
906
+ throw new QStashWorkflowAbort("discarded parallel");
907
+ }
908
+ case "last": {
909
+ const parallelResultSteps = sortedSteps.filter((step) => step.stepId >= initialStepCount).slice(0, parallelSteps.length);
910
+ validateParallelSteps(parallelSteps, parallelResultSteps);
911
+ return parallelResultSteps.map((step) => step.out);
912
+ }
913
+ }
914
+ const fillValue = void 0;
915
+ return Array.from({ length: parallelSteps.length }).fill(fillValue);
916
+ }
917
+ /**
918
+ * Determines the parallel call state
919
+ *
920
+ * First filters the steps to get the steps which are after `initialStepCount` parameter.
921
+ *
922
+ * Depending on the remaining steps, decides the parallel state:
923
+ * - "first": If there are no steps
924
+ * - "last" If there are equal to or more than `2 * parallelStepCount`. We multiply by two
925
+ * because each step in a parallel execution will have 2 steps: a plan step and a result
926
+ * step.
927
+ * - "partial": If the last step is a plan step
928
+ * - "discard": If the last step is not a plan step. This means that the parallel execution
929
+ * is in progress (there are still steps to run) and one step has finished and submitted
930
+ * its result to QStash
931
+ *
932
+ * @param parallelStepCount number of steps to run in parallel
933
+ * @param initialStepCount steps after the parallel invocation
934
+ * @returns parallel call state
935
+ */
936
+ getParallelCallState(parallelStepCount, initialStepCount) {
937
+ const remainingSteps = this.steps.filter(
938
+ (step) => (step.targetStep || step.stepId) >= initialStepCount
939
+ );
940
+ if (remainingSteps.length === 0) {
941
+ return "first";
942
+ } else if (remainingSteps.length >= 2 * parallelStepCount) {
943
+ return "last";
944
+ } else if (remainingSteps.at(-1)?.targetStep) {
945
+ return "partial";
946
+ } else {
947
+ return "discard";
948
+ }
949
+ }
950
+ /**
951
+ * sends the steps to QStash as batch
952
+ *
953
+ * @param steps steps to send
954
+ */
955
+ async submitStepsToQStash(steps) {
956
+ if (steps.length === 0) {
957
+ throw new QStashWorkflowError(
958
+ `Unable to submit steps to QStash. Provided list is empty. Current step: ${this.stepCount}`
959
+ );
960
+ }
961
+ await this.debug?.log("SUBMIT", "SUBMIT_STEP", {
962
+ length: steps.length,
963
+ steps
964
+ });
965
+ if (steps[0].waitEventId && steps.length === 1) {
966
+ const waitStep = steps[0];
967
+ const { headers, timeoutHeaders } = getHeaders(
968
+ "false",
969
+ this.context.workflowRunId,
970
+ this.context.url,
971
+ this.context.headers,
972
+ waitStep,
973
+ this.context.failureUrl,
974
+ this.context.retries
975
+ );
976
+ const waitBody = {
977
+ url: this.context.url,
978
+ timeout: waitStep.timeout,
979
+ timeoutBody: void 0,
980
+ timeoutUrl: this.context.url,
981
+ timeoutHeaders,
982
+ step: {
983
+ stepId: waitStep.stepId,
984
+ stepType: "Wait",
985
+ stepName: waitStep.stepName,
986
+ concurrent: waitStep.concurrent,
987
+ targetStep: waitStep.targetStep
988
+ }
989
+ };
990
+ await this.context.qstashClient.http.request({
991
+ path: ["v2", "wait", waitStep.waitEventId],
992
+ body: JSON.stringify(waitBody),
993
+ headers,
994
+ method: "POST"
995
+ });
996
+ throw new QStashWorkflowAbort(steps[0].stepName, steps[0]);
997
+ }
998
+ const result = await this.context.qstashClient.batchJSON(
999
+ steps.map((singleStep) => {
1000
+ const { headers } = getHeaders(
1001
+ "false",
1002
+ this.context.workflowRunId,
1003
+ this.context.url,
1004
+ this.context.headers,
1005
+ singleStep,
1006
+ this.context.failureUrl,
1007
+ this.context.retries
1008
+ );
1009
+ const willWait = singleStep.concurrent === NO_CONCURRENCY || singleStep.stepId === 0;
1010
+ return singleStep.callUrl ? (
1011
+ // if the step is a third party call, we call the third party
1012
+ // url (singleStep.callUrl) and pass information about the workflow
1013
+ // in the headers (handled in getHeaders). QStash makes the request
1014
+ // to callUrl and returns the result to Workflow endpoint.
1015
+ // handleThirdPartyCallResult method sends the result of the third
1016
+ // party call to QStash.
1017
+ {
1018
+ headers,
1019
+ method: singleStep.callMethod,
1020
+ body: singleStep.callBody,
1021
+ url: singleStep.callUrl
1022
+ }
1023
+ ) : (
1024
+ // if the step is not a third party call, we use workflow
1025
+ // endpoint (context.url) as URL when calling QStash. QStash
1026
+ // calls us back with the updated steps list.
1027
+ {
1028
+ headers,
1029
+ method: "POST",
1030
+ body: singleStep,
1031
+ url: this.context.url,
1032
+ notBefore: willWait ? singleStep.sleepUntil : void 0,
1033
+ delay: willWait ? singleStep.sleepFor : void 0
1034
+ }
1035
+ );
1036
+ })
1037
+ );
1038
+ await this.debug?.log("INFO", "SUBMIT_STEP", {
1039
+ messageIds: result.map((message) => {
1040
+ return {
1041
+ message: message.messageId
1042
+ };
1043
+ })
1044
+ });
1045
+ throw new QStashWorkflowAbort(steps[0].stepName, steps[0]);
1046
+ }
1047
+ /**
1048
+ * Get the promise by executing the lazt steps list. If there is a single
1049
+ * step, we call `runSingle`. Otherwise `runParallel` is called.
1050
+ *
1051
+ * @param lazyStepList steps list to execute
1052
+ * @returns promise corresponding to the execution
1053
+ */
1054
+ getExecutionPromise(lazyStepList) {
1055
+ return lazyStepList.length === 1 ? this.runSingle(lazyStepList[0]) : this.runParallel(lazyStepList);
1056
+ }
1057
+ /**
1058
+ * @param lazyStepList steps we executed
1059
+ * @param result result of the promise from `getExecutionPromise`
1060
+ * @param index index of the current step
1061
+ * @returns result[index] if lazyStepList > 1, otherwise result
1062
+ */
1063
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
1064
+ static getResult(lazyStepList, result, index) {
1065
+ if (lazyStepList.length === 1) {
1066
+ return result;
1067
+ } else if (Array.isArray(result) && lazyStepList.length === result.length && index < lazyStepList.length) {
1068
+ return result[index];
1069
+ } else {
1070
+ throw new QStashWorkflowError(
1071
+ `Unexpected parallel call result while executing step ${index}: '${result}'. Expected ${lazyStepList.length} many items`
1072
+ );
1073
+ }
1074
+ }
1075
+ async deferExecution() {
1076
+ await Promise.resolve();
1077
+ await Promise.resolve();
1078
+ }
1079
+ };
1080
+ var validateStep = (lazyStep, stepFromRequest) => {
1081
+ if (lazyStep.stepName !== stepFromRequest.stepName) {
1082
+ throw new QStashWorkflowError(
1083
+ `Incompatible step name. Expected '${lazyStep.stepName}', got '${stepFromRequest.stepName}' from the request`
1084
+ );
1085
+ }
1086
+ if (lazyStep.stepType !== stepFromRequest.stepType) {
1087
+ throw new QStashWorkflowError(
1088
+ `Incompatible step type. Expected '${lazyStep.stepType}', got '${stepFromRequest.stepType}' from the request`
1089
+ );
1090
+ }
1091
+ };
1092
+ var validateParallelSteps = (lazySteps, stepsFromRequest) => {
1093
+ try {
1094
+ for (const [index, stepFromRequest] of stepsFromRequest.entries()) {
1095
+ validateStep(lazySteps[index], stepFromRequest);
1096
+ }
1097
+ } catch (error) {
1098
+ if (error instanceof QStashWorkflowError) {
1099
+ const lazyStepNames = lazySteps.map((lazyStep) => lazyStep.stepName);
1100
+ const lazyStepTypes = lazySteps.map((lazyStep) => lazyStep.stepType);
1101
+ const requestStepNames = stepsFromRequest.map((step) => step.stepName);
1102
+ const requestStepTypes = stepsFromRequest.map((step) => step.stepType);
1103
+ throw new QStashWorkflowError(
1104
+ `Incompatible steps detected in parallel execution: ${error.message}
1105
+ > Step Names from the request: ${JSON.stringify(requestStepNames)}
1106
+ Step Types from the request: ${JSON.stringify(requestStepTypes)}
1107
+ > Step Names expected: ${JSON.stringify(lazyStepNames)}
1108
+ Step Types expected: ${JSON.stringify(lazyStepTypes)}`
1109
+ );
1110
+ }
1111
+ throw error;
1112
+ }
1113
+ };
1114
+ var sortSteps = (steps) => {
1115
+ const getStepId = (step) => step.targetStep || step.stepId;
1116
+ return steps.toSorted((step, stepOther) => getStepId(step) - getStepId(stepOther));
1117
+ };
1118
+
1119
+ // src/context/steps.ts
1120
+ var BaseLazyStep = class {
1121
+ stepName;
1122
+ // will be set in the subclasses
1123
+ constructor(stepName) {
1124
+ this.stepName = stepName;
1125
+ }
1126
+ };
1127
+ var LazyFunctionStep = class extends BaseLazyStep {
1128
+ stepFunction;
1129
+ stepType = "Run";
1130
+ constructor(stepName, stepFunction) {
1131
+ super(stepName);
1132
+ this.stepFunction = stepFunction;
1133
+ }
1134
+ getPlanStep(concurrent, targetStep) {
1135
+ return {
1136
+ stepId: 0,
1137
+ stepName: this.stepName,
1138
+ stepType: this.stepType,
1139
+ concurrent,
1140
+ targetStep
1141
+ };
1142
+ }
1143
+ async getResultStep(concurrent, stepId) {
1144
+ let result = this.stepFunction();
1145
+ if (result instanceof Promise) {
1146
+ result = await result;
1147
+ }
1148
+ return {
1149
+ stepId,
1150
+ stepName: this.stepName,
1151
+ stepType: this.stepType,
1152
+ out: result,
1153
+ concurrent
1154
+ };
1155
+ }
1156
+ };
1157
+ var LazySleepStep = class extends BaseLazyStep {
1158
+ sleep;
1159
+ stepType = "SleepFor";
1160
+ constructor(stepName, sleep) {
1161
+ super(stepName);
1162
+ this.sleep = sleep;
1163
+ }
1164
+ getPlanStep(concurrent, targetStep) {
1165
+ return {
1166
+ stepId: 0,
1167
+ stepName: this.stepName,
1168
+ stepType: this.stepType,
1169
+ sleepFor: this.sleep,
1170
+ concurrent,
1171
+ targetStep
1172
+ };
1173
+ }
1174
+ async getResultStep(concurrent, stepId) {
1175
+ return await Promise.resolve({
1176
+ stepId,
1177
+ stepName: this.stepName,
1178
+ stepType: this.stepType,
1179
+ sleepFor: this.sleep,
1180
+ concurrent
1181
+ });
1182
+ }
1183
+ };
1184
+ var LazySleepUntilStep = class extends BaseLazyStep {
1185
+ sleepUntil;
1186
+ stepType = "SleepUntil";
1187
+ constructor(stepName, sleepUntil) {
1188
+ super(stepName);
1189
+ this.sleepUntil = sleepUntil;
1190
+ }
1191
+ getPlanStep(concurrent, targetStep) {
1192
+ return {
1193
+ stepId: 0,
1194
+ stepName: this.stepName,
1195
+ stepType: this.stepType,
1196
+ sleepUntil: this.sleepUntil,
1197
+ concurrent,
1198
+ targetStep
1199
+ };
1200
+ }
1201
+ async getResultStep(concurrent, stepId) {
1202
+ return await Promise.resolve({
1203
+ stepId,
1204
+ stepName: this.stepName,
1205
+ stepType: this.stepType,
1206
+ sleepUntil: this.sleepUntil,
1207
+ concurrent
1208
+ });
1209
+ }
1210
+ };
1211
+ var LazyCallStep = class extends BaseLazyStep {
1212
+ url;
1213
+ method;
1214
+ body;
1215
+ headers;
1216
+ stepType = "Call";
1217
+ constructor(stepName, url, method, body, headers) {
1218
+ super(stepName);
1219
+ this.url = url;
1220
+ this.method = method;
1221
+ this.body = body;
1222
+ this.headers = headers;
1223
+ }
1224
+ getPlanStep(concurrent, targetStep) {
1225
+ return {
1226
+ stepId: 0,
1227
+ stepName: this.stepName,
1228
+ stepType: this.stepType,
1229
+ concurrent,
1230
+ targetStep
1231
+ };
1232
+ }
1233
+ async getResultStep(concurrent, stepId) {
1234
+ return await Promise.resolve({
1235
+ stepId,
1236
+ stepName: this.stepName,
1237
+ stepType: this.stepType,
1238
+ concurrent,
1239
+ callUrl: this.url,
1240
+ callMethod: this.method,
1241
+ callBody: this.body,
1242
+ callHeaders: this.headers
1243
+ });
1244
+ }
1245
+ };
1246
+ var LazyWaitForEventStep = class extends BaseLazyStep {
1247
+ eventId;
1248
+ timeout;
1249
+ stepType = "Wait";
1250
+ constructor(stepName, eventId, timeout) {
1251
+ super(stepName);
1252
+ this.eventId = eventId;
1253
+ this.timeout = timeout;
1254
+ }
1255
+ getPlanStep(concurrent, targetStep) {
1256
+ return {
1257
+ stepId: 0,
1258
+ stepName: this.stepName,
1259
+ stepType: this.stepType,
1260
+ waitEventId: this.eventId,
1261
+ timeout: this.timeout,
1262
+ concurrent,
1263
+ targetStep
1264
+ };
1265
+ }
1266
+ async getResultStep(concurrent, stepId) {
1267
+ return await Promise.resolve({
1268
+ stepId,
1269
+ stepName: this.stepName,
1270
+ stepType: this.stepType,
1271
+ waitEventId: this.eventId,
1272
+ timeout: this.timeout,
1273
+ concurrent
1274
+ });
1275
+ }
1276
+ };
1277
+
1278
+ // src/context/context.ts
1279
+ var WorkflowContext = class {
1280
+ executor;
1281
+ steps;
1282
+ /**
1283
+ * QStash client of the workflow
1284
+ *
1285
+ * Can be overwritten by passing `qstashClient` parameter in `serve`:
1286
+ *
1287
+ * ```ts
1288
+ * import { Client } from "@upstash/qstash"
1289
+ *
1290
+ * export const POST = serve(
1291
+ * async (context) => {
1292
+ * ...
1293
+ * },
1294
+ * {
1295
+ * qstashClient: new Client({...})
1296
+ * }
1297
+ * )
1298
+ * ```
1299
+ */
1300
+ qstashClient;
1301
+ /**
1302
+ * Run id of the workflow
1303
+ */
1304
+ workflowRunId;
1305
+ /**
1306
+ * URL of the workflow
1307
+ *
1308
+ * Can be overwritten by passing a `url` parameter in `serve`:
1309
+ *
1310
+ * ```ts
1311
+ * export const POST = serve(
1312
+ * async (context) => {
1313
+ * ...
1314
+ * },
1315
+ * {
1316
+ * url: "new-url-value"
1317
+ * }
1318
+ * )
1319
+ * ```
1320
+ */
1321
+ url;
1322
+ /**
1323
+ * URL to call in case of workflow failure with QStash failure callback
1324
+ *
1325
+ * https://upstash.com/docs/qstash/features/callbacks#what-is-a-failure-callback
1326
+ *
1327
+ * Can be overwritten by passing a `failureUrl` parameter in `serve`:
1328
+ *
1329
+ * ```ts
1330
+ * export const POST = serve(
1331
+ * async (context) => {
1332
+ * ...
1333
+ * },
1334
+ * {
1335
+ * failureUrl: "new-url-value"
1336
+ * }
1337
+ * )
1338
+ * ```
1339
+ */
1340
+ failureUrl;
1341
+ /**
1342
+ * Payload of the request which started the workflow.
1343
+ *
1344
+ * To specify its type, you can define `serve` as follows:
1345
+ *
1346
+ * ```ts
1347
+ * // set requestPayload type to MyPayload:
1348
+ * export const POST = serve<MyPayload>(
1349
+ * async (context) => {
1350
+ * ...
1351
+ * }
1352
+ * )
1353
+ * ```
1354
+ *
1355
+ * By default, `serve` tries to apply `JSON.parse` to the request payload.
1356
+ * If your payload is encoded in a format other than JSON, you can utilize
1357
+ * the `initialPayloadParser` parameter:
1358
+ *
1359
+ * ```ts
1360
+ * export const POST = serve<MyPayload>(
1361
+ * async (context) => {
1362
+ * ...
1363
+ * },
1364
+ * {
1365
+ * initialPayloadParser: (initialPayload) => {return doSomething(initialPayload)}
1366
+ * }
1367
+ * )
1368
+ * ```
1369
+ */
1370
+ requestPayload;
1371
+ /**
1372
+ * headers of the initial request
1373
+ */
1374
+ headers;
1375
+ /**
1376
+ * initial payload as a raw string
1377
+ */
1378
+ rawInitialPayload;
1379
+ /**
1380
+ * Map of environment variables and their values.
1381
+ *
1382
+ * Can be set using the `env` option of serve:
1383
+ *
1384
+ * ```ts
1385
+ * export const POST = serve<MyPayload>(
1386
+ * async (context) => {
1387
+ * const key = context.env["API_KEY"];
1388
+ * },
1389
+ * {
1390
+ * env: {
1391
+ * "API_KEY": "*****";
1392
+ * }
1393
+ * }
1394
+ * )
1395
+ * ```
1396
+ *
1397
+ * Default value is set to `process.env`.
1398
+ */
1399
+ env;
1400
+ /**
1401
+ * Number of retries
1402
+ */
1403
+ retries;
1404
+ constructor({
1405
+ qstashClient,
1406
+ workflowRunId,
1407
+ headers,
1408
+ steps,
1409
+ url,
1410
+ failureUrl,
1411
+ debug,
1412
+ initialPayload,
1413
+ rawInitialPayload,
1414
+ env,
1415
+ retries
1416
+ }) {
1417
+ this.qstashClient = qstashClient;
1418
+ this.workflowRunId = workflowRunId;
1419
+ this.steps = steps;
1420
+ this.url = url;
1421
+ this.failureUrl = failureUrl;
1422
+ this.headers = headers;
1423
+ this.requestPayload = initialPayload;
1424
+ this.rawInitialPayload = rawInitialPayload ?? JSON.stringify(this.requestPayload);
1425
+ this.env = env ?? {};
1426
+ this.retries = retries ?? DEFAULT_RETRIES;
1427
+ this.executor = new AutoExecutor(this, this.steps, debug);
1428
+ }
1429
+ /**
1430
+ * Executes a workflow step
1431
+ *
1432
+ * ```typescript
1433
+ * const result = await context.run("step 1", () => {
1434
+ * return "result"
1435
+ * })
1436
+ * ```
1437
+ *
1438
+ * Can also be called in parallel and the steps will be executed
1439
+ * simulatenously:
1440
+ *
1441
+ * ```typescript
1442
+ * const [result1, result2] = await Promise.all([
1443
+ * context.run("step 1", () => {
1444
+ * return "result1"
1445
+ * })
1446
+ * context.run("step 2", async () => {
1447
+ * return await fetchResults()
1448
+ * })
1449
+ * ])
1450
+ * ```
1451
+ *
1452
+ * @param stepName name of the step
1453
+ * @param stepFunction step function to be executed
1454
+ * @returns result of the step function
1455
+ */
1456
+ async run(stepName, stepFunction) {
1457
+ const wrappedStepFunction = () => this.executor.wrapStep(stepName, stepFunction);
1458
+ return this.addStep(new LazyFunctionStep(stepName, wrappedStepFunction));
1459
+ }
1460
+ /**
1461
+ * Stops the execution for the duration provided.
1462
+ *
1463
+ * @param stepName
1464
+ * @param duration sleep duration in seconds
1465
+ * @returns undefined
1466
+ */
1467
+ async sleep(stepName, duration) {
1468
+ await this.addStep(new LazySleepStep(stepName, duration));
1469
+ }
1470
+ /**
1471
+ * Stops the execution until the date time provided.
1472
+ *
1473
+ * @param stepName
1474
+ * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
1475
+ * as a Date object or a string (passed to `new Date(datetimeString)`)
1476
+ * @returns undefined
1477
+ */
1478
+ async sleepUntil(stepName, datetime) {
1479
+ let time;
1480
+ if (typeof datetime === "number") {
1481
+ time = datetime;
1482
+ } else {
1483
+ datetime = typeof datetime === "string" ? new Date(datetime) : datetime;
1484
+ time = Math.round(datetime.getTime() / 1e3);
1485
+ }
1486
+ await this.addStep(new LazySleepUntilStep(stepName, time));
1487
+ }
1488
+ /**
1489
+ * Makes a third party call through QStash in order to make a
1490
+ * network call without consuming any runtime.
1491
+ *
1492
+ * ```ts
1493
+ * const postResult = await context.call<string>(
1494
+ * "post call step",
1495
+ * `https://www.some-endpoint.com/api`,
1496
+ * "POST",
1497
+ * "my-payload"
1498
+ * );
1499
+ * ```
1500
+ *
1501
+ * tries to parse the result of the request as JSON. If it's
1502
+ * not a JSON which can be parsed, simply returns the response
1503
+ * body as it is.
1504
+ *
1505
+ * @param stepName
1506
+ * @param url url to call
1507
+ * @param method call method
1508
+ * @param body call body
1509
+ * @param headers call headers
1510
+ * @returns call result (parsed as JSON if possible)
1511
+ */
1512
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
1513
+ async call(stepName, url, method, body, headers) {
1514
+ const result = await this.addStep(
1515
+ new LazyCallStep(stepName, url, method, body, headers ?? {})
1516
+ );
1517
+ try {
1518
+ return JSON.parse(result);
1519
+ } catch {
1520
+ return result;
1521
+ }
1522
+ }
1523
+ async waitForEvent(stepName, eventId, timeout) {
1524
+ const result = await this.addStep(
1525
+ new LazyWaitForEventStep(
1526
+ stepName,
1527
+ eventId,
1528
+ typeof timeout === "string" ? timeout : `${timeout}s`
1529
+ )
1530
+ );
1531
+ return result;
1532
+ }
1533
+ /**
1534
+ * Adds steps to the executor. Needed so that it can be overwritten in
1535
+ * DisabledWorkflowContext.
1536
+ */
1537
+ async addStep(step) {
1538
+ return await this.executor.addStep(step);
1539
+ }
1540
+ };
1541
+
1542
+ // src/logger.ts
1543
+ var LOG_LEVELS = ["DEBUG", "INFO", "SUBMIT", "WARN", "ERROR"];
1544
+ var WorkflowLogger = class _WorkflowLogger {
1545
+ logs = [];
1546
+ options;
1547
+ workflowRunId = void 0;
1548
+ constructor(options) {
1549
+ this.options = options;
1550
+ }
1551
+ async log(level, eventType, details) {
1552
+ if (this.shouldLog(level)) {
1553
+ const timestamp = Date.now();
1554
+ const logEntry = {
1555
+ timestamp,
1556
+ workflowRunId: this.workflowRunId ?? "",
1557
+ logLevel: level,
1558
+ eventType,
1559
+ details
1560
+ };
1561
+ this.logs.push(logEntry);
1562
+ if (this.options.logOutput === "console") {
1563
+ this.writeToConsole(logEntry);
1564
+ }
1565
+ await new Promise((resolve) => setTimeout(resolve, 100));
1566
+ }
1567
+ }
1568
+ setWorkflowRunId(workflowRunId) {
1569
+ this.workflowRunId = workflowRunId;
1570
+ }
1571
+ writeToConsole(logEntry) {
1572
+ const JSON_SPACING = 2;
1573
+ console.log(JSON.stringify(logEntry, void 0, JSON_SPACING));
1574
+ }
1575
+ shouldLog(level) {
1576
+ return LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(this.options.logLevel);
1577
+ }
1578
+ static getLogger(verbose) {
1579
+ if (typeof verbose === "object") {
1580
+ return verbose;
1581
+ } else {
1582
+ return verbose ? new _WorkflowLogger({
1583
+ logLevel: "INFO",
1584
+ logOutput: "console"
1585
+ }) : void 0;
1586
+ }
1587
+ }
1588
+ };
1589
+
1590
+ // src/utils.ts
1591
+ var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1592
+ var NANOID_LENGTH = 21;
1593
+ function nanoid() {
1594
+ return [...crypto.getRandomValues(new Uint8Array(NANOID_LENGTH))].map((x) => NANOID_CHARS[x % NANOID_CHARS.length]).join("");
1595
+ }
1596
+ function decodeBase64(base64) {
1597
+ try {
1598
+ const binString = atob(base64);
1599
+ const intArray = Uint8Array.from(binString, (m) => m.codePointAt(0));
1600
+ return new TextDecoder().decode(intArray);
1601
+ } catch (error) {
1602
+ console.warn(
1603
+ `Upstash Qstash: Failed while decoding base64 "${base64}". Decoding with atob and returning it instead. ${error}`
1604
+ );
1605
+ return atob(base64);
1606
+ }
1607
+ }
1608
+
1609
+ // src/workflow-parser.ts
1610
+ var getPayload = async (request) => {
1611
+ try {
1612
+ return await request.text();
1613
+ } catch {
1614
+ return;
1615
+ }
1616
+ };
1617
+ var parsePayload = (rawPayload) => {
1618
+ const [encodedInitialPayload, ...encodedSteps] = JSON.parse(rawPayload);
1619
+ const rawInitialPayload = decodeBase64(encodedInitialPayload.body);
1620
+ const initialStep = {
1621
+ stepId: 0,
1622
+ stepName: "init",
1623
+ stepType: "Initial",
1624
+ out: rawInitialPayload,
1625
+ concurrent: NO_CONCURRENCY
1626
+ };
1627
+ const stepsToDecode = encodedSteps.filter((step) => step.callType === "step");
1628
+ const otherSteps = stepsToDecode.map((rawStep) => {
1629
+ const step = JSON.parse(decodeBase64(rawStep.body));
1630
+ if (step.waitEventId) {
1631
+ const newOut = {
1632
+ notifyBody: step.out,
1633
+ timeout: step.waitTimeout ?? false
1634
+ };
1635
+ step.out = newOut;
1636
+ }
1637
+ return step;
1638
+ });
1639
+ const steps = [initialStep, ...otherSteps];
1640
+ return {
1641
+ rawInitialPayload,
1642
+ steps
1643
+ };
1644
+ };
1645
+ var deduplicateSteps = (steps) => {
1646
+ const targetStepIds = [];
1647
+ const stepIds = [];
1648
+ const deduplicatedSteps = [];
1649
+ for (const step of steps) {
1650
+ if (step.stepId === 0) {
1651
+ if (!targetStepIds.includes(step.targetStep ?? 0)) {
1652
+ deduplicatedSteps.push(step);
1653
+ targetStepIds.push(step.targetStep ?? 0);
1654
+ }
1655
+ } else {
1656
+ if (!stepIds.includes(step.stepId)) {
1657
+ deduplicatedSteps.push(step);
1658
+ stepIds.push(step.stepId);
1659
+ }
1660
+ }
1661
+ }
1662
+ return deduplicatedSteps;
1663
+ };
1664
+ var checkIfLastOneIsDuplicate = async (steps, debug) => {
1665
+ if (steps.length < 2) {
1666
+ return false;
1667
+ }
1668
+ const lastStep = steps.at(-1);
1669
+ const lastStepId = lastStep.stepId;
1670
+ const lastTargetStepId = lastStep.targetStep;
1671
+ for (let index = 0; index < steps.length - 1; index++) {
1672
+ const step = steps[index];
1673
+ if (step.stepId === lastStepId && step.targetStep === lastTargetStepId) {
1674
+ const message = `Upstash Workflow: The step '${step.stepName}' with id '${step.stepId}' has run twice during workflow execution. Rest of the workflow will continue running as usual.`;
1675
+ await debug?.log("WARN", "RESPONSE_DEFAULT", message);
1676
+ console.warn(message);
1677
+ return true;
1678
+ }
1679
+ }
1680
+ return false;
1681
+ };
1682
+ var validateRequest = (request) => {
1683
+ const versionHeader = request.headers.get(WORKFLOW_PROTOCOL_VERSION_HEADER);
1684
+ const isFirstInvocation = !versionHeader;
1685
+ if (!isFirstInvocation && versionHeader !== WORKFLOW_PROTOCOL_VERSION) {
1686
+ throw new QStashWorkflowError(
1687
+ `Incompatible workflow sdk protocol version. Expected ${WORKFLOW_PROTOCOL_VERSION}, got ${versionHeader} from the request.`
1688
+ );
1689
+ }
1690
+ const workflowRunId = isFirstInvocation ? `wfr_${nanoid()}` : request.headers.get(WORKFLOW_ID_HEADER) ?? "";
1691
+ if (workflowRunId.length === 0) {
1692
+ throw new QStashWorkflowError("Couldn't get workflow id from header");
1693
+ }
1694
+ return {
1695
+ isFirstInvocation,
1696
+ workflowRunId
1697
+ };
1698
+ };
1699
+ var parseRequest = async (requestPayload, isFirstInvocation, debug) => {
1700
+ if (isFirstInvocation) {
1701
+ return {
1702
+ rawInitialPayload: requestPayload ?? "",
1703
+ steps: [],
1704
+ isLastDuplicate: false
1705
+ };
1706
+ } else {
1707
+ if (!requestPayload) {
1708
+ throw new QStashWorkflowError("Only first call can have an empty body");
1709
+ }
1710
+ const { rawInitialPayload, steps } = parsePayload(requestPayload);
1711
+ const isLastDuplicate = await checkIfLastOneIsDuplicate(steps, debug);
1712
+ const deduplicatedSteps = deduplicateSteps(steps);
1713
+ return {
1714
+ rawInitialPayload,
1715
+ steps: deduplicatedSteps,
1716
+ isLastDuplicate
1717
+ };
1718
+ }
1719
+ };
1720
+ var handleFailure = async (request, requestPayload, qstashClient, initialPayloadParser, failureFunction, debug) => {
1721
+ if (request.headers.get(WORKFLOW_FAILURE_HEADER) !== "true") {
1722
+ return ok("not-failure-callback");
1723
+ }
1724
+ if (!failureFunction) {
1725
+ return err(
1726
+ new QStashWorkflowError(
1727
+ "Workflow endpoint is called to handle a failure, but a failureFunction is not provided in serve options. Either provide a failureUrl or a failureFunction."
1728
+ )
1729
+ );
1730
+ }
1731
+ try {
1732
+ const { status, header, body, url, sourceHeader, sourceBody, workflowRunId } = JSON.parse(
1733
+ requestPayload
1734
+ );
1735
+ const decodedBody = body ? decodeBase64(body) : "{}";
1736
+ const errorPayload = JSON.parse(decodedBody);
1737
+ const {
1738
+ rawInitialPayload,
1739
+ steps,
1740
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1741
+ isLastDuplicate: _isLastDuplicate
1742
+ } = await parseRequest(decodeBase64(sourceBody), false, debug);
1743
+ const workflowContext = new WorkflowContext({
1744
+ qstashClient,
1745
+ workflowRunId,
1746
+ initialPayload: initialPayloadParser(rawInitialPayload),
1747
+ rawInitialPayload,
1748
+ headers: recreateUserHeaders(new Headers(sourceHeader)),
1749
+ steps,
1750
+ url,
1751
+ failureUrl: url,
1752
+ debug
1753
+ });
1754
+ await failureFunction(workflowContext, status, errorPayload.message, header);
1755
+ } catch (error) {
1756
+ return err(error);
1757
+ }
1758
+ return ok("is-failure-callback");
1759
+ };
1760
+
1761
+ // src/serve/authorization.ts
1762
+ var import_qstash2 = require("@upstash/qstash");
1763
+ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowContext {
1764
+ static disabledMessage = "disabled-qstash-worklfow-run";
1765
+ /**
1766
+ * overwrite the WorkflowContext.addStep method to always raise QStashWorkflowAbort
1767
+ * error in order to stop the execution whenever we encounter a step.
1768
+ *
1769
+ * @param _step
1770
+ */
1771
+ async addStep(_step) {
1772
+ throw new QStashWorkflowAbort(_DisabledWorkflowContext.disabledMessage);
1773
+ }
1774
+ /**
1775
+ * copies the passed context to create a DisabledWorkflowContext. Then, runs the
1776
+ * route function with the new context.
1777
+ *
1778
+ * - returns "run-ended" if there are no steps found or
1779
+ * if the auth failed and user called `return`
1780
+ * - returns "step-found" if DisabledWorkflowContext.addStep is called.
1781
+ * - if there is another error, returns the error.
1782
+ *
1783
+ * @param routeFunction
1784
+ */
1785
+ static async tryAuthentication(routeFunction, context) {
1786
+ const disabledContext = new _DisabledWorkflowContext({
1787
+ qstashClient: new import_qstash2.Client({
1788
+ baseUrl: "disabled-client",
1789
+ token: "disabled-client"
1790
+ }),
1791
+ workflowRunId: context.workflowRunId,
1792
+ headers: context.headers,
1793
+ steps: [],
1794
+ url: context.url,
1795
+ failureUrl: context.failureUrl,
1796
+ initialPayload: context.requestPayload,
1797
+ rawInitialPayload: context.rawInitialPayload,
1798
+ env: context.env,
1799
+ retries: context.retries
1800
+ });
1801
+ try {
1802
+ await routeFunction(disabledContext);
1803
+ } catch (error) {
1804
+ if (error instanceof QStashWorkflowAbort && error.stepName === this.disabledMessage) {
1805
+ return ok("step-found");
1806
+ }
1807
+ return err(error);
1808
+ }
1809
+ return ok("run-ended");
1810
+ }
1811
+ };
1812
+
1813
+ // src/serve/options.ts
1814
+ var import_qstash3 = require("@upstash/qstash");
1815
+ var import_qstash4 = require("@upstash/qstash");
1816
+ var processOptions = (options) => {
1817
+ const environment = options?.env ?? (typeof process === "undefined" ? {} : process.env);
1818
+ const receiverEnvironmentVariablesSet = Boolean(
1819
+ environment.QSTASH_CURRENT_SIGNING_KEY && environment.QSTASH_NEXT_SIGNING_KEY
1820
+ );
1821
+ return {
1822
+ qstashClient: new import_qstash4.Client({
1823
+ baseUrl: environment.QSTASH_URL,
1824
+ token: environment.QSTASH_TOKEN
1825
+ }),
1826
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1827
+ onStepFinish: (workflowRunId, _finishCondition) => new Response(JSON.stringify({ workflowRunId }), {
1828
+ status: 200
1829
+ }),
1830
+ initialPayloadParser: (initialRequest) => {
1831
+ if (!initialRequest) {
1832
+ return void 0;
1833
+ }
1834
+ try {
1835
+ return JSON.parse(initialRequest);
1836
+ } catch (error) {
1837
+ if (error instanceof SyntaxError) {
1838
+ return initialRequest;
1839
+ }
1840
+ throw error;
1841
+ }
1842
+ },
1843
+ receiver: receiverEnvironmentVariablesSet ? new import_qstash3.Receiver({
1844
+ currentSigningKey: environment.QSTASH_CURRENT_SIGNING_KEY,
1845
+ nextSigningKey: environment.QSTASH_NEXT_SIGNING_KEY
1846
+ }) : void 0,
1847
+ baseUrl: environment.UPSTASH_WORKFLOW_URL,
1848
+ env: environment,
1849
+ retries: DEFAULT_RETRIES,
1850
+ ...options
1851
+ };
1852
+ };
1853
+ var determineUrls = async (request, url, baseUrl, failureFunction, failureUrl, debug) => {
1854
+ const initialWorkflowUrl = url ?? request.url;
1855
+ const workflowUrl = baseUrl ? initialWorkflowUrl.replace(/^(https?:\/\/[^/]+)(\/.*)?$/, (_, matchedBaseUrl, path) => {
1856
+ return baseUrl + (path || "");
1857
+ }) : initialWorkflowUrl;
1858
+ if (workflowUrl !== initialWorkflowUrl) {
1859
+ await debug?.log("WARN", "ENDPOINT_START", {
1860
+ warning: `Upstash Workflow: replacing the base of the url with "${baseUrl}" and using it as workflow endpoint.`,
1861
+ originalURL: initialWorkflowUrl,
1862
+ updatedURL: workflowUrl
1863
+ });
1864
+ }
1865
+ const workflowFailureUrl = failureFunction ? workflowUrl : failureUrl;
1866
+ return {
1867
+ workflowUrl,
1868
+ workflowFailureUrl
1869
+ };
1870
+ };
1871
+
1872
+ // src/serve/index.ts
1873
+ var serve = (routeFunction, options) => {
1874
+ const {
1875
+ qstashClient,
1876
+ onStepFinish,
1877
+ initialPayloadParser,
1878
+ url,
1879
+ verbose,
1880
+ receiver,
1881
+ failureUrl,
1882
+ failureFunction,
1883
+ baseUrl,
1884
+ env,
1885
+ retries
1886
+ } = processOptions(options);
1887
+ const debug = WorkflowLogger.getLogger(verbose);
1888
+ const handler = async (request) => {
1889
+ const { workflowUrl, workflowFailureUrl } = await determineUrls(
1890
+ request,
1891
+ url,
1892
+ baseUrl,
1893
+ failureFunction,
1894
+ failureUrl,
1895
+ debug
1896
+ );
1897
+ const requestPayload = await getPayload(request) ?? "";
1898
+ await verifyRequest(requestPayload, request.headers.get("upstash-signature"), receiver);
1899
+ const { isFirstInvocation, workflowRunId } = validateRequest(request);
1900
+ debug?.setWorkflowRunId(workflowRunId);
1901
+ const { rawInitialPayload, steps, isLastDuplicate } = await parseRequest(
1902
+ requestPayload,
1903
+ isFirstInvocation,
1904
+ debug
1905
+ );
1906
+ if (isLastDuplicate) {
1907
+ return onStepFinish("no-workflow-id", "duplicate-step");
1908
+ }
1909
+ const failureCheck = await handleFailure(
1910
+ request,
1911
+ requestPayload,
1912
+ qstashClient,
1913
+ initialPayloadParser,
1914
+ failureFunction
1915
+ );
1916
+ if (failureCheck.isErr()) {
1917
+ throw failureCheck.error;
1918
+ } else if (failureCheck.value === "is-failure-callback") {
1919
+ await debug?.log("WARN", "RESPONSE_DEFAULT", "failureFunction executed");
1920
+ return onStepFinish("no-workflow-id", "failure-callback");
1921
+ }
1922
+ const workflowContext = new WorkflowContext({
1923
+ qstashClient,
1924
+ workflowRunId,
1925
+ initialPayload: initialPayloadParser(rawInitialPayload),
1926
+ rawInitialPayload,
1927
+ headers: recreateUserHeaders(request.headers),
1928
+ steps,
1929
+ url: workflowUrl,
1930
+ failureUrl: workflowFailureUrl,
1931
+ debug,
1932
+ env
1933
+ });
1934
+ const authCheck = await DisabledWorkflowContext.tryAuthentication(
1935
+ routeFunction,
1936
+ workflowContext
1937
+ );
1938
+ if (authCheck.isErr()) {
1939
+ await debug?.log("ERROR", "ERROR", { error: authCheck.error.message });
1940
+ throw authCheck.error;
1941
+ } else if (authCheck.value === "run-ended") {
1942
+ return onStepFinish("no-workflow-id", "auth-fail");
1943
+ }
1944
+ const callReturnCheck = await handleThirdPartyCallResult(
1945
+ request,
1946
+ rawInitialPayload,
1947
+ qstashClient,
1948
+ workflowUrl,
1949
+ workflowFailureUrl,
1950
+ retries,
1951
+ debug
1952
+ );
1953
+ if (callReturnCheck.isErr()) {
1954
+ await debug?.log("ERROR", "SUBMIT_THIRD_PARTY_RESULT", {
1955
+ error: callReturnCheck.error.message
1956
+ });
1957
+ throw callReturnCheck.error;
1958
+ } else if (callReturnCheck.value === "continue-workflow") {
1959
+ const result = isFirstInvocation ? await triggerFirstInvocation(workflowContext, retries, debug) : await triggerRouteFunction({
1960
+ onStep: async () => routeFunction(workflowContext),
1961
+ onCleanup: async () => {
1962
+ await triggerWorkflowDelete(workflowContext, debug);
1963
+ }
1964
+ });
1965
+ if (result.isErr()) {
1966
+ await debug?.log("ERROR", "ERROR", { error: result.error.message });
1967
+ throw result.error;
1968
+ }
1969
+ await debug?.log("INFO", "RESPONSE_WORKFLOW");
1970
+ return onStepFinish(workflowContext.workflowRunId, "success");
1971
+ }
1972
+ await debug?.log("INFO", "RESPONSE_DEFAULT");
1973
+ return onStepFinish("no-workflow-id", "fromCallback");
1974
+ };
1975
+ return async (request) => {
1976
+ try {
1977
+ return await handler(request);
1978
+ } catch (error) {
1979
+ console.error(error);
1980
+ return new Response(JSON.stringify(formatWorkflowError(error)), {
1981
+ status: 500
1982
+ });
1983
+ }
1984
+ };
1985
+ };
1986
+
1987
+ // src/client/index.ts
1988
+ var import_qstash5 = require("@upstash/qstash");
1989
+ var Client3 = class {
1990
+ client;
1991
+ constructor(clientConfig) {
1992
+ if (!clientConfig.baseUrl || !clientConfig.token) {
1993
+ console.warn("[Upstash Workflow] url or the token is not set. client will not work.");
1994
+ }
1995
+ this.client = new import_qstash5.Client(clientConfig);
1996
+ }
1997
+ /**
1998
+ * Cancel an ongoing workflow
1999
+ *
2000
+ * @param workflowRunId run id of the workflow to delete
2001
+ * @returns true if workflow is succesfully deleted. Otherwise throws QStashError
2002
+ */
2003
+ async cancel({ workflowRunId }) {
2004
+ const result = await this.client.http.request({
2005
+ path: ["v2", "workflows", "runs", `${workflowRunId}?cancel=true`],
2006
+ method: "DELETE",
2007
+ parseResponseAsJson: false
2008
+ });
2009
+ return result ?? true;
2010
+ }
2011
+ /**
2012
+ * Notify a workflow run waiting for an event
2013
+ *
2014
+ * @param eventId event id to notify
2015
+ * @param notifyData data to provide to the workflow
2016
+ */
2017
+ async notify({
2018
+ eventId,
2019
+ notifyBody
2020
+ }) {
2021
+ const result = await this.client.http.request({
2022
+ path: ["v2", "notify", eventId],
2023
+ method: "POST",
2024
+ body: notifyBody
2025
+ });
2026
+ return result;
2027
+ }
2028
+ };
2029
+ // Annotate the CommonJS export names for ESM import in node:
2030
+ 0 && (module.exports = {
2031
+ Client,
2032
+ QStashWorkflowAbort,
2033
+ QStashWorkflowError,
2034
+ StepTypes,
2035
+ WorkflowContext,
2036
+ WorkflowLogger,
2037
+ serve
2038
+ });