@upstash/workflow 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/h3.js CHANGED
@@ -403,11 +403,12 @@ var WORKFLOW_PROTOCOL_VERSION_HEADER = "Upstash-Workflow-Sdk-Version";
403
403
  var DEFAULT_CONTENT_TYPE = "application/json";
404
404
  var NO_CONCURRENCY = 1;
405
405
  var DEFAULT_RETRIES = 3;
406
- var VERSION = "v0.2.7";
406
+ var VERSION = "v0.2.13";
407
407
  var SDK_TELEMETRY = `@upstash/workflow@${VERSION}`;
408
408
  var TELEMETRY_HEADER_SDK = "Upstash-Telemetry-Sdk";
409
409
  var TELEMETRY_HEADER_FRAMEWORK = "Upstash-Telemetry-Framework";
410
410
  var TELEMETRY_HEADER_RUNTIME = "Upstash-Telemetry-Runtime";
411
+ var TELEMETRY_HEADER_AGENT = "Upstash-Telemetry-Agent";
411
412
 
412
413
  // src/error.ts
413
414
  var import_qstash2 = require("@upstash/qstash");
@@ -446,10 +447,16 @@ var formatWorkflowError = (error) => {
446
447
  message: error.message
447
448
  } : {
448
449
  error: "Error",
449
- message: "An error occured while executing workflow."
450
+ message: `An error occured while executing workflow: '${typeof error === "string" ? error : JSON.stringify(error)}'`
450
451
  };
451
452
  };
452
453
 
454
+ // src/context/auto-executor.ts
455
+ var import_qstash5 = require("@upstash/qstash");
456
+
457
+ // src/qstash/headers.ts
458
+ var import_qstash4 = require("@upstash/qstash");
459
+
453
460
  // src/utils.ts
454
461
  var NANOID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
455
462
  var NANOID_LENGTH = 21;
@@ -475,574 +482,231 @@ function decodeBase64(base64) {
475
482
  }
476
483
  }
477
484
 
