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