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