478
- // src/context/steps.ts
479
- var BaseLazyStep = class _BaseLazyStep {
480
- stepName;
481
- constructor(stepName) {
482
- if (!stepName) {
483
- throw new WorkflowError(
484
- "A workflow step name cannot be undefined or an empty string. Please provide a name for your workflow step."
485
- );
486
- }
487
- this.stepName = stepName;
485
+ // node_modules/neverthrow/dist/index.es.js
486
+ var defaultErrorConfig = {
487
+ withStackTrace: false
488
+ };
489
+ var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
490
+ const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
491
+ const maybeStack = config.withStackTrace ? new Error().stack : void 0;
492
+ return {
493
+ data,
494
+ message,
495
+ stack: maybeStack
496
+ };
497
+ };
498
+ function __awaiter(thisArg, _arguments, P, generator) {
499
+ function adopt(value) {
500
+ return value instanceof P ? value : new P(function(resolve) {
501
+ resolve(value);
502
+ });
488
503
  }
489
- /**
490
- * parse the out field of a step result.
491
- *
492
- * will be called when returning the steps to the context from auto executor
493
- *
494
- * @param out field of the step
495
- * @returns parsed out field
496
- */
497
- parseOut(out) {
498
- if (out === void 0) {
499
- if (this.allowUndefinedOut) {
500
- return void 0;
501
- } else {
502
- throw new WorkflowError(
503
- `Error while parsing output of ${this.stepType} step. Expected a string, but got: undefined`
504
- );
504
+ return new (P || (P = Promise))(function(resolve, reject) {
505
+ function fulfilled(value) {
506
+ try {
507
+ step(generator.next(value));
508
+ } catch (e) {
509
+ reject(e);
505
510
  }
506
511
  }
507
- if (typeof out === "object") {
508
- if (this.stepType !== "Wait") {
509
- console.warn(
510
- `Error while parsing ${this.stepType} step output. Expected a string, but got object. Please reach out to Upstash Support.`
511
- );
512
- return out;
512
+ function rejected(value) {
513
+ try {
514
+ step(generator["throw"](value));
515
+ } catch (e) {
516
+ reject(e);
513
517
  }
514
- return {
515
- ...out,
516
- eventData: _BaseLazyStep.tryParsing(out.eventData)
517
- };
518
518
  }
519
- if (typeof out !== "string") {
520
- throw new WorkflowError(
521
- `Error while parsing output of ${this.stepType} step. Expected a string or undefined, but got: ${typeof out}`
522
- );
519
+ function step(result) {
520
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
523
521
  }
524
- return this.safeParseOut(out);
525
- }
526
- safeParseOut(out) {
527
- return _BaseLazyStep.tryParsing(out);
522
+ step((generator = generator.apply(thisArg, [])).next());
523
+ });
524
+ }
525
+ function __values(o) {
526
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
527
+ if (m) return m.call(o);
528
+ if (o && typeof o.length === "number") return {
529
+ next: function() {
530
+ if (o && i >= o.length) o = void 0;
531
+ return { value: o && o[i++], done: !o };
532
+ }
533
+ };
534
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
535
+ }
536
+ function __await(v) {
537
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
538
+ }
539
+ function __asyncGenerator(thisArg, _arguments, generator) {
540
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
541
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
542
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
543
+ return this;
544
+ }, i;
545
+ function verb(n) {
546
+ if (g[n]) i[n] = function(v) {
547
+ return new Promise(function(a, b) {
548
+ q.push([n, v, a, b]) > 1 || resume(n, v);
549
+ });
550
+ };
528
551
  }
529
- static tryParsing(stepOut) {
552
+ function resume(n, v) {
530
553
  try {
531
- return JSON.parse(stepOut);
532
- } catch {
533
- return stepOut;
554
+ step(g[n](v));
555
+ } catch (e) {
556
+ settle(q[0][3], e);
534
557
  }
535
558
  }
536
- };
537
- var LazyFunctionStep = class extends BaseLazyStep {
538
- stepFunction;
539
- stepType = "Run";
540
- allowUndefinedOut = true;
541
- constructor(stepName, stepFunction) {
542
- super(stepName);
543
- this.stepFunction = stepFunction;
559
+ function step(r) {
560
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
544
561
  }
545
- getPlanStep(concurrent, targetStep) {
546
- return {
547
- stepId: 0,
548
- stepName: this.stepName,
549
- stepType: this.stepType,
550
- concurrent,
551
- targetStep
552
- };
562
+ function fulfill(value) {
563
+ resume("next", value);
553
564
  }
554
- async getResultStep(concurrent, stepId) {
555
- let result = this.stepFunction();
556
- if (result instanceof Promise) {
557
- result = await result;
558
- }
559
- return {
560
- stepId,
561
- stepName: this.stepName,
562
- stepType: this.stepType,
563
- out: result,
564
- concurrent
565
- };
565
+ function reject(value) {
566
+ resume("throw", value);
566
567
  }
567
- };
568
- var LazySleepStep = class extends BaseLazyStep {
569
- sleep;
570
- stepType = "SleepFor";
571
- allowUndefinedOut = true;
572
- constructor(stepName, sleep) {
573
- super(stepName);
574
- this.sleep = sleep;
568
+ function settle(f, v) {
569
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
575
570
  }
576
- getPlanStep(concurrent, targetStep) {
577
- return {
578
- stepId: 0,
579
- stepName: this.stepName,
580
- stepType: this.stepType,
581
- sleepFor: this.sleep,
582
- concurrent,
583
- targetStep
571
+ }
572
+ function __asyncDelegator(o) {
573
+ var i, p;
574
+ return i = {}, verb("next"), verb("throw", function(e) {
575
+ throw e;
576
+ }), verb("return"), i[Symbol.iterator] = function() {
577
+ return this;
578
+ }, i;
579
+ function verb(n, f) {
580
+ i[n] = o[n] ? function(v) {
581
+ return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
582
+ } : f;
583
+ }
584
+ }
585
+ function __asyncValues(o) {
586
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
587
+ var m = o[Symbol.asyncIterator], i;
588
+ 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() {
589
+ return this;
590
+ }, i);
591
+ function verb(n) {
592
+ i[n] = o[n] && function(v) {
593
+ return new Promise(function(resolve, reject) {
594
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
595
+ });
584
596
  };
585
597
  }
586
- async getResultStep(concurrent, stepId) {
587
- return await Promise.resolve({
588
- stepId,
589
- stepName: this.stepName,
590
- stepType: this.stepType,
591
- sleepFor: this.sleep,
592
- concurrent
593
- });
598
+ function settle(resolve, reject, d, v) {
599
+ Promise.resolve(v).then(function(v2) {
600
+ resolve({ value: v2, done: d });
601
+ }, reject);
594
602
  }
595
- };
596
- var LazySleepUntilStep = class extends BaseLazyStep {
597
- sleepUntil;
598
- stepType = "SleepUntil";
599
- allowUndefinedOut = true;
600
- constructor(stepName, sleepUntil) {
601
- super(stepName);
602
- this.sleepUntil = sleepUntil;
603
+ }
604
+ var ResultAsync = class _ResultAsync {
605
+ constructor(res) {
606
+ this._promise = res;
603
607
  }
604
- getPlanStep(concurrent, targetStep) {
605
- return {
606
- stepId: 0,
607
- stepName: this.stepName,
608
- stepType: this.stepType,
609
- sleepUntil: this.sleepUntil,
610
- concurrent,
611
- targetStep
612
- };
608
+ static fromSafePromise(promise) {
609
+ const newPromise = promise.then((value) => new Ok(value));
610
+ return new _ResultAsync(newPromise);
613
611
  }
614
- async getResultStep(concurrent, stepId) {
615
- return await Promise.resolve({
616
- stepId,
617
- stepName: this.stepName,
618
- stepType: this.stepType,
619
- sleepUntil: this.sleepUntil,
620
- concurrent
621
- });
612
+ static fromPromise(promise, errorFn) {
613
+ const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
614
+ return new _ResultAsync(newPromise);
622
615
  }
623
- safeParseOut() {
624
- return void 0;
616
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
617
+ static fromThrowable(fn, errorFn) {
618
+ return (...args) => {
619
+ return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
620
+ try {
621
+ return new Ok(yield fn(...args));
622
+ } catch (error) {
623
+ return new Err(errorFn ? errorFn(error) : error);
624
+ }
625
+ }))());
626
+ };
625
627
  }
626
- };
627
- var LazyCallStep = class _LazyCallStep extends BaseLazyStep {
628
- url;
629
- method;
630
- body;
631
- headers;
632
- retries;
633
- timeout;
634
- flowControl;
635
- stepType = "Call";
636
- allowUndefinedOut = false;
637
- constructor(stepName, url, method, body, headers, retries, timeout, flowControl) {
638
- super(stepName);
639
- this.url = url;
640
- this.method = method;
641
- this.body = body;
642
- this.headers = headers;
643
- this.retries = retries;
644
- this.timeout = timeout;
645
- this.flowControl = flowControl;
646
- }
647
- getPlanStep(concurrent, targetStep) {
648
- return {
649
- stepId: 0,
650
- stepName: this.stepName,
651
- stepType: this.stepType,
652
- concurrent,
653
- targetStep
654
- };
628
+ static combine(asyncResultList) {
629
+ return combineResultAsyncList(asyncResultList);
655
630
  }
656
- async getResultStep(concurrent, stepId) {
657
- return await Promise.resolve({
658
- stepId,
659
- stepName: this.stepName,
660
- stepType: this.stepType,
661
- concurrent,
662
- callUrl: this.url,
663
- callMethod: this.method,
664
- callBody: this.body,
665
- callHeaders: this.headers
666
- });
631
+ static combineWithAllErrors(asyncResultList) {
632
+ return combineResultAsyncListWithAllErrors(asyncResultList);
667
633
  }
668
- safeParseOut(out) {
669
- const { header, status, body } = JSON.parse(out);
670
- const responseHeaders = new Headers(header);
671
- if (_LazyCallStep.isText(responseHeaders.get("content-type"))) {
672
- const bytes = new Uint8Array(out.length);
673
- for (let i = 0; i < out.length; i++) {
674
- bytes[i] = out.charCodeAt(i);
634
+ map(f) {
635
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
636
+ if (res.isErr()) {
637
+ return new Err(res.error);
675
638
  }
676
- const processedResult = new TextDecoder().decode(bytes);
677
- const newBody = JSON.parse(processedResult).body;
678
- return {
679
- status,
680
- header,
681
- body: BaseLazyStep.tryParsing(newBody)
682
- };
683
- } else {
684
- return { header, status, body };
685
- }
686
- }
687
- static applicationHeaders = /* @__PURE__ */ new Set([
688
- "application/json",
689
- "application/xml",
690
- "application/javascript",
691
- "application/x-www-form-urlencoded",
692
- "application/xhtml+xml",
693
- "application/ld+json",
694
- "application/rss+xml",
695
- "application/atom+xml"
696
- ]);
697
- static isText = (contentTypeHeader) => {
698
- if (!contentTypeHeader) {
699
- return false;
700
- }
701
- if (_LazyCallStep.applicationHeaders.has(contentTypeHeader)) {
702
- return true;
703
- }
704
- if (contentTypeHeader.startsWith("text/")) {
705
- return true;
706
- }
707
- return false;
708
- };
709
- };
710
- var LazyWaitForEventStep = class extends BaseLazyStep {
711
- eventId;
712
- timeout;
713
- stepType = "Wait";
714
- allowUndefinedOut = false;
715
- constructor(stepName, eventId, timeout) {
716
- super(stepName);
717
- this.eventId = eventId;
718
- this.timeout = timeout;
639
+ return new Ok(yield f(res.value));
640
+ })));
719
641
  }
720
- getPlanStep(concurrent, targetStep) {
721
- return {
722
- stepId: 0,
723
- stepName: this.stepName,
724
- stepType: this.stepType,
725
- waitEventId: this.eventId,
726
- timeout: this.timeout,
727
- concurrent,
728
- targetStep
729
- };
642
+ andThrough(f) {
643
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
644
+ if (res.isErr()) {
645
+ return new Err(res.error);
646
+ }
647
+ const newRes = yield f(res.value);
648
+ if (newRes.isErr()) {
649
+ return new Err(newRes.error);
650
+ }
651
+ return new Ok(res.value);
652
+ })));
730
653
  }
731
- async getResultStep(concurrent, stepId) {
732
- return await Promise.resolve({
733
- stepId,
734
- stepName: this.stepName,
735
- stepType: this.stepType,
736
- waitEventId: this.eventId,
737
- timeout: this.timeout,
738
- concurrent
739
- });
654
+ andTee(f) {
655
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
656
+ if (res.isErr()) {
657
+ return new Err(res.error);
658
+ }
659
+ try {
660
+ yield f(res.value);
661
+ } catch (e) {
662
+ }
663
+ return new Ok(res.value);
664
+ })));
740
665
  }
741
- safeParseOut(out) {
742
- const result = JSON.parse(out);
743
- return {
744
- ...result,
745
- eventData: BaseLazyStep.tryParsing(result.eventData)
746
- };
666
+ mapErr(f) {
667
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
668
+ if (res.isOk()) {
669
+ return new Ok(res.value);
670
+ }
671
+ return new Err(yield f(res.error));
672
+ })));
747
673
  }
748
- };
749
- var LazyNotifyStep = class extends LazyFunctionStep {
750
- stepType = "Notify";
751
- constructor(stepName, eventId, eventData, requester) {
752
- super(stepName, async () => {
753
- const notifyResponse = await makeNotifyRequest(requester, eventId, eventData);
754
- return {
755
- eventId,
756
- eventData,
757
- notifyResponse
758
- };
759
- });
674
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
675
+ andThen(f) {
676
+ return new _ResultAsync(this._promise.then((res) => {
677
+ if (res.isErr()) {
678
+ return new Err(res.error);
679
+ }
680
+ const newValue = f(res.value);
681
+ return newValue instanceof _ResultAsync ? newValue._promise : newValue;
682
+ }));
760
683
  }
761
- safeParseOut(out) {
762
- const result = JSON.parse(out);
763
- return {
764
- ...result,
765
- eventData: BaseLazyStep.tryParsing(result.eventData)
766
- };
684
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
685
+ orElse(f) {
686
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
687
+ if (res.isErr()) {
688
+ return f(res.error);
689
+ }
690
+ return new Ok(res.value);
691
+ })));
767
692
  }
768
- };
769
- var LazyInvokeStep = class extends BaseLazyStep {
770
- stepType = "Invoke";
771
- params;
772
- allowUndefinedOut = false;
773
- constructor(stepName, {
774
- workflow,
775
- body,
776
- headers = {},
777
- workflowRunId,
778
- retries,
779
- flowControl
780
- }) {
781
- super(stepName);
782
- this.params = {
783
- workflow,
784
- body,
785
- headers,
786
- workflowRunId: getWorkflowRunId(workflowRunId),
787
- retries,
788
- flowControl
789
- };
693
+ match(ok2, _err) {
694
+ return this._promise.then((res) => res.match(ok2, _err));
790
695
  }
791
- getPlanStep(concurrent, targetStep) {
792
- return {
793
- stepId: 0,
794
- stepName: this.stepName,
795
- stepType: this.stepType,
796
- concurrent,
797
- targetStep
798
- };
696
+ unwrapOr(t) {
697
+ return this._promise.then((res) => res.unwrapOr(t));
799
698
  }
800
699
  /**
801
- * won't be used as it's the server who will add the result step
802
- * in Invoke step.
700
+ * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
803
701
  */
804
- getResultStep(concurrent, stepId) {
805
- return Promise.resolve({
806
- stepId,
807
- stepName: this.stepName,
808
- stepType: this.stepType,
809
- concurrent
702
+ safeUnwrap() {
703
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
704
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
810
705
  });
811
706
  }
812
- safeParseOut(out) {
813
- const result = JSON.parse(out);
814
- return {
815
- ...result,
816
- body: BaseLazyStep.tryParsing(result.body)
817
- };
818
- }
819
- };
820
-
821
- // node_modules/neverthrow/dist/index.es.js
822
- var defaultErrorConfig = {
823
- withStackTrace: false
824
- };
825
- var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
826
- const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
827
- const maybeStack = config.withStackTrace ? new Error().stack : void 0;
828
- return {
829
- data,
830
- message,
831
- stack: maybeStack
832
- };
833
- };
834
- function __awaiter(thisArg, _arguments, P, generator) {
835
- function adopt(value) {
836
- return value instanceof P ? value : new P(function(resolve) {
837
- resolve(value);
838
- });
839
- }
840
- return new (P || (P = Promise))(function(resolve, reject) {
841
- function fulfilled(value) {
842
- try {
843
- step(generator.next(value));
844
- } catch (e) {
845
- reject(e);
846
- }
847
- }
848
- function rejected(value) {
849
- try {
850
- step(generator["throw"](value));
851
- } catch (e) {
852
- reject(e);
853
- }
854
- }
855
- function step(result) {
856
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
857
- }
858
- step((generator = generator.apply(thisArg, [])).next());
859
- });
860
- }
861
- function __values(o) {
862
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
863
- if (m) return m.call(o);
864
- if (o && typeof o.length === "number") return {
865
- next: function() {
866
- if (o && i >= o.length) o = void 0;
867
- return { value: o && o[i++], done: !o };
868
- }
869
- };
870
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
871
- }
872
- function __await(v) {
873
- return this instanceof __await ? (this.v = v, this) : new __await(v);
874
- }
875
- function __asyncGenerator(thisArg, _arguments, generator) {
876
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
877
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
878
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
879
- return this;
880
- }, i;
881
- function verb(n) {
882
- if (g[n]) i[n] = function(v) {
883
- return new Promise(function(a, b) {
884
- q.push([n, v, a, b]) > 1 || resume(n, v);
885
- });
886
- };
887
- }
888
- function resume(n, v) {
889
- try {
890
- step(g[n](v));
891
- } catch (e) {
892
- settle(q[0][3], e);
893
- }
894
- }
895
- function step(r) {
896
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
897
- }
898
- function fulfill(value) {
899
- resume("next", value);
900
- }
901
- function reject(value) {
902
- resume("throw", value);
903
- }
904
- function settle(f, v) {
905
- if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
906
- }
907
- }
908
- function __asyncDelegator(o) {
909
- var i, p;
910
- return i = {}, verb("next"), verb("throw", function(e) {
911
- throw e;
912
- }), verb("return"), i[Symbol.iterator] = function() {
913
- return this;
914
- }, i;
915
- function verb(n, f) {
916
- i[n] = o[n] ? function(v) {
917
- return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
918
- } : f;
919
- }
920
- }
921
- function __asyncValues(o) {
922
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
923
- var m = o[Symbol.asyncIterator], i;
924
- 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() {
925
- return this;
926
- }, i);
927
- function verb(n) {
928
- i[n] = o[n] && function(v) {
929
- return new Promise(function(resolve, reject) {
930
- v = o[n](v), settle(resolve, reject, v.done, v.value);
931
- });
932
- };
933
- }
934
- function settle(resolve, reject, d, v) {
935
- Promise.resolve(v).then(function(v2) {
936
- resolve({ value: v2, done: d });
937
- }, reject);
938
- }
939
- }
940
- var ResultAsync = class _ResultAsync {
941
- constructor(res) {
942
- this._promise = res;
943
- }
944
- static fromSafePromise(promise) {
945
- const newPromise = promise.then((value) => new Ok(value));
946
- return new _ResultAsync(newPromise);
947
- }
948
- static fromPromise(promise, errorFn) {
949
- const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
950
- return new _ResultAsync(newPromise);
951
- }
952
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
953
- static fromThrowable(fn, errorFn) {
954
- return (...args) => {
955
- return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
956
- try {
957
- return new Ok(yield fn(...args));
958
- } catch (error) {
959
- return new Err(errorFn ? errorFn(error) : error);
960
- }
961
- }))());
962
- };
963
- }
964
- static combine(asyncResultList) {
965
- return combineResultAsyncList(asyncResultList);
966
- }
967
- static combineWithAllErrors(asyncResultList) {
968
- return combineResultAsyncListWithAllErrors(asyncResultList);
969
- }
970
- map(f) {
971
- return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
972
- if (res.isErr()) {
973
- return new Err(res.error);
974
- }
975
- return new Ok(yield f(res.value));
976
- })));
977
- }
978
- andThrough(f) {
979
- return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
980
- if (res.isErr()) {
981
- return new Err(res.error);
982
- }
983
- const newRes = yield f(res.value);
984
- if (newRes.isErr()) {
985
- return new Err(newRes.error);
986
- }
987
- return new Ok(res.value);
988
- })));
989
- }
990
- andTee(f) {
991
- return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
992
- if (res.isErr()) {
993
- return new Err(res.error);
994
- }
995
- try {
996
- yield f(res.value);
997
- } catch (e) {
998
- }
999
- return new Ok(res.value);
1000
- })));
1001
- }
1002
- mapErr(f) {
1003
- return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
1004
- if (res.isOk()) {
1005
- return new Ok(res.value);
1006
- }
1007
- return new Err(yield f(res.error));
1008
- })));
1009
- }
1010
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1011
- andThen(f) {
1012
- return new _ResultAsync(this._promise.then((res) => {
1013
- if (res.isErr()) {
1014
- return new Err(res.error);
1015
- }
1016
- const newValue = f(res.value);
1017
- return newValue instanceof _ResultAsync ? newValue._promise : newValue;
1018
- }));
1019
- }
1020
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
1021
- orElse(f) {
1022
- return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
1023
- if (res.isErr()) {
1024
- return f(res.error);
1025
- }
1026
- return new Ok(res.value);
1027
- })));
1028
- }
1029
- match(ok2, _err) {
1030
- return this._promise.then((res) => res.match(ok2, _err));
1031
- }
1032
- unwrapOr(t) {
1033
- return this._promise.then((res) => res.unwrapOr(t));
1034
- }
1035
- /**
1036
- * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
1037
- */
1038
- safeUnwrap() {
1039
- return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
1040
- return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
1041
- });
1042
- }
1043
- // Makes ResultAsync implement PromiseLike<Result>
1044
- then(successCallback, failureCallback) {
1045
- return this._promise.then(successCallback, failureCallback);
707
+ // Makes ResultAsync implement PromiseLike<Result>
708
+ then(successCallback, failureCallback) {
709
+ return this._promise.then(successCallback, failureCallback);
1046
710
  }
1047
711
  };
1048
712
  var errAsync = (err2) => new ResultAsync(Promise.resolve(new Err(err2)));
@@ -1252,18 +916,22 @@ var triggerFirstInvocation = async ({
1252
916
  useJSONContent,
1253
917
  telemetry: telemetry2,
1254
918
  debug,
1255
- invokeCount
919
+ invokeCount,
920
+ delay
1256
921
  }) => {
1257
922
  const { headers } = getHeaders({
1258
923
  initHeaderValue: "true",
1259
- workflowRunId: workflowContext.workflowRunId,
1260
- workflowUrl: workflowContext.url,
1261
- userHeaders: workflowContext.headers,
1262
- failureUrl: workflowContext.failureUrl,
1263
- retries: workflowContext.retries,
1264
- telemetry: telemetry2,
1265
- invokeCount,
1266
- flowControl: workflowContext.flowControl
924
+ workflowConfig: {
925
+ workflowRunId: workflowContext.workflowRunId,
926
+ workflowUrl: workflowContext.url,
927
+ failureUrl: workflowContext.failureUrl,
928
+ retries: workflowContext.retries,
929
+ telemetry: telemetry2,
930
+ flowControl: workflowContext.flowControl,
931
+ useJSONContent: useJSONContent ?? false
932
+ },
933
+ invokeCount: invokeCount ?? 0,
934
+ userHeaders: workflowContext.headers
1267
935
  });
1268
936
  if (workflowContext.headers.get("content-type")) {
1269
937
  headers["content-type"] = workflowContext.headers.get("content-type");
@@ -1277,7 +945,8 @@ var triggerFirstInvocation = async ({
1277
945
  headers,
1278
946
  method: "POST",
1279
947
  body,
1280
- url: workflowContext.url
948
+ url: workflowContext.url,
949
+ delay
1281
950
  });
1282
951
  if (result.deduplicated) {
1283
952
  await debug?.log("WARN", "SUBMIT_FIRST_INVOCATION", {
@@ -1433,14 +1102,16 @@ ${atob(callbackMessage.body ?? "")}`
1433
1102
  const userHeaders = recreateUserHeaders(request.headers);
1434
1103
  const { headers: requestHeaders } = getHeaders({
1435
1104
  initHeaderValue: "false",
1436
- workflowRunId,
1437
- workflowUrl,
1105
+ workflowConfig: {
1106
+ workflowRunId,
1107
+ workflowUrl,
1108
+ failureUrl,
1109
+ retries,
1110
+ telemetry: telemetry2,
1111
+ flowControl
1112
+ },
1438
1113
  userHeaders,
1439
- failureUrl,
1440
- retries,
1441
- telemetry: telemetry2,
1442
- invokeCount: Number(invokeCount),
1443
- flowControl
1114
+ invokeCount: Number(invokeCount)
1444
1115
  });
1445
1116
  const callResponse = {
1446
1117
  status: callbackMessage.status,
@@ -1486,329 +1157,899 @@ var getTelemetryHeaders = (telemetry2) => {
1486
1157
  [TELEMETRY_HEADER_RUNTIME]: telemetry2.runtime ?? "unknown"
1487
1158
  };
1488
1159
  };
1489
- var getHeaders = ({
1490
- initHeaderValue,
1491
- workflowRunId,
1492
- workflowUrl,
1493
- userHeaders,
1494
- failureUrl,
1495
- retries,
1496
- step,
1497
- callRetries,
1498
- callTimeout,
1499
- telemetry: telemetry2,
1500
- invokeCount,
1501
- flowControl,
1502
- callFlowControl
1503
- }) => {
1504
- const callHeaders = new Headers(step?.callHeaders);
1505
- const contentType = (callHeaders.get("content-type") ? callHeaders.get("content-type") : userHeaders?.get("Content-Type") ? userHeaders.get("Content-Type") : void 0) ?? DEFAULT_CONTENT_TYPE;
1506
- const baseHeaders = {
1507
- [WORKFLOW_INIT_HEADER]: initHeaderValue,
1508
- [WORKFLOW_ID_HEADER]: workflowRunId,
1509
- [WORKFLOW_URL_HEADER]: workflowUrl,
1510
- [WORKFLOW_FEATURE_HEADER]: "LazyFetch,InitialBody",
1511
- [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
1512
- "content-type": contentType,
1513
- ...telemetry2 ? getTelemetryHeaders(telemetry2) : {}
1514
- };
1515
- if (invokeCount !== void 0 && !step?.callUrl) {
1516
- baseHeaders[`Upstash-Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount.toString();
1517
- }
1518
- if (!step?.callUrl) {
1519
- baseHeaders[`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`] = WORKFLOW_PROTOCOL_VERSION;
1520
- }
1521
- if (callTimeout) {
1522
- baseHeaders[`Upstash-Timeout`] = callTimeout.toString();
1523
- }
1524
- if (failureUrl) {
1525
- baseHeaders[`Upstash-Failure-Callback-Forward-${WORKFLOW_FAILURE_HEADER}`] = "true";
1526
- baseHeaders[`Upstash-Failure-Callback-Forward-Upstash-Workflow-Failure-Callback`] = "true";
1527
- baseHeaders["Upstash-Failure-Callback-Workflow-Runid"] = workflowRunId;
1528
- baseHeaders["Upstash-Failure-Callback-Workflow-Init"] = "false";
1529
- baseHeaders["Upstash-Failure-Callback-Workflow-Url"] = workflowUrl;
1530
- baseHeaders["Upstash-Failure-Callback-Workflow-Calltype"] = "failureCall";
1531
- if (retries !== void 0) {
1532
- baseHeaders["Upstash-Failure-Callback-Retries"] = retries.toString();
1533
- }
1534
- if (flowControl) {
1535
- const { flowControlKey, flowControlValue } = prepareFlowControl(flowControl);
1536
- baseHeaders["Upstash-Failure-Callback-Flow-Control-Key"] = flowControlKey;
1537
- baseHeaders["Upstash-Failure-Callback-Flow-Control-Value"] = flowControlValue;
1538
- }
1539
- if (!step?.callUrl) {
1540
- baseHeaders["Upstash-Failure-Callback"] = failureUrl;
1541
- }
1542
- }
1543
- if (step?.callUrl) {
1544
- baseHeaders["Upstash-Retries"] = callRetries?.toString() ?? "0";
1545
- baseHeaders[WORKFLOW_FEATURE_HEADER] = "WF_NoDelete,InitialBody";
1546
- if (retries !== void 0) {
1547
- baseHeaders["Upstash-Callback-Retries"] = retries.toString();
1548
- baseHeaders["Upstash-Failure-Callback-Retries"] = retries.toString();
1549
- }
1550
- if (callFlowControl) {
1551
- const { flowControlKey, flowControlValue } = prepareFlowControl(callFlowControl);
1552
- baseHeaders["Upstash-Flow-Control-Key"] = flowControlKey;
1553
- baseHeaders["Upstash-Flow-Control-Value"] = flowControlValue;
1554
- }
1555
- if (flowControl) {
1556
- const { flowControlKey, flowControlValue } = prepareFlowControl(flowControl);
1557
- baseHeaders["Upstash-Callback-Flow-Control-Key"] = flowControlKey;
1558
- baseHeaders["Upstash-Callback-Flow-Control-Value"] = flowControlValue;
1160
+ var verifyRequest = async (body, signature, verifier) => {
1161
+ if (!verifier) {
1162
+ return;
1163
+ }
1164
+ try {
1165
+ if (!signature) {
1166
+ throw new Error("`Upstash-Signature` header is not passed.");
1559
1167
  }
1560
- } else {
1561
- if (flowControl) {
1562
- const { flowControlKey, flowControlValue } = prepareFlowControl(flowControl);
1563
- baseHeaders["Upstash-Flow-Control-Key"] = flowControlKey;
1564
- baseHeaders["Upstash-Flow-Control-Value"] = flowControlValue;
1168
+ const isValid = await verifier.verify({
1169
+ body,
1170
+ signature
1171
+ });
1172
+ if (!isValid) {
1173
+ throw new Error("Signature in `Upstash-Signature` header is not valid");
1174
+ }
1175
+ } catch (error) {
1176
+ throw new WorkflowError(
1177
+ `Failed to verify that the Workflow request comes from QStash: ${error}
1178
+
1179
+ If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
1180
+
1181
+ If you want to disable QStash Verification, you should clear env variables QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY`
1182
+ );
1183
+ }
1184
+ };
1185
+
1186
+ // src/context/steps.ts
1187
+ var BaseLazyStep = class _BaseLazyStep {
1188
+ stepName;
1189
+ constructor(stepName) {
1190
+ if (!stepName) {
1191
+ throw new WorkflowError(
1192
+ "A workflow step name cannot be undefined or an empty string. Please provide a name for your workflow step."
1193
+ );
1194
+ }
1195
+ if (typeof stepName !== "string") {
1196
+ console.warn(
1197
+ "Workflow Warning: A workflow step name must be a string. In a future release, this will throw an error."
1198
+ );
1199
+ }
1200
+ this.stepName = stepName;
1201
+ }
1202
+ /**
1203
+ * parse the out field of a step result.
1204
+ *
1205
+ * will be called when returning the steps to the context from auto executor
1206
+ *
1207
+ * @param out field of the step
1208
+ * @returns parsed out field
1209
+ */
1210
+ parseOut(out) {
1211
+ if (out === void 0) {
1212
+ if (this.allowUndefinedOut) {
1213
+ return void 0;
1214
+ } else {
1215
+ throw new WorkflowError(
1216
+ `Error while parsing output of ${this.stepType} step. Expected a string, but got: undefined`
1217
+ );
1218
+ }
1219
+ }
1220
+ if (typeof out === "object") {
1221
+ if (this.stepType !== "Wait") {
1222
+ console.warn(
1223
+ `Error while parsing ${this.stepType} step output. Expected a string, but got object. Please reach out to Upstash Support.`
1224
+ );
1225
+ return out;
1226
+ }
1227
+ return {
1228
+ ...out,
1229
+ eventData: _BaseLazyStep.tryParsing(out.eventData)
1230
+ };
1231
+ }
1232
+ if (typeof out !== "string") {
1233
+ throw new WorkflowError(
1234
+ `Error while parsing output of ${this.stepType} step. Expected a string or undefined, but got: ${typeof out}`
1235
+ );
1236
+ }
1237
+ return this.safeParseOut(out);
1238
+ }
1239
+ safeParseOut(out) {
1240
+ return _BaseLazyStep.tryParsing(out);
1241
+ }
1242
+ static tryParsing(stepOut) {
1243
+ try {
1244
+ return JSON.parse(stepOut);
1245
+ } catch {
1246
+ return stepOut;
1247
+ }
1248
+ }
1249
+ getBody({ step }) {
1250
+ step.out = JSON.stringify(step.out);
1251
+ return JSON.stringify(step);
1252
+ }
1253
+ getHeaders({ context, telemetry: telemetry2, invokeCount, step }) {
1254
+ return getHeaders({
1255
+ initHeaderValue: "false",
1256
+ workflowConfig: {
1257
+ workflowRunId: context.workflowRunId,
1258
+ workflowUrl: context.url,
1259
+ failureUrl: context.failureUrl,
1260
+ retries: context.retries,
1261
+ useJSONContent: false,
1262
+ telemetry: telemetry2,
1263
+ flowControl: context.flowControl
1264
+ },
1265
+ userHeaders: context.headers,
1266
+ invokeCount,
1267
+ stepInfo: {
1268
+ step,
1269
+ lazyStep: this
1270
+ }
1271
+ });
1272
+ }
1273
+ async submitStep({ context, body, headers }) {
1274
+ return await context.qstashClient.batch([
1275
+ {
1276
+ body,
1277
+ headers,
1278
+ method: "POST",
1279
+ url: context.url
1280
+ }
1281
+ ]);
1282
+ }
1283
+ };
1284
+ var LazyFunctionStep = class extends BaseLazyStep {
1285
+ stepFunction;
1286
+ stepType = "Run";
1287
+ allowUndefinedOut = true;
1288
+ constructor(stepName, stepFunction) {
1289
+ super(stepName);
1290
+ this.stepFunction = stepFunction;
1291
+ }
1292
+ getPlanStep(concurrent, targetStep) {
1293
+ return {
1294
+ stepId: 0,
1295
+ stepName: this.stepName,
1296
+ stepType: this.stepType,
1297
+ concurrent,
1298
+ targetStep
1299
+ };
1300
+ }
1301
+ async getResultStep(concurrent, stepId) {
1302
+ let result = this.stepFunction();
1303
+ if (result instanceof Promise) {
1304
+ result = await result;
1305
+ }
1306
+ return {
1307
+ stepId,
1308
+ stepName: this.stepName,
1309
+ stepType: this.stepType,
1310
+ out: result,
1311
+ concurrent
1312
+ };
1313
+ }
1314
+ };
1315
+ var LazySleepStep = class extends BaseLazyStep {
1316
+ sleep;
1317
+ stepType = "SleepFor";
1318
+ allowUndefinedOut = true;
1319
+ constructor(stepName, sleep) {
1320
+ super(stepName);
1321
+ this.sleep = sleep;
1322
+ }
1323
+ getPlanStep(concurrent, targetStep) {
1324
+ return {
1325
+ stepId: 0,
1326
+ stepName: this.stepName,
1327
+ stepType: this.stepType,
1328
+ sleepFor: this.sleep,
1329
+ concurrent,
1330
+ targetStep
1331
+ };
1332
+ }
1333
+ async getResultStep(concurrent, stepId) {
1334
+ return await Promise.resolve({
1335
+ stepId,
1336
+ stepName: this.stepName,
1337
+ stepType: this.stepType,
1338
+ sleepFor: this.sleep,
1339
+ concurrent
1340
+ });
1341
+ }
1342
+ async submitStep({ context, body, headers, isParallel }) {
1343
+ return await context.qstashClient.batch([
1344
+ {
1345
+ body,
1346
+ headers,
1347
+ method: "POST",
1348
+ url: context.url,
1349
+ delay: isParallel ? void 0 : this.sleep
1350
+ }
1351
+ ]);
1352
+ }
1353
+ };
1354
+ var LazySleepUntilStep = class extends BaseLazyStep {
1355
+ sleepUntil;
1356
+ stepType = "SleepUntil";
1357
+ allowUndefinedOut = true;
1358
+ constructor(stepName, sleepUntil) {
1359
+ super(stepName);
1360
+ this.sleepUntil = sleepUntil;
1361
+ }
1362
+ getPlanStep(concurrent, targetStep) {
1363
+ return {
1364
+ stepId: 0,
1365
+ stepName: this.stepName,
1366
+ stepType: this.stepType,
1367
+ sleepUntil: this.sleepUntil,
1368
+ concurrent,
1369
+ targetStep
1370
+ };
1371
+ }
1372
+ async getResultStep(concurrent, stepId) {
1373
+ return await Promise.resolve({
1374
+ stepId,
1375
+ stepName: this.stepName,
1376
+ stepType: this.stepType,
1377
+ sleepUntil: this.sleepUntil,
1378
+ concurrent
1379
+ });
1380
+ }
1381
+ safeParseOut() {
1382
+ return void 0;
1383
+ }
1384
+ async submitStep({ context, body, headers, isParallel }) {
1385
+ return await context.qstashClient.batch([
1386
+ {
1387
+ body,
1388
+ headers,
1389
+ method: "POST",
1390
+ url: context.url,
1391
+ notBefore: isParallel ? void 0 : this.sleepUntil
1392
+ }
1393
+ ]);
1394
+ }
1395
+ };
1396
+ var LazyCallStep = class _LazyCallStep extends BaseLazyStep {
1397
+ url;
1398
+ method;
1399
+ body;
1400
+ headers;
1401
+ retries;
1402
+ timeout;
1403
+ flowControl;
1404
+ stepType = "Call";
1405
+ allowUndefinedOut = false;
1406
+ constructor(stepName, url, method, body, headers, retries, timeout, flowControl) {
1407
+ super(stepName);
1408
+ this.url = url;
1409
+ this.method = method;
1410
+ this.body = body;
1411
+ this.headers = headers;
1412
+ this.retries = retries;
1413
+ this.timeout = timeout;
1414
+ this.flowControl = flowControl;
1415
+ }
1416
+ getPlanStep(concurrent, targetStep) {
1417
+ return {
1418
+ stepId: 0,
1419
+ stepName: this.stepName,
1420
+ stepType: this.stepType,
1421
+ concurrent,
1422
+ targetStep
1423
+ };
1424
+ }
1425
+ async getResultStep(concurrent, stepId) {
1426
+ return await Promise.resolve({
1427
+ stepId,
1428
+ stepName: this.stepName,
1429
+ stepType: this.stepType,
1430
+ concurrent,
1431
+ callUrl: this.url,
1432
+ callMethod: this.method,
1433
+ callBody: this.body,
1434
+ callHeaders: this.headers
1435
+ });
1436
+ }
1437
+ safeParseOut(out) {
1438
+ const { header, status, body } = JSON.parse(out);
1439
+ const responseHeaders = new Headers(header);
1440
+ if (_LazyCallStep.isText(responseHeaders.get("content-type"))) {
1441
+ const bytes = new Uint8Array(out.length);
1442
+ for (let i = 0; i < out.length; i++) {
1443
+ bytes[i] = out.charCodeAt(i);
1444
+ }
1445
+ const processedResult = new TextDecoder().decode(bytes);
1446
+ const newBody = JSON.parse(processedResult).body;
1447
+ return {
1448
+ status,
1449
+ header,
1450
+ body: BaseLazyStep.tryParsing(newBody)
1451
+ };
1452
+ } else {
1453
+ return { header, status, body };
1454
+ }
1455
+ }
1456
+ static applicationHeaders = /* @__PURE__ */ new Set([
1457
+ "application/json",
1458
+ "application/xml",
1459
+ "application/javascript",
1460
+ "application/x-www-form-urlencoded",
1461
+ "application/xhtml+xml",
1462
+ "application/ld+json",
1463
+ "application/rss+xml",
1464
+ "application/atom+xml"
1465
+ ]);
1466
+ static isText = (contentTypeHeader) => {
1467
+ if (!contentTypeHeader) {
1468
+ return false;
1469
+ }
1470
+ if (_LazyCallStep.applicationHeaders.has(contentTypeHeader)) {
1471
+ return true;
1472
+ }
1473
+ if (contentTypeHeader.startsWith("text/")) {
1474
+ return true;
1565
1475
  }
1566
- if (retries !== void 0) {
1567
- baseHeaders["Upstash-Retries"] = retries.toString();
1568
- baseHeaders["Upstash-Failure-Callback-Retries"] = retries.toString();
1476
+ return false;
1477
+ };
1478
+ getBody({ step }) {
1479
+ if (!step.callUrl) {
1480
+ throw new WorkflowError("Incompatible step received in LazyCallStep.getBody");
1569
1481
  }
1482
+ return JSON.stringify(step.callBody);
1570
1483
  }
1571
- if (userHeaders) {
1572
- for (const header of userHeaders.keys()) {
1573
- if (step?.callHeaders) {
1574
- baseHeaders[`Upstash-Callback-Forward-${header}`] = userHeaders.get(header);
1575
- } else {
1576
- baseHeaders[`Upstash-Forward-${header}`] = userHeaders.get(header);
1577
- }
1578
- baseHeaders[`Upstash-Failure-Callback-Forward-${header}`] = userHeaders.get(header);
1484
+ getHeaders({ context, telemetry: telemetry2, invokeCount, step }) {
1485
+ const { headers, contentType } = super.getHeaders({ context, telemetry: telemetry2, invokeCount, step });
1486
+ headers["Upstash-Retries"] = this.retries.toString();
1487
+ headers[WORKFLOW_FEATURE_HEADER] = "WF_NoDelete,InitialBody";
1488
+ if (this.flowControl) {
1489
+ const { flowControlKey, flowControlValue } = prepareFlowControl(this.flowControl);
1490
+ headers["Upstash-Flow-Control-Key"] = flowControlKey;
1491
+ headers["Upstash-Flow-Control-Value"] = flowControlValue;
1492
+ }
1493
+ if (this.timeout) {
1494
+ headers["Upstash-Timeout"] = this.timeout.toString();
1579
1495
  }
1580
- }
1581
- if (step?.callHeaders) {
1582
1496
  const forwardedHeaders = Object.fromEntries(
1583
- Object.entries(step.callHeaders).map(([header, value]) => [
1584
- `Upstash-Forward-${header}`,
1585
- value
1586
- ])
1497
+ Object.entries(this.headers).map(([header, value]) => [`Upstash-Forward-${header}`, value])
1587
1498
  );
1588
1499
  return {
1589
1500
  headers: {
1590
- ...baseHeaders,
1501
+ ...headers,
1591
1502
  ...forwardedHeaders,
1592
- "Upstash-Callback": workflowUrl,
1593
- "Upstash-Callback-Workflow-RunId": workflowRunId,
1503
+ "Upstash-Callback": context.url,
1504
+ "Upstash-Callback-Workflow-RunId": context.workflowRunId,
1594
1505
  "Upstash-Callback-Workflow-CallType": "fromCallback",
1595
1506
  "Upstash-Callback-Workflow-Init": "false",
1596
- "Upstash-Callback-Workflow-Url": workflowUrl,
1507
+ "Upstash-Callback-Workflow-Url": context.url,
1597
1508
  "Upstash-Callback-Feature-Set": "LazyFetch,InitialBody",
1598
1509
  "Upstash-Callback-Forward-Upstash-Workflow-Callback": "true",
1599
1510
  "Upstash-Callback-Forward-Upstash-Workflow-StepId": step.stepId.toString(),
1600
- "Upstash-Callback-Forward-Upstash-Workflow-StepName": step.stepName,
1601
- "Upstash-Callback-Forward-Upstash-Workflow-StepType": step.stepType,
1511
+ "Upstash-Callback-Forward-Upstash-Workflow-StepName": this.stepName,
1512
+ "Upstash-Callback-Forward-Upstash-Workflow-StepType": this.stepType,
1602
1513
  "Upstash-Callback-Forward-Upstash-Workflow-Concurrent": step.concurrent.toString(),
1603
1514
  "Upstash-Callback-Forward-Upstash-Workflow-ContentType": contentType,
1604
- [`Upstash-Callback-Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`]: (invokeCount ?? 0).toString(),
1605
1515
  "Upstash-Workflow-CallType": "toCallback"
1516
+ },
1517
+ contentType
1518
+ };
1519
+ }
1520
+ async submitStep({ context, headers }) {
1521
+ return await context.qstashClient.batch([
1522
+ {
1523
+ headers,
1524
+ body: JSON.stringify(this.body),
1525
+ method: this.method,
1526
+ url: this.url
1606
1527
  }
1528
+ ]);
1529
+ }
1530
+ };
1531
+ var LazyWaitForEventStep = class extends BaseLazyStep {
1532
+ eventId;
1533
+ timeout;
1534
+ stepType = "Wait";
1535
+ allowUndefinedOut = false;
1536
+ constructor(stepName, eventId, timeout) {
1537
+ super(stepName);
1538
+ this.eventId = eventId;
1539
+ this.timeout = timeout;
1540
+ }
1541
+ getPlanStep(concurrent, targetStep) {
1542
+ return {
1543
+ stepId: 0,
1544
+ stepName: this.stepName,
1545
+ stepType: this.stepType,
1546
+ waitEventId: this.eventId,
1547
+ timeout: this.timeout,
1548
+ concurrent,
1549
+ targetStep
1607
1550
  };
1608
1551
  }
1609
- if (step?.waitEventId) {
1552
+ async getResultStep(concurrent, stepId) {
1553
+ return await Promise.resolve({
1554
+ stepId,
1555
+ stepName: this.stepName,
1556
+ stepType: this.stepType,
1557
+ waitEventId: this.eventId,
1558
+ timeout: this.timeout,
1559
+ concurrent
1560
+ });
1561
+ }
1562
+ safeParseOut(out) {
1563
+ const result = JSON.parse(out);
1610
1564
  return {
1611
- headers: {
1612
- ...baseHeaders,
1613
- "Upstash-Workflow-CallType": "step"
1614
- },
1615
- timeoutHeaders: {
1616
- // to include user headers:
1617
- ...Object.fromEntries(
1618
- Object.entries(baseHeaders).map(([header, value]) => [header, [value]])
1619
- ),
1620
- // to include telemetry headers:
1621
- ...telemetry2 ? Object.fromEntries(
1622
- Object.entries(getTelemetryHeaders(telemetry2)).map(([header, value]) => [
1623
- header,
1624
- [value]
1625
- ])
1626
- ) : {},
1627
- // note: using WORKFLOW_ID_HEADER doesn't work, because Runid -> RunId:
1628
- "Upstash-Workflow-Runid": [workflowRunId],
1629
- [WORKFLOW_INIT_HEADER]: ["false"],
1630
- [WORKFLOW_URL_HEADER]: [workflowUrl],
1631
- "Upstash-Workflow-CallType": ["step"]
1565
+ ...result,
1566
+ eventData: BaseLazyStep.tryParsing(result.eventData)
1567
+ };
1568
+ }
1569
+ getHeaders({ context, telemetry: telemetry2, invokeCount, step }) {
1570
+ const headers = super.getHeaders({ context, telemetry: telemetry2, invokeCount, step });
1571
+ headers.headers["Upstash-Workflow-CallType"] = "step";
1572
+ return headers;
1573
+ }
1574
+ getBody({ context, step, headers, telemetry: telemetry2 }) {
1575
+ if (!step.waitEventId) {
1576
+ throw new WorkflowError("Incompatible step received in LazyWaitForEventStep.getBody");
1577
+ }
1578
+ const timeoutHeaders = {
1579
+ // to include user headers:
1580
+ ...Object.fromEntries(Object.entries(headers).map(([header, value]) => [header, [value]])),
1581
+ // to include telemetry headers:
1582
+ ...telemetry2 ? Object.fromEntries(
1583
+ Object.entries(getTelemetryHeaders(telemetry2)).map(([header, value]) => [
1584
+ header,
1585
+ [value]
1586
+ ])
1587
+ ) : {},
1588
+ // note: using WORKFLOW_ID_HEADER doesn't work, because Runid -> RunId:
1589
+ "Upstash-Workflow-Runid": [context.workflowRunId],
1590
+ [WORKFLOW_INIT_HEADER]: ["false"],
1591
+ [WORKFLOW_URL_HEADER]: [context.url],
1592
+ "Upstash-Workflow-CallType": ["step"]
1593
+ };
1594
+ const waitBody = {
1595
+ url: context.url,
1596
+ timeout: step.timeout,
1597
+ timeoutBody: void 0,
1598
+ timeoutUrl: context.url,
1599
+ timeoutHeaders,
1600
+ step: {
1601
+ stepId: step.stepId,
1602
+ stepType: "Wait",
1603
+ stepName: step.stepName,
1604
+ concurrent: step.concurrent,
1605
+ targetStep: step.targetStep
1632
1606
  }
1633
1607
  };
1608
+ return JSON.stringify(waitBody);
1609
+ }
1610
+ async submitStep({ context, body, headers }) {
1611
+ const result = await context.qstashClient.http.request({
1612
+ path: ["v2", "wait", this.eventId],
1613
+ body,
1614
+ headers,
1615
+ method: "POST",
1616
+ parseResponseAsJson: false
1617
+ });
1618
+ return [result];
1634
1619
  }
1635
- return { headers: baseHeaders };
1636
1620
  };
1637
- var verifyRequest = async (body, signature, verifier) => {
1638
- if (!verifier) {
1639
- return;
1621
+ var LazyNotifyStep = class extends LazyFunctionStep {
1622
+ stepType = "Notify";
1623
+ constructor(stepName, eventId, eventData, requester) {
1624
+ super(stepName, async () => {
1625
+ const notifyResponse = await makeNotifyRequest(requester, eventId, eventData);
1626
+ return {
1627
+ eventId,
1628
+ eventData,
1629
+ notifyResponse
1630
+ };
1631
+ });
1640
1632
  }
1641
- try {
1642
- if (!signature) {
1643
- throw new Error("`Upstash-Signature` header is not passed.");
1633
+ safeParseOut(out) {
1634
+ const result = JSON.parse(out);
1635
+ return {
1636
+ ...result,
1637
+ eventData: BaseLazyStep.tryParsing(result.eventData)
1638
+ };
1639
+ }
1640
+ };
1641
+ var LazyInvokeStep = class extends BaseLazyStep {
1642
+ stepType = "Invoke";
1643
+ params;
1644
+ allowUndefinedOut = false;
1645
+ /**
1646
+ * workflow id of the invoked workflow
1647
+ */
1648
+ workflowId;
1649
+ constructor(stepName, {
1650
+ workflow,
1651
+ body,
1652
+ headers = {},
1653
+ workflowRunId,
1654
+ retries,
1655
+ flowControl
1656
+ }) {
1657
+ super(stepName);
1658
+ this.params = {
1659
+ workflow,
1660
+ body,
1661
+ headers,
1662
+ workflowRunId: getWorkflowRunId(workflowRunId),
1663
+ retries,
1664
+ flowControl
1665
+ };
1666
+ const { workflowId } = workflow;
1667
+ if (!workflowId) {
1668
+ throw new WorkflowError("You can only invoke workflow which has a workflowId");
1644
1669
  }
1645
- const isValid = await verifier.verify({
1670
+ this.workflowId = workflowId;
1671
+ }
1672
+ getPlanStep(concurrent, targetStep) {
1673
+ return {
1674
+ stepId: 0,
1675
+ stepName: this.stepName,
1676
+ stepType: this.stepType,
1677
+ concurrent,
1678
+ targetStep
1679
+ };
1680
+ }
1681
+ /**
1682
+ * won't be used as it's the server who will add the result step
1683
+ * in Invoke step.
1684
+ */
1685
+ getResultStep(concurrent, stepId) {
1686
+ return Promise.resolve({
1687
+ stepId,
1688
+ stepName: this.stepName,
1689
+ stepType: this.stepType,
1690
+ concurrent
1691
+ });
1692
+ }
1693
+ safeParseOut(out) {
1694
+ const result = JSON.parse(out);
1695
+ return {
1696
+ ...result,
1697
+ body: BaseLazyStep.tryParsing(result.body)
1698
+ };
1699
+ }
1700
+ getBody({ context, step, telemetry: telemetry2, invokeCount }) {
1701
+ const { headers: invokerHeaders } = getHeaders({
1702
+ initHeaderValue: "false",
1703
+ workflowConfig: {
1704
+ workflowRunId: context.workflowRunId,
1705
+ workflowUrl: context.url,
1706
+ failureUrl: context.failureUrl,
1707
+ retries: context.retries,
1708
+ telemetry: telemetry2,
1709
+ flowControl: context.flowControl,
1710
+ useJSONContent: false
1711
+ },
1712
+ userHeaders: context.headers,
1713
+ invokeCount
1714
+ });
1715
+ invokerHeaders["Upstash-Workflow-Runid"] = context.workflowRunId;
1716
+ const request = {
1717
+ body: JSON.stringify(this.params.body),
1718
+ headers: Object.fromEntries(
1719
+ Object.entries(invokerHeaders).map((pairs) => [pairs[0], [pairs[1]]])
1720
+ ),
1721
+ workflowRunId: context.workflowRunId,
1722
+ workflowUrl: context.url,
1723
+ step
1724
+ };
1725
+ return JSON.stringify(request);
1726
+ }
1727
+ getHeaders({ context, telemetry: telemetry2, invokeCount }) {
1728
+ const {
1729
+ workflow,
1730
+ headers = {},
1731
+ workflowRunId = getWorkflowRunId(),
1732
+ retries,
1733
+ flowControl
1734
+ } = this.params;
1735
+ const newUrl = context.url.replace(/[^/]+$/, this.workflowId);
1736
+ const {
1737
+ retries: workflowRetries,
1738
+ failureFunction,
1739
+ failureUrl,
1740
+ useJSONContent,
1741
+ flowControl: workflowFlowControl
1742
+ } = workflow.options;
1743
+ const { headers: triggerHeaders, contentType } = getHeaders({
1744
+ initHeaderValue: "true",
1745
+ workflowConfig: {
1746
+ workflowRunId,
1747
+ workflowUrl: newUrl,
1748
+ retries: retries ?? workflowRetries,
1749
+ telemetry: telemetry2,
1750
+ failureUrl: failureFunction ? newUrl : failureUrl,
1751
+ flowControl: flowControl ?? workflowFlowControl,
1752
+ useJSONContent: useJSONContent ?? false
1753
+ },
1754
+ invokeCount: invokeCount + 1,
1755
+ userHeaders: new Headers(headers)
1756
+ });
1757
+ triggerHeaders["Upstash-Workflow-Invoke"] = "true";
1758
+ return { headers: triggerHeaders, contentType };
1759
+ }
1760
+ async submitStep({ context, body, headers }) {
1761
+ const newUrl = context.url.replace(/[^/]+$/, this.workflowId);
1762
+ const result = await context.qstashClient.publish({
1763
+ headers,
1764
+ method: "POST",
1646
1765
  body,
1647
- signature
1766
+ url: newUrl
1648
1767
  });
1649
- if (!isValid) {
1650
- throw new Error("Signature in `Upstash-Signature` header is not valid");
1651
- }
1652
- } catch (error) {
1653
- throw new WorkflowError(
1654
- `Failed to verify that the Workflow request comes from QStash: ${error}
1768
+ return [result];
1769
+ }
1770
+ };
1655
1771
 
1656
- If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
1772
+ // src/agents/constants.ts
1773
+ var AGENT_NAME_HEADER = "upstash-agent-name";
1774
+ var MANAGER_AGENT_PROMPT = `You are an agent orchestrating other AI Agents.
1657
1775
 
1658
- If you want to disable QStash Verification, you should clear env variables QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY`
1776
+ These other agents have tools available to them.
1777
+
1778
+ Given a prompt, utilize these agents to address requests.
1779
+
1780
+ Don't always call all the agents provided to you at the same time. You can call one and use it's response to call another.
1781
+
1782
+ Avoid calling the same agent twice in one turn. Instead, prefer to call it once but provide everything
1783
+ you need from that agent.
1784
+ `;
1785
+
1786
+ // src/qstash/headers.ts
1787
+ var WorkflowHeaders = class {
1788
+ userHeaders;
1789
+ workflowConfig;
1790
+ invokeCount;
1791
+ initHeaderValue;
1792
+ stepInfo;
1793
+ headers;
1794
+ constructor({
1795
+ userHeaders,
1796
+ workflowConfig,
1797
+ invokeCount,
1798
+ initHeaderValue,
1799
+ stepInfo
1800
+ }) {
1801
+ this.userHeaders = userHeaders;
1802
+ this.workflowConfig = workflowConfig;
1803
+ this.invokeCount = invokeCount;
1804
+ this.initHeaderValue = initHeaderValue;
1805
+ this.stepInfo = stepInfo;
1806
+ this.headers = {
1807
+ rawHeaders: {},
1808
+ workflowHeaders: {},
1809
+ failureHeaders: {}
1810
+ };
1811
+ }
1812
+ getHeaders() {
1813
+ this.addBaseHeaders();
1814
+ this.addRetries();
1815
+ this.addFlowControl();
1816
+ this.addUserHeaders();
1817
+ this.addInvokeCount();
1818
+ this.addFailureUrl();
1819
+ const contentType = this.addContentType();
1820
+ return this.prefixHeaders(contentType);
1821
+ }
1822
+ addBaseHeaders() {
1823
+ this.headers.rawHeaders = {
1824
+ ...this.headers.rawHeaders,
1825
+ [WORKFLOW_INIT_HEADER]: this.initHeaderValue,
1826
+ [WORKFLOW_ID_HEADER]: this.workflowConfig.workflowRunId,
1827
+ [WORKFLOW_URL_HEADER]: this.workflowConfig.workflowUrl,
1828
+ [WORKFLOW_FEATURE_HEADER]: "LazyFetch,InitialBody",
1829
+ [WORKFLOW_PROTOCOL_VERSION_HEADER]: WORKFLOW_PROTOCOL_VERSION,
1830
+ ...this.workflowConfig.telemetry ? getTelemetryHeaders(this.workflowConfig.telemetry) : {},
1831
+ ...this.workflowConfig.telemetry && this.stepInfo?.lazyStep instanceof LazyCallStep && this.stepInfo.lazyStep.headers[AGENT_NAME_HEADER] ? { [TELEMETRY_HEADER_AGENT]: "true" } : {}
1832
+ };
1833
+ if (this.stepInfo?.lazyStep.stepType !== "Call") {
1834
+ this.headers.rawHeaders[`Upstash-Forward-${WORKFLOW_PROTOCOL_VERSION_HEADER}`] = WORKFLOW_PROTOCOL_VERSION;
1835
+ }
1836
+ }
1837
+ addInvokeCount() {
1838
+ if (this.invokeCount === void 0 || this.invokeCount === 0) {
1839
+ return;
1840
+ }
1841
+ const invokeCount = this.invokeCount.toString();
1842
+ this.headers.workflowHeaders[`Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount;
1843
+ if (this.workflowConfig.failureUrl) {
1844
+ this.headers.failureHeaders[`Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount;
1845
+ }
1846
+ if (this.stepInfo?.lazyStep instanceof LazyCallStep) {
1847
+ this.headers.rawHeaders[`Upstash-Forward-${WORKFLOW_INVOKE_COUNT_HEADER}`] = invokeCount;
1848
+ }
1849
+ }
1850
+ addRetries() {
1851
+ if (this.workflowConfig.retries === void 0 || this.workflowConfig.retries === DEFAULT_RETRIES) {
1852
+ return;
1853
+ }
1854
+ const retries = this.workflowConfig.retries.toString();
1855
+ this.headers.workflowHeaders["Retries"] = retries;
1856
+ if (this.workflowConfig.failureUrl) {
1857
+ this.headers.failureHeaders["Retries"] = retries;
1858
+ }
1859
+ }
1860
+ addFlowControl() {
1861
+ if (!this.workflowConfig.flowControl) {
1862
+ return;
1863
+ }
1864
+ const { flowControlKey, flowControlValue } = prepareFlowControl(
1865
+ this.workflowConfig.flowControl
1866
+ );
1867
+ this.headers.workflowHeaders["Flow-Control-Key"] = flowControlKey;
1868
+ this.headers.workflowHeaders["Flow-Control-Value"] = flowControlValue;
1869
+ if (this.workflowConfig.failureUrl) {
1870
+ this.headers.failureHeaders["Flow-Control-Key"] = flowControlKey;
1871
+ this.headers.failureHeaders["Flow-Control-Value"] = flowControlValue;
1872
+ }
1873
+ }
1874
+ addUserHeaders() {
1875
+ for (const [key, value] of this.userHeaders.entries()) {
1876
+ const forwardKey = `Forward-${key}`;
1877
+ this.headers.workflowHeaders[forwardKey] = value;
1878
+ if (this.workflowConfig.failureUrl) {
1879
+ this.headers.failureHeaders[forwardKey] = value;
1880
+ }
1881
+ }
1882
+ }
1883
+ addFailureUrl() {
1884
+ if (!this.workflowConfig.failureUrl) {
1885
+ return;
1886
+ }
1887
+ this.headers.workflowHeaders["Failure-Callback"] = this.workflowConfig.failureUrl;
1888
+ this.headers.failureHeaders[`Forward-${WORKFLOW_FAILURE_HEADER}`] = "true";
1889
+ this.headers.failureHeaders[`Forward-Upstash-Workflow-Failure-Callback`] = "true";
1890
+ this.headers.failureHeaders["Workflow-Runid"] = this.workflowConfig.workflowRunId;
1891
+ this.headers.failureHeaders["Workflow-Init"] = "false";
1892
+ this.headers.failureHeaders["Workflow-Url"] = this.workflowConfig.workflowUrl;
1893
+ this.headers.failureHeaders["Workflow-Calltype"] = "failureCall";
1894
+ this.headers.failureHeaders["Feature-Set"] = "LazyFetch,InitialBody";
1895
+ if (this.workflowConfig.retries !== void 0 && this.workflowConfig.retries !== DEFAULT_RETRIES) {
1896
+ this.headers.failureHeaders["Retries"] = this.workflowConfig.retries.toString();
1897
+ }
1898
+ }
1899
+ addContentType() {
1900
+ if (this.workflowConfig.useJSONContent) {
1901
+ this.headers.rawHeaders["content-type"] = "application/json";
1902
+ return "application/json";
1903
+ }
1904
+ const callHeaders = new Headers(
1905
+ this.stepInfo?.lazyStep instanceof LazyCallStep ? this.stepInfo.lazyStep.headers : {}
1659
1906
  );
1907
+ const contentType = (callHeaders.get("content-type") ? callHeaders.get("content-type") : this.userHeaders?.get("Content-Type") ? this.userHeaders.get("Content-Type") : void 0) ?? DEFAULT_CONTENT_TYPE;
1908
+ this.headers.rawHeaders["content-type"] = contentType;
1909
+ return contentType;
1910
+ }
1911
+ prefixHeaders(contentType) {
1912
+ const { rawHeaders, workflowHeaders, failureHeaders } = this.headers;
1913
+ const isCall = this.stepInfo?.lazyStep.stepType === "Call";
1914
+ return {
1915
+ headers: {
1916
+ ...rawHeaders,
1917
+ ...addPrefixToHeaders(workflowHeaders, isCall ? "Upstash-Callback-" : "Upstash-"),
1918
+ ...addPrefixToHeaders(failureHeaders, "Upstash-Failure-Callback-"),
1919
+ ...isCall ? addPrefixToHeaders(failureHeaders, "Upstash-Callback-Failure-Callback-") : {}
1920
+ },
1921
+ contentType
1922
+ };
1660
1923
  }
1661
1924
  };
1925
+ function addPrefixToHeaders(headers, prefix) {
1926
+ const prefixedHeaders = {};
1927
+ for (const [key, value] of Object.entries(headers)) {
1928
+ prefixedHeaders[`${prefix}${key}`] = value;
1929
+ }
1930
+ return prefixedHeaders;
1931
+ }
1662
1932
  var prepareFlowControl = (flowControl) => {
1663
1933
  const parallelism = flowControl.parallelism?.toString();
1664
- const rate = flowControl.ratePerSecond?.toString();
1934
+ const rate = (flowControl.rate ?? flowControl.ratePerSecond)?.toString();
1935
+ const period = typeof flowControl.period === "number" ? `${flowControl.period}s` : flowControl.period;
1665
1936
  const controlValue = [
1666
1937
  parallelism ? `parallelism=${parallelism}` : void 0,
1667
- rate ? `rate=${rate}` : void 0
1938
+ rate ? `rate=${rate}` : void 0,
1939
+ period ? `period=${period}` : void 0
1668
1940
  ].filter(Boolean);
1669
1941
  if (controlValue.length === 0) {
1670
- throw new import_qstash3.QstashError("Provide at least one of parallelism or ratePerSecond for flowControl");
1942
+ throw new import_qstash4.QstashError("Provide at least one of parallelism or ratePerSecond for flowControl");
1671
1943
  }
1672
1944
  return {
1673
1945
  flowControlKey: flowControl.key,
1674
1946
  flowControlValue: controlValue.join(", ")
1675
1947
  };
1676
1948
  };
1677
-
1678
- // src/context/auto-executor.ts
1679
- var import_qstash4 = require("@upstash/qstash");
1680
-
1681
- // src/serve/serve-many.ts
1682
- var getWorkflowId = (url) => {
1683
- const components = url.split("/");
1684
- const lastComponent = components[components.length - 1];
1685
- return lastComponent.split("?")[0];
1949
+ var getHeaders = (params) => {
1950
+ const workflowHeaders = new WorkflowHeaders(params);
1951
+ return workflowHeaders.getHeaders();
1686
1952
  };
1687
- var serveManyBase = ({
1688
- workflows,
1689
- getUrl: getUrl2,
1690
- serveMethod,
1691
- options
1953
+
1954
+ // src/qstash/submit-steps.ts
1955
+ var submitParallelSteps = async ({
1956
+ context,
1957
+ steps,
1958
+ initialStepCount,
1959
+ invokeCount,
1960
+ telemetry: telemetry2,
1961
+ debug
1692
1962
  }) => {
1693
- const workflowIds = [];
1694
- const workflowMap = Object.fromEntries(
1695
- Object.entries(workflows).map((workflow) => {
1696
- const workflowId = workflow[0];
1697
- if (workflowIds.includes(workflowId)) {
1698
- throw new WorkflowError(
1699
- `Duplicate workflow name found: '${workflowId}'. Please set different workflow names in serveMany.`
1700
- );
1701
- }
1702
- if (workflowId.includes("/")) {
1703
- throw new WorkflowError(
1704
- `Invalid workflow name found: '${workflowId}'. Workflow name cannot contain '/'.`
1705
- );
1706
- }
1707
- workflowIds.push(workflowId);
1708
- workflow[1].workflowId = workflowId;
1709
- workflow[1].options = {
1710
- ...options,
1711
- ...workflow[1].options
1963
+ const planSteps = steps.map(
1964
+ (step, index) => step.getPlanStep(steps.length, initialStepCount + index)
1965
+ );
1966
+ await debug?.log("SUBMIT", "SUBMIT_STEP", {
1967
+ length: planSteps.length,
1968
+ steps: planSteps
1969
+ });
1970
+ const result = await context.qstashClient.batch(
1971
+ planSteps.map((planStep) => {
1972
+ const { headers } = getHeaders({
1973
+ initHeaderValue: "false",
1974
+ workflowConfig: {
1975
+ workflowRunId: context.workflowRunId,
1976
+ workflowUrl: context.url,
1977
+ failureUrl: context.failureUrl,
1978
+ retries: context.retries,
1979
+ flowControl: context.flowControl,
1980
+ telemetry: telemetry2
1981
+ },
1982
+ userHeaders: context.headers,
1983
+ invokeCount
1984
+ });
1985
+ return {
1986
+ headers,
1987
+ method: "POST",
1988
+ url: context.url,
1989
+ body: JSON.stringify(planStep),
1990
+ notBefore: planStep.sleepUntil,
1991
+ delay: planStep.sleepFor
1712
1992
  };
1713
- const params = [workflow[1].routeFunction, workflow[1].options];
1714
- const handler = serveMethod(...params);
1715
- return [workflowId, handler];
1716
1993
  })
1717
1994
  );
1718
- return {
1719
- handler: async (...params) => {
1720
- const url = getUrl2(...params);
1721
- const pickedWorkflowId = getWorkflowId(url);
1722
- if (!pickedWorkflowId) {
1723
- return new Response(
1724
- `Unexpected request in serveMany. workflowId not set. Please update the URL of your request.`,
1725
- {
1726
- status: 404
1727
- }
1728
- );
1729
- }
1730
- const workflow = workflowMap[pickedWorkflowId];
1731
- if (!workflow) {
1732
- return new Response(
1733
- `No workflows in serveMany found for '${pickedWorkflowId}'. Please update the URL of your request.`,
1734
- {
1735
- status: 404
1736
- }
1737
- );
1738
- }
1739
- return await workflow(...params);
1740
- }
1741
- };
1995
+ await debug?.log("INFO", "SUBMIT_STEP", {
1996
+ messageIds: result.map((message) => {
1997
+ return {
1998
+ message: message.messageId
1999
+ };
2000
+ })
2001
+ });
2002
+ throw new WorkflowAbort(planSteps[0].stepName, planSteps[0]);
1742
2003
  };
1743
- var invokeWorkflow = async ({
1744
- settings,
1745
- invokeStep,
2004
+ var submitSingleStep = async ({
1746
2005
  context,
2006
+ lazyStep,
2007
+ stepId,
1747
2008
  invokeCount,
1748
- telemetry: telemetry2
2009
+ concurrency,
2010
+ telemetry: telemetry2,
2011
+ debug
1749
2012
  }) => {
1750
- const {
1751
- body,
1752
- workflow,
1753
- headers = {},
1754
- workflowRunId = getWorkflowRunId(),
1755
- retries,
1756
- flowControl
1757
- } = settings;
1758
- const { workflowId } = workflow;
1759
- const {
1760
- retries: workflowRetries,
1761
- failureFunction,
1762
- failureUrl,
1763
- useJSONContent,
1764
- flowControl: workflowFlowControl
1765
- } = workflow.options;
1766
- if (!workflowId) {
1767
- throw new WorkflowError("You can only invoke workflow which has a workflowId");
1768
- }
1769
- const { headers: invokerHeaders } = getHeaders({
1770
- initHeaderValue: "false",
1771
- workflowRunId: context.workflowRunId,
1772
- workflowUrl: context.url,
1773
- userHeaders: context.headers,
1774
- failureUrl: context.failureUrl,
1775
- retries: context.retries,
1776
- telemetry: telemetry2,
2013
+ const resultStep = await lazyStep.getResultStep(concurrency, stepId);
2014
+ await debug?.log("INFO", "RUN_SINGLE", {
2015
+ fromRequest: false,
2016
+ step: resultStep,
2017
+ stepCount: stepId
2018
+ });
2019
+ const { headers } = lazyStep.getHeaders({
2020
+ context,
2021
+ step: resultStep,
1777
2022
  invokeCount,
1778
- flowControl: context.flowControl
2023
+ telemetry: telemetry2
1779
2024
  });
1780
- invokerHeaders["Upstash-Workflow-Runid"] = context.workflowRunId;
1781
- const newUrl = context.url.replace(/[^/]+$/, workflowId);
1782
- const { headers: triggerHeaders } = getHeaders({
1783
- initHeaderValue: "true",
1784
- workflowRunId,
1785
- workflowUrl: newUrl,
1786
- userHeaders: new Headers(headers),
1787
- retries: retries ?? workflowRetries,
1788
- telemetry: telemetry2,
1789
- failureUrl: failureFunction ? newUrl : failureUrl,
1790
- invokeCount: invokeCount + 1,
1791
- flowControl: flowControl ?? workflowFlowControl
2025
+ const body = lazyStep.getBody({
2026
+ context,
2027
+ step: resultStep,
2028
+ headers,
2029
+ invokeCount,
2030
+ telemetry: telemetry2
1792
2031
  });
1793
- triggerHeaders["Upstash-Workflow-Invoke"] = "true";
1794
- if (useJSONContent) {
1795
- triggerHeaders["content-type"] = "application/json";
1796
- }
1797
- const request = {
1798
- body: JSON.stringify(body),
1799
- headers: Object.fromEntries(
1800
- Object.entries(invokerHeaders).map((pairs) => [pairs[0], [pairs[1]]])
1801
- ),
1802
- workflowRunId: context.workflowRunId,
1803
- workflowUrl: context.url,
1804
- step: invokeStep
1805
- };
1806
- await context.qstashClient.publish({
1807
- headers: triggerHeaders,
1808
- method: "POST",
1809
- body: JSON.stringify(request),
1810
- url: newUrl
2032
+ await debug?.log("SUBMIT", "SUBMIT_STEP", {
2033
+ length: 1,
2034
+ steps: [resultStep]
2035
+ });
2036
+ const submitResult = await lazyStep.submitStep({
2037
+ context,
2038
+ body,
2039
+ headers,
2040
+ isParallel: concurrency !== NO_CONCURRENCY,
2041
+ invokeCount,
2042
+ step: resultStep,
2043
+ telemetry: telemetry2
2044
+ });
2045
+ await debug?.log("INFO", "SUBMIT_STEP", {
2046
+ messageIds: submitResult.map((message) => {
2047
+ return {
2048
+ message: message.messageId
2049
+ };
2050
+ })
1811
2051
  });
2052
+ return resultStep;
1812
2053
  };
1813
2054
 
1814
2055
  // src/context/auto-executor.ts
@@ -1915,14 +2156,16 @@ var AutoExecutor = class _AutoExecutor {
1915
2156
  });
1916
2157
  return lazyStep.parseOut(step.out);
1917
2158
  }
1918
- const resultStep = await lazyStep.getResultStep(NO_CONCURRENCY, this.stepCount);
1919
- await this.debug?.log("INFO", "RUN_SINGLE", {
1920
- fromRequest: false,
1921
- step: resultStep,
1922
- stepCount: this.stepCount
2159
+ const resultStep = await submitSingleStep({
2160
+ context: this.context,
2161
+ lazyStep,
2162
+ stepId: this.stepCount,
2163
+ invokeCount: this.invokeCount,
2164
+ concurrency: 1,
2165
+ telemetry: this.telemetry,
2166
+ debug: this.debug
1923
2167
  });
1924
- await this.submitStepsToQStash([resultStep], [lazyStep]);
1925
- return resultStep.out;
2168
+ throw new WorkflowAbort(lazyStep.stepName, resultStep);
1926
2169
  }
1927
2170
  /**
1928
2171
  * Runs steps in parallel.
@@ -1950,10 +2193,14 @@ var AutoExecutor = class _AutoExecutor {
1950
2193
  });
1951
2194
  switch (parallelCallState) {
1952
2195
  case "first": {
1953
- const planSteps = parallelSteps.map(
1954
- (parallelStep, index) => parallelStep.getPlanStep(parallelSteps.length, initialStepCount + index)
1955
- );
1956
- await this.submitStepsToQStash(planSteps, parallelSteps);
2196
+ await submitParallelSteps({
2197
+ context: this.context,
2198
+ steps: parallelSteps,
2199
+ initialStepCount,
2200
+ invokeCount: this.invokeCount,
2201
+ telemetry: this.telemetry,
2202
+ debug: this.debug
2203
+ });
1957
2204
  break;
1958
2205
  }
1959
2206
  case "partial": {
@@ -1967,13 +2214,18 @@ var AutoExecutor = class _AutoExecutor {
1967
2214
  validateStep(parallelSteps[stepIndex], planStep);
1968
2215
  try {
1969
2216
  const parallelStep = parallelSteps[stepIndex];
1970
- const resultStep = await parallelStep.getResultStep(
1971
- parallelSteps.length,
1972
- planStep.targetStep
1973
- );
1974
- await this.submitStepsToQStash([resultStep], [parallelStep]);
2217
+ const resultStep = await submitSingleStep({
2218
+ context: this.context,
2219
+ lazyStep: parallelStep,
2220
+ stepId: planStep.targetStep,
2221
+ invokeCount: this.invokeCount,
2222
+ concurrency: parallelSteps.length,
2223
+ telemetry: this.telemetry,
2224
+ debug: this.debug
2225
+ });
2226
+ throw new WorkflowAbort(parallelStep.stepName, resultStep);
1975
2227
  } catch (error) {
1976
- if (error instanceof WorkflowAbort || error instanceof import_qstash4.QstashError && error.status === 400) {
2228
+ if (error instanceof WorkflowAbort || error instanceof import_qstash5.QstashError && error.status === 400) {
1977
2229
  throw error;
1978
2230
  }
1979
2231
  throw new WorkflowError(
@@ -2029,128 +2281,6 @@ var AutoExecutor = class _AutoExecutor {
2029
2281
  return "discard";
2030
2282
  }
2031
2283
  }
2032
- /**
2033
- * sends the steps to QStash as batch
2034
- *
2035
- * @param steps steps to send
2036
- */
2037
- async submitStepsToQStash(steps, lazySteps) {
2038
- if (steps.length === 0) {
2039
- throw new WorkflowError(
2040
- `Unable to submit steps to QStash. Provided list is empty. Current step: ${this.stepCount}`
2041
- );
2042
- }
2043
- await this.debug?.log("SUBMIT", "SUBMIT_STEP", {
2044
- length: steps.length,
2045
- steps
2046
- });
2047
- if (steps[0].waitEventId && steps.length === 1) {
2048
- const waitStep = steps[0];
2049
- const { headers, timeoutHeaders } = getHeaders({
2050
- initHeaderValue: "false",
2051
- workflowRunId: this.context.workflowRunId,
2052
- workflowUrl: this.context.url,
2053
- userHeaders: this.context.headers,
2054
- step: waitStep,
2055
- failureUrl: this.context.failureUrl,
2056
- retries: this.context.retries,
2057
- telemetry: this.telemetry,
2058
- invokeCount: this.invokeCount,
2059
- flowControl: this.context.flowControl
2060
- });
2061
- const waitBody = {
2062
- url: this.context.url,
2063
- timeout: waitStep.timeout,
2064
- timeoutBody: void 0,
2065
- timeoutUrl: this.context.url,
2066
- timeoutHeaders,
2067
- step: {
2068
- stepId: waitStep.stepId,
2069
- stepType: "Wait",
2070
- stepName: waitStep.stepName,
2071
- concurrent: waitStep.concurrent,
2072
- targetStep: waitStep.targetStep
2073
- }
2074
- };
2075
- await this.context.qstashClient.http.request({
2076
- path: ["v2", "wait", waitStep.waitEventId],
2077
- body: JSON.stringify(waitBody),
2078
- headers,
2079
- method: "POST",
2080
- parseResponseAsJson: false
2081
- });
2082
- throw new WorkflowAbort(waitStep.stepName, waitStep);
2083
- }
2084
- if (steps.length === 1 && lazySteps[0] instanceof LazyInvokeStep) {
2085
- const invokeStep = steps[0];
2086
- const lazyInvokeStep = lazySteps[0];
2087
- await invokeWorkflow({
2088
- settings: lazyInvokeStep.params,
2089
- invokeStep,
2090
- context: this.context,
2091
- invokeCount: this.invokeCount,
2092
- telemetry: this.telemetry
2093
- });
2094
- throw new WorkflowAbort(invokeStep.stepName, invokeStep);
2095
- }
2096
- const result = await this.context.qstashClient.batch(
2097
- steps.map((singleStep, index) => {
2098
- const lazyStep = lazySteps[index];
2099
- const { headers } = getHeaders({
2100
- initHeaderValue: "false",
2101
- workflowRunId: this.context.workflowRunId,
2102
- workflowUrl: this.context.url,
2103
- userHeaders: this.context.headers,
2104
- step: singleStep,
2105
- failureUrl: this.context.failureUrl,
2106
- retries: this.context.retries,
2107
- callRetries: lazyStep instanceof LazyCallStep ? lazyStep.retries : void 0,
2108
- callTimeout: lazyStep instanceof LazyCallStep ? lazyStep.timeout : void 0,
2109
- telemetry: this.telemetry,
2110
- invokeCount: this.invokeCount,
2111
- flowControl: this.context.flowControl,
2112
- callFlowControl: lazyStep instanceof LazyCallStep ? lazyStep.flowControl : void 0
2113
- });
2114
- const willWait = singleStep.concurrent === NO_CONCURRENCY || singleStep.stepId === 0;
2115
- singleStep.out = JSON.stringify(singleStep.out);
2116
- return singleStep.callUrl && lazyStep instanceof LazyCallStep ? (
2117
- // if the step is a third party call, we call the third party
2118
- // url (singleStep.callUrl) and pass information about the workflow
2119
- // in the headers (handled in getHeaders). QStash makes the request
2120
- // to callUrl and returns the result to Workflow endpoint.
2121
- // handleThirdPartyCallResult method sends the result of the third
2122
- // party call to QStash.
2123
- {
2124
- headers,
2125
- method: singleStep.callMethod,
2126
- body: JSON.stringify(singleStep.callBody),
2127
- url: singleStep.callUrl
2128
- }
2129
- ) : (
2130
- // if the step is not a third party call, we use workflow
2131
- // endpoint (context.url) as URL when calling QStash. QStash
2132
- // calls us back with the updated steps list.
2133
- {
2134
- headers,
2135
- method: "POST",
2136
- body: JSON.stringify(singleStep),
2137
- url: this.context.url,
2138
- notBefore: willWait ? singleStep.sleepUntil : void 0,
2139
- delay: willWait ? singleStep.sleepFor : void 0
2140
- }
2141
- );
2142
- })
2143
- );
2144
- const _result = result;
2145
- await this.debug?.log("INFO", "SUBMIT_STEP", {
2146
- messageIds: _result.map((message) => {
2147
- return {
2148
- message: message.messageId
2149
- };
2150
- })
2151
- });
2152
- throw new WorkflowAbort(steps[0].stepName, steps[0]);
2153
- }
2154
2284
  /**
2155
2285
  * Get the promise by executing the lazt steps list. If there is a single
2156
2286
  * step, we call `runSingle`. Otherwise `runParallel` is called.
@@ -2224,7 +2354,7 @@ var sortSteps = (steps) => {
2224
2354
  };
2225
2355
 
2226
2356
  // src/context/api/anthropic.ts
2227
- var import_qstash5 = require("@upstash/qstash");
2357
+ var import_qstash6 = require("@upstash/qstash");
2228
2358
 
2229
2359
  // src/context/provider.ts
2230
2360
  var getProviderInfo = (api) => {
@@ -2288,7 +2418,7 @@ var AnthropicAPI = class extends BaseWorkflowApi {
2288
2418
  return await this.callApi(stepName, {
2289
2419
  api: {
2290
2420
  name: "llm",
2291
- provider: (0, import_qstash5.anthropic)({ token })
2421
+ provider: (0, import_qstash6.anthropic)({ token })
2292
2422
  },
2293
2423
  ...parameters
2294
2424
  });
@@ -2296,12 +2426,12 @@ var AnthropicAPI = class extends BaseWorkflowApi {
2296
2426
  };
2297
2427
 
2298
2428
  // src/context/api/openai.ts
2299
- var import_qstash6 = require("@upstash/qstash");
2429
+ var import_qstash7 = require("@upstash/qstash");
2300
2430
  var OpenAIAPI = class extends BaseWorkflowApi {
2301
2431
  async call(stepName, settings) {
2302
2432
  const { token, organization, operation, baseURL, ...parameters } = settings;
2303
2433
  const useOpenAI = baseURL === void 0;
2304
- const provider = useOpenAI ? (0, import_qstash6.openai)({ token, organization }) : (0, import_qstash6.custom)({ baseUrl: baseURL, token });
2434
+ const provider = useOpenAI ? (0, import_qstash7.openai)({ token, organization }) : (0, import_qstash7.custom)({ baseUrl: baseURL, token });
2305
2435
  return await this.callApi(stepName, {
2306
2436
  api: {
2307
2437
  name: "llm",
@@ -2313,14 +2443,14 @@ var OpenAIAPI = class extends BaseWorkflowApi {
2313
2443
  };
2314
2444
 
2315
2445
  // src/context/api/resend.ts
2316
- var import_qstash7 = require("@upstash/qstash");
2446
+ var import_qstash8 = require("@upstash/qstash");
2317
2447
  var ResendAPI = class extends BaseWorkflowApi {
2318
2448
  async call(stepName, settings) {
2319
2449
  const { token, batch = false, ...parameters } = settings;
2320
2450
  return await this.callApi(stepName, {
2321
2451
  api: {
2322
2452
  name: "email",
2323
- provider: (0, import_qstash7.resend)({ token, batch })
2453
+ provider: (0, import_qstash8.resend)({ token, batch })
2324
2454
  },
2325
2455
  ...parameters
2326
2456
  });
@@ -2346,65 +2476,58 @@ var WorkflowApi = class extends BaseWorkflowApi {
2346
2476
  }
2347
2477
  };
2348
2478
 
2349
- // src/agents/adapters.ts
2479
+ // src/agents/index.ts
2350
2480
  var import_openai2 = require("@ai-sdk/openai");
2351
- var import_ai = require("ai");
2352
-
2353
- // src/agents/constants.ts
2354
- var AGENT_NAME_HEADER = "upstash-agent-name";
2355
- var MANAGER_AGENT_PROMPT = `You are an agent orchestrating other AI Agents.
2356
-
2357
- These other agents have tools available to them.
2358
-
2359
- Given a prompt, utilize these agents to address requests.
2360
-
2361
- Don't always call all the agents provided to you at the same time. You can call one and use it's response to call another.
2362
-
2363
- Avoid calling the same agent twice in one turn. Instead, prefer to call it once but provide everything
2364
- you need from that agent.
2365
- `;
2366
2481
 
2367
2482
  // src/agents/adapters.ts
2368
- var createWorkflowOpenAI = (context, config) => {
2369
- const { baseURL, apiKey } = config ?? {};
2370
- return (0, import_openai2.createOpenAI)({
2371
- baseURL,
2372
- apiKey,
2373
- compatibility: "strict",
2374
- fetch: async (input, init) => {
2375
- try {
2376
- const headers = init?.headers ? Object.fromEntries(new Headers(init.headers).entries()) : {};
2377
- const body = init?.body ? JSON.parse(init.body) : void 0;
2378
- const agentName = headers[AGENT_NAME_HEADER];
2379
- const stepName = agentName ? `Call Agent ${agentName}` : "Call Agent";
2380
- const responseInfo = await context.call(stepName, {
2381
- url: input.toString(),
2382
- method: init?.method,
2383
- headers,
2384
- body
2385
- });
2386
- const responseHeaders = new Headers(
2387
- Object.entries(responseInfo.header).reduce(
2388
- (acc, [key, values]) => {
2389
- acc[key] = values.join(", ");
2390
- return acc;
2391
- },
2392
- {}
2393
- )
2394
- );
2395
- return new Response(JSON.stringify(responseInfo.body), {
2396
- status: responseInfo.status,
2397
- headers: responseHeaders
2398
- });
2399
- } catch (error) {
2400
- if (error instanceof Error && error.name === "WorkflowAbort") {
2401
- throw error;
2402
- } else {
2403
- console.error("Error in fetch implementation:", error);
2404
- throw error;
2405
- }
2406
- }
2483
+ var import_ai = require("ai");
2484
+ var fetchWithContextCall = async (context, agentCallParams, ...params) => {
2485
+ const [input, init] = params;
2486
+ try {
2487
+ const headers = init?.headers ? Object.fromEntries(new Headers(init.headers).entries()) : {};
2488
+ const body = init?.body ? JSON.parse(init.body) : void 0;
2489
+ const agentName = headers[AGENT_NAME_HEADER];
2490
+ const stepName = agentName ? `Call Agent ${agentName}` : "Call Agent";
2491
+ const responseInfo = await context.call(stepName, {
2492
+ url: input.toString(),
2493
+ method: init?.method,
2494
+ headers,
2495
+ body,
2496
+ timeout: agentCallParams?.timeout,
2497
+ retries: agentCallParams?.retries,
2498
+ flowControl: agentCallParams?.flowControl
2499
+ });
2500
+ const responseHeaders = new Headers(
2501
+ Object.entries(responseInfo.header).reduce(
2502
+ (acc, [key, values]) => {
2503
+ acc[key] = values.join(", ");
2504
+ return acc;
2505
+ },
2506
+ {}
2507
+ )
2508
+ );
2509
+ return new Response(JSON.stringify(responseInfo.body), {
2510
+ status: responseInfo.status,
2511
+ headers: responseHeaders
2512
+ });
2513
+ } catch (error) {
2514
+ if (error instanceof Error && error.name === "WorkflowAbort") {
2515
+ throw error;
2516
+ } else {
2517
+ console.error("Error in fetch implementation:", error);
2518
+ throw error;
2407
2519
  }
2520
+ }
2521
+ };
2522
+ var createWorkflowModel = ({
2523
+ context,
2524
+ provider,
2525
+ providerParams,
2526
+ agentCallParams
2527
+ }) => {
2528
+ return provider({
2529
+ fetch: (...params) => fetchWithContextCall(context, agentCallParams, ...params),
2530
+ ...providerParams
2408
2531
  });
2409
2532
  };
2410
2533
  var wrapTools = ({
@@ -2643,10 +2766,85 @@ var WorkflowAgents = class {
2643
2766
  */
2644
2767
  openai(...params) {
2645
2768
  const [model, settings] = params;
2646
- const { baseURL, apiKey, ...otherSettings } = settings ?? {};
2647
- const openai2 = createWorkflowOpenAI(this.context, { baseURL, apiKey });
2648
- return openai2(model, otherSettings);
2769
+ const { baseURL, apiKey, callSettings, ...otherSettings } = settings ?? {};
2770
+ const openaiModel = this.AISDKModel({
2771
+ context: this.context,
2772
+ provider: import_openai2.createOpenAI,
2773
+ providerParams: { baseURL, apiKey, compatibility: "strict" },
2774
+ agentCallParams: callSettings
2775
+ });
2776
+ return openaiModel(model, otherSettings);
2777
+ }
2778
+ AISDKModel = createWorkflowModel;
2779
+ };
2780
+
2781
+ // src/serve/serve-many.ts
2782
+ var getWorkflowId = (url) => {
2783
+ const components = url.split("/");
2784
+ const lastComponent = components[components.length - 1];
2785
+ return lastComponent.split("?")[0];
2786
+ };
2787
+ var serveManyBase = ({
2788
+ workflows,
2789
+ getUrl: getUrl2,
2790
+ serveMethod,
2791
+ options
2792
+ }) => {
2793
+ const workflowIds = [];
2794
+ const workflowMap = Object.fromEntries(
2795
+ Object.entries(workflows).map((workflow) => {
2796
+ const workflowId = workflow[0];
2797
+ if (workflowIds.includes(workflowId)) {
2798
+ throw new WorkflowError(
2799
+ `Duplicate workflow name found: '${workflowId}'. Please set different workflow names in serveMany.`
2800
+ );
2801
+ }
2802
+ if (workflowId.includes("/")) {
2803
+ throw new WorkflowError(
2804
+ `Invalid workflow name found: '${workflowId}'. Workflow name cannot contain '/'.`
2805
+ );
2806
+ }
2807
+ workflowIds.push(workflowId);
2808
+ workflow[1].workflowId = workflowId;
2809
+ workflow[1].options = {
2810
+ ...options,
2811
+ ...workflow[1].options
2812
+ };
2813
+ const params = [workflow[1].routeFunction, workflow[1].options];
2814
+ const handler = serveMethod(...params);
2815
+ return [workflowId, handler];
2816
+ })
2817
+ );
2818
+ return {
2819
+ handler: async (...params) => {
2820
+ const url = getUrl2(...params);
2821
+ const pickedWorkflowId = getWorkflowId(url);
2822
+ if (!pickedWorkflowId) {
2823
+ return new Response(
2824
+ `Unexpected request in serveMany. workflowId not set. Please update the URL of your request.`,
2825
+ {
2826
+ status: 404
2827
+ }
2828
+ );
2829
+ }
2830
+ const workflow = workflowMap[pickedWorkflowId];
2831
+ if (!workflow) {
2832
+ return new Response(
2833
+ `No workflows in serveMany found for '${pickedWorkflowId}'. Please update the URL of your request.`,
2834
+ {
2835
+ status: 404
2836
+ }
2837
+ );
2838
+ }
2839
+ return await workflow(...params);
2840
+ }
2841
+ };
2842
+ };
2843
+ var getNewUrlFromWorkflowId = (url, workflowId) => {
2844
+ if (!workflowId) {
2845
+ throw new WorkflowError("You can only call workflow which has a workflowId");
2649
2846
  }
2847
+ return url.replace(/[^/]+$/, workflowId);
2650
2848
  };
2651
2849
 
2652
2850
  // src/context/context.ts
@@ -2870,60 +3068,42 @@ var WorkflowContext = class {
2870
3068
  }
2871
3069
  await this.addStep(new LazySleepUntilStep(stepName, time));
2872
3070
  }
2873
- /**
2874
- * Makes a third party call through QStash in order to make a
2875
- * network call without consuming any runtime.
2876
- *
2877
- * ```ts
2878
- * const { status, body } = await context.call<string>(
2879
- * "post call step",
2880
- * {
2881
- * url: "https://www.some-endpoint.com/api",
2882
- * method: "POST",
2883
- * body: "my-payload"
2884
- * }
2885
- * );
2886
- * ```
2887
- *
2888
- * tries to parse the result of the request as JSON. If it's
2889
- * not a JSON which can be parsed, simply returns the response
2890
- * body as it is.
2891
- *
2892
- * @param stepName
2893
- * @param url url to call
2894
- * @param method call method. "GET" by default.
2895
- * @param body call body
2896
- * @param headers call headers
2897
- * @param retries number of call retries. 0 by default
2898
- * @param timeout max duration to wait for the endpoint to respond. in seconds.
2899
- * @returns call result as {
2900
- * status: number;
2901
- * body: unknown;
2902
- * header: Record<string, string[]>
2903
- * }
2904
- */
2905
3071
  async call(stepName, settings) {
2906
- const {
2907
- url,
2908
- method = "GET",
2909
- body: requestBody,
2910
- headers = {},
2911
- retries = 0,
2912
- timeout,
2913
- flowControl
2914
- } = settings;
2915
- return await this.addStep(
2916
- new LazyCallStep(
3072
+ let callStep;
3073
+ if ("workflow" in settings) {
3074
+ const url = getNewUrlFromWorkflowId(this.url, settings.workflow.workflowId);
3075
+ callStep = new LazyCallStep(
3076
+ stepName,
3077
+ url,
3078
+ "POST",
3079
+ settings.body,
3080
+ settings.headers || {},
3081
+ settings.retries || 0,
3082
+ settings.timeout,
3083
+ settings.flowControl ?? settings.workflow.options.flowControl
3084
+ );
3085
+ } else {
3086
+ const {
3087
+ url,
3088
+ method = "GET",
3089
+ body,
3090
+ headers = {},
3091
+ retries = 0,
3092
+ timeout,
3093
+ flowControl
3094
+ } = settings;
3095
+ callStep = new LazyCallStep(
2917
3096
  stepName,
2918
3097
  url,
2919
3098
  method,
2920
- requestBody,
3099
+ body,
2921
3100
  headers,
2922
3101
  retries,
2923
3102
  timeout,
2924
3103
  flowControl
2925
- )
2926
- );
3104
+ );
3105
+ }
3106
+ return await this.addStep(callStep);
2927
3107
  }
2928
3108
  /**
2929
3109
  * Pauses workflow execution until a specific event occurs or a timeout is reached.
@@ -3071,7 +3251,7 @@ var WorkflowLogger = class _WorkflowLogger {
3071
3251
  };
3072
3252
 
3073
3253
  // src/serve/authorization.ts
3074
- var import_qstash8 = require("@upstash/qstash");
3254
+ var import_qstash9 = require("@upstash/qstash");
3075
3255
  var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowContext {
3076
3256
  static disabledMessage = "disabled-qstash-worklfow-run";
3077
3257
  disabled = true;
@@ -3103,7 +3283,7 @@ var DisabledWorkflowContext = class _DisabledWorkflowContext extends WorkflowCon
3103
3283
  */
3104
3284
  static async tryAuthentication(routeFunction, context) {
3105
3285
  const disabledContext = new _DisabledWorkflowContext({
3106
- qstashClient: new import_qstash8.Client({
3286
+ qstashClient: new import_qstash9.Client({
3107
3287
  baseUrl: "disabled-client",
3108
3288
  token: "disabled-client"
3109
3289
  }),
@@ -3317,15 +3497,15 @@ var handleFailure = async (request, requestPayload, qstashClient, initialPayload
3317
3497
  };
3318
3498
 
3319
3499
  // src/serve/options.ts
3320
- var import_qstash9 = require("@upstash/qstash");
3321
3500
  var import_qstash10 = require("@upstash/qstash");
3501
+ var import_qstash11 = require("@upstash/qstash");
3322
3502
  var processOptions = (options) => {
3323
3503
  const environment = options?.env ?? (typeof process === "undefined" ? {} : process.env);
3324
3504
  const receiverEnvironmentVariablesSet = Boolean(
3325
3505
  environment.QSTASH_CURRENT_SIGNING_KEY && environment.QSTASH_NEXT_SIGNING_KEY
3326
3506
  );
3327
3507
  return {
3328
- qstashClient: new import_qstash10.Client({
3508
+ qstashClient: new import_qstash11.Client({
3329
3509
  baseUrl: environment.QSTASH_URL,
3330
3510
  token: environment.QSTASH_TOKEN
3331
3511
  }),
@@ -3360,7 +3540,7 @@ var processOptions = (options) => {
3360
3540
  throw error;
3361
3541
  }
3362
3542
  },
3363
- receiver: receiverEnvironmentVariablesSet ? new import_qstash9.Receiver({
3543
+ receiver: receiverEnvironmentVariablesSet ? new import_qstash10.Receiver({
3364
3544
  currentSigningKey: environment.QSTASH_CURRENT_SIGNING_KEY,
3365
3545
  nextSigningKey: environment.QSTASH_NEXT_SIGNING_KEY
3366
3546
  }) : void 0,
@@ -3369,6 +3549,7 @@ var processOptions = (options) => {
3369
3549
  retries: DEFAULT_RETRIES,
3370
3550
  useJSONContent: false,
3371
3551
  disableTelemetry: false,
3552
+ onError: console.error,
3372
3553
  ...options
3373
3554
  };
3374
3555
  };
@@ -3418,7 +3599,8 @@ var serveBase = (routeFunction, telemetry2, options) => {
3418
3599
  retries,
3419
3600
  useJSONContent,
3420
3601
  disableTelemetry,
3421
- flowControl
3602
+ flowControl,
3603
+ onError
3422
3604
  } = processOptions(options);
3423
3605
  telemetry2 = disableTelemetry ? void 0 : telemetry2;
3424
3606
  const debug = WorkflowLogger.getLogger(verbose);
@@ -3547,8 +3729,19 @@ var serveBase = (routeFunction, telemetry2, options) => {
3547
3729
  try {
3548
3730
  return await handler(request);
3549
3731
  } catch (error) {
3550
- console.error(error);
3551
- return new Response(JSON.stringify(formatWorkflowError(error)), {
3732
+ const formattedError = formatWorkflowError(error);
3733
+ try {
3734
+ onError?.(error);
3735
+ } catch (onErrorError) {
3736
+ const formattedOnErrorError = formatWorkflowError(onErrorError);
3737
+ const errorMessage = `Error while running onError callback: '${formattedOnErrorError.message}'.
3738
+ Original error: '${formattedError.message}'`;
3739
+ console.error(errorMessage);
3740
+ return new Response(errorMessage, {
3741
+ status: 500
3742
+ });
3743
+ }
3744
+ return new Response(JSON.stringify(formattedError), {
3552
3745
  status: 500
3553
3746
  });
3554
3747
  }