@atxp/base 0.9.0 → 0.9.2

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.
Files changed (52) hide show
  1. package/dist/basePaymentMaker.d.ts.map +1 -1
  2. package/dist/basePaymentMaker.js +33 -6
  3. package/dist/basePaymentMaker.js.map +1 -1
  4. package/dist/index.cjs +4833 -8
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.js +4836 -11
  7. package/dist/index.js.map +1 -1
  8. package/dist/node_modules/@aa-sdk/core/dist/esm/client/schema.js +69 -0
  9. package/dist/node_modules/@aa-sdk/core/dist/esm/client/schema.js.map +1 -0
  10. package/dist/node_modules/@aa-sdk/core/dist/esm/errors/base.js +43 -0
  11. package/dist/node_modules/@aa-sdk/core/dist/esm/errors/base.js.map +1 -0
  12. package/dist/node_modules/@aa-sdk/core/dist/esm/errors/client.js +22 -0
  13. package/dist/node_modules/@aa-sdk/core/dist/esm/errors/client.js.map +1 -0
  14. package/dist/node_modules/@aa-sdk/core/dist/esm/transport/split.js +57 -0
  15. package/dist/node_modules/@aa-sdk/core/dist/esm/transport/split.js.map +1 -0
  16. package/dist/node_modules/@aa-sdk/core/dist/esm/utils/schema.js +33 -0
  17. package/dist/node_modules/@aa-sdk/core/dist/esm/utils/schema.js.map +1 -0
  18. package/dist/node_modules/@aa-sdk/core/dist/esm/utils/traceHeader.js +22 -0
  19. package/dist/node_modules/@aa-sdk/core/dist/esm/utils/traceHeader.js.map +1 -0
  20. package/dist/node_modules/@aa-sdk/core/dist/esm/version.js +6 -0
  21. package/dist/node_modules/@aa-sdk/core/dist/esm/version.js.map +1 -0
  22. package/dist/node_modules/@account-kit/infra/dist/esm/alchemyTrackerHeaders.js +36 -0
  23. package/dist/node_modules/@account-kit/infra/dist/esm/alchemyTrackerHeaders.js.map +1 -0
  24. package/dist/node_modules/@account-kit/infra/dist/esm/alchemyTransport.js +190 -0
  25. package/dist/node_modules/@account-kit/infra/dist/esm/alchemyTransport.js.map +1 -0
  26. package/dist/node_modules/@account-kit/infra/dist/esm/schema.js +10 -0
  27. package/dist/node_modules/@account-kit/infra/dist/esm/schema.js.map +1 -0
  28. package/dist/node_modules/@account-kit/infra/dist/esm/version.js +6 -0
  29. package/dist/node_modules/@account-kit/infra/dist/esm/version.js.map +1 -0
  30. package/dist/node_modules/zod/index.js +6 -0
  31. package/dist/node_modules/zod/index.js.map +1 -0
  32. package/dist/node_modules/zod/v3/ZodError.js +137 -0
  33. package/dist/node_modules/zod/v3/ZodError.js.map +1 -0
  34. package/dist/node_modules/zod/v3/errors.js +12 -0
  35. package/dist/node_modules/zod/v3/errors.js.map +1 -0
  36. package/dist/node_modules/zod/v3/external.js +7 -0
  37. package/dist/node_modules/zod/v3/external.js.map +1 -0
  38. package/dist/node_modules/zod/v3/helpers/errorUtil.js +9 -0
  39. package/dist/node_modules/zod/v3/helpers/errorUtil.js.map +1 -0
  40. package/dist/node_modules/zod/v3/helpers/parseUtil.js +113 -0
  41. package/dist/node_modules/zod/v3/helpers/parseUtil.js.map +1 -0
  42. package/dist/node_modules/zod/v3/helpers/util.js +136 -0
  43. package/dist/node_modules/zod/v3/helpers/util.js.map +1 -0
  44. package/dist/node_modules/zod/v3/locales/en.js +112 -0
  45. package/dist/node_modules/zod/v3/locales/en.js.map +1 -0
  46. package/dist/node_modules/zod/v3/types.js +3690 -0
  47. package/dist/node_modules/zod/v3/types.js.map +1 -0
  48. package/dist/smartWalletHelpers.d.ts +5 -1
  49. package/dist/smartWalletHelpers.d.ts.map +1 -1
  50. package/dist/smartWalletHelpers.js +67 -3
  51. package/dist/smartWalletHelpers.js.map +1 -1
  52. package/package.json +5 -4
package/dist/index.cjs CHANGED
@@ -470,6 +470,4741 @@ class MainWalletPaymentMaker {
470
470
  class IntermediaryCache extends common.JsonCache {
471
471
  }
472
472
 
473
+ // This file is autogenerated by inject-version.ts. Any changes will be
474
+ // overwritten on commit!
475
+ const VERSION$1 = "4.81.3";
476
+
477
+ /**
478
+ * A custom error class that extends from `ViemBaseError`. This class allows for error messages to include links to relevant documentation based on provided `docsPath` and `docsSlug` parameters.
479
+ * This is based on on viem's BaseError type (obviously from the import and extend)
480
+ * we want the errors here to point to our docs if we supply a docsPath though
481
+ */
482
+ class BaseError extends viem.BaseError {
483
+ constructor(shortMessage, args = {}) {
484
+ super(shortMessage, args);
485
+ Object.defineProperty(this, "name", {
486
+ enumerable: true,
487
+ configurable: true,
488
+ writable: true,
489
+ value: "AASDKError"
490
+ });
491
+ Object.defineProperty(this, "version", {
492
+ enumerable: true,
493
+ configurable: true,
494
+ writable: true,
495
+ value: VERSION$1
496
+ });
497
+ const docsPath = args.cause instanceof BaseError
498
+ ? args.cause.docsPath || args.docsPath
499
+ : args.docsPath;
500
+ this.message = [
501
+ shortMessage || "An error occurred.",
502
+ "",
503
+ ...(args.metaMessages ? [...args.metaMessages, ""] : []),
504
+ ...(docsPath
505
+ ? [
506
+ `Docs: https://www.alchemy.com/docs/wallets${docsPath}${args.docsSlug ? `#${args.docsSlug}` : ""}`,
507
+ ]
508
+ : []),
509
+ ...(this.details ? [`Details: ${this.details}`] : []),
510
+ `Version: ${this.version}`,
511
+ ].join("\n");
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Error class representing a "Chain Not Found" error, typically thrown when no chain is supplied to the client.
517
+ */
518
+ class ChainNotFoundError extends BaseError {
519
+ /**
520
+ * Initializes a new instance of the error message with a default message indicating that no chain was supplied to the client.
521
+ */
522
+ constructor() {
523
+ super("No chain supplied to the client");
524
+ Object.defineProperty(this, "name", {
525
+ enumerable: true,
526
+ configurable: true,
527
+ writable: true,
528
+ value: "ChainNotFoundError"
529
+ });
530
+ }
531
+ }
532
+
533
+ var util;
534
+ (function (util) {
535
+ util.assertEqual = (_) => { };
536
+ function assertIs(_arg) { }
537
+ util.assertIs = assertIs;
538
+ function assertNever(_x) {
539
+ throw new Error();
540
+ }
541
+ util.assertNever = assertNever;
542
+ util.arrayToEnum = (items) => {
543
+ const obj = {};
544
+ for (const item of items) {
545
+ obj[item] = item;
546
+ }
547
+ return obj;
548
+ };
549
+ util.getValidEnumValues = (obj) => {
550
+ const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
551
+ const filtered = {};
552
+ for (const k of validKeys) {
553
+ filtered[k] = obj[k];
554
+ }
555
+ return util.objectValues(filtered);
556
+ };
557
+ util.objectValues = (obj) => {
558
+ return util.objectKeys(obj).map(function (e) {
559
+ return obj[e];
560
+ });
561
+ };
562
+ util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
563
+ ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
564
+ : (object) => {
565
+ const keys = [];
566
+ for (const key in object) {
567
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
568
+ keys.push(key);
569
+ }
570
+ }
571
+ return keys;
572
+ };
573
+ util.find = (arr, checker) => {
574
+ for (const item of arr) {
575
+ if (checker(item))
576
+ return item;
577
+ }
578
+ return undefined;
579
+ };
580
+ util.isInteger = typeof Number.isInteger === "function"
581
+ ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
582
+ : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
583
+ function joinValues(array, separator = " | ") {
584
+ return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
585
+ }
586
+ util.joinValues = joinValues;
587
+ util.jsonStringifyReplacer = (_, value) => {
588
+ if (typeof value === "bigint") {
589
+ return value.toString();
590
+ }
591
+ return value;
592
+ };
593
+ })(util || (util = {}));
594
+ var objectUtil;
595
+ (function (objectUtil) {
596
+ objectUtil.mergeShapes = (first, second) => {
597
+ return {
598
+ ...first,
599
+ ...second, // second overwrites first
600
+ };
601
+ };
602
+ })(objectUtil || (objectUtil = {}));
603
+ const ZodParsedType = util.arrayToEnum([
604
+ "string",
605
+ "nan",
606
+ "number",
607
+ "integer",
608
+ "float",
609
+ "boolean",
610
+ "date",
611
+ "bigint",
612
+ "symbol",
613
+ "function",
614
+ "undefined",
615
+ "null",
616
+ "array",
617
+ "object",
618
+ "unknown",
619
+ "promise",
620
+ "void",
621
+ "never",
622
+ "map",
623
+ "set",
624
+ ]);
625
+ const getParsedType = (data) => {
626
+ const t = typeof data;
627
+ switch (t) {
628
+ case "undefined":
629
+ return ZodParsedType.undefined;
630
+ case "string":
631
+ return ZodParsedType.string;
632
+ case "number":
633
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
634
+ case "boolean":
635
+ return ZodParsedType.boolean;
636
+ case "function":
637
+ return ZodParsedType.function;
638
+ case "bigint":
639
+ return ZodParsedType.bigint;
640
+ case "symbol":
641
+ return ZodParsedType.symbol;
642
+ case "object":
643
+ if (Array.isArray(data)) {
644
+ return ZodParsedType.array;
645
+ }
646
+ if (data === null) {
647
+ return ZodParsedType.null;
648
+ }
649
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
650
+ return ZodParsedType.promise;
651
+ }
652
+ if (typeof Map !== "undefined" && data instanceof Map) {
653
+ return ZodParsedType.map;
654
+ }
655
+ if (typeof Set !== "undefined" && data instanceof Set) {
656
+ return ZodParsedType.set;
657
+ }
658
+ if (typeof Date !== "undefined" && data instanceof Date) {
659
+ return ZodParsedType.date;
660
+ }
661
+ return ZodParsedType.object;
662
+ default:
663
+ return ZodParsedType.unknown;
664
+ }
665
+ };
666
+
667
+ const ZodIssueCode = util.arrayToEnum([
668
+ "invalid_type",
669
+ "invalid_literal",
670
+ "custom",
671
+ "invalid_union",
672
+ "invalid_union_discriminator",
673
+ "invalid_enum_value",
674
+ "unrecognized_keys",
675
+ "invalid_arguments",
676
+ "invalid_return_type",
677
+ "invalid_date",
678
+ "invalid_string",
679
+ "too_small",
680
+ "too_big",
681
+ "invalid_intersection_types",
682
+ "not_multiple_of",
683
+ "not_finite",
684
+ ]);
685
+ const quotelessJson = (obj) => {
686
+ const json = JSON.stringify(obj, null, 2);
687
+ return json.replace(/"([^"]+)":/g, "$1:");
688
+ };
689
+ class ZodError extends Error {
690
+ get errors() {
691
+ return this.issues;
692
+ }
693
+ constructor(issues) {
694
+ super();
695
+ this.issues = [];
696
+ this.addIssue = (sub) => {
697
+ this.issues = [...this.issues, sub];
698
+ };
699
+ this.addIssues = (subs = []) => {
700
+ this.issues = [...this.issues, ...subs];
701
+ };
702
+ const actualProto = new.target.prototype;
703
+ if (Object.setPrototypeOf) {
704
+ // eslint-disable-next-line ban/ban
705
+ Object.setPrototypeOf(this, actualProto);
706
+ }
707
+ else {
708
+ this.__proto__ = actualProto;
709
+ }
710
+ this.name = "ZodError";
711
+ this.issues = issues;
712
+ }
713
+ format(_mapper) {
714
+ const mapper = _mapper ||
715
+ function (issue) {
716
+ return issue.message;
717
+ };
718
+ const fieldErrors = { _errors: [] };
719
+ const processError = (error) => {
720
+ for (const issue of error.issues) {
721
+ if (issue.code === "invalid_union") {
722
+ issue.unionErrors.map(processError);
723
+ }
724
+ else if (issue.code === "invalid_return_type") {
725
+ processError(issue.returnTypeError);
726
+ }
727
+ else if (issue.code === "invalid_arguments") {
728
+ processError(issue.argumentsError);
729
+ }
730
+ else if (issue.path.length === 0) {
731
+ fieldErrors._errors.push(mapper(issue));
732
+ }
733
+ else {
734
+ let curr = fieldErrors;
735
+ let i = 0;
736
+ while (i < issue.path.length) {
737
+ const el = issue.path[i];
738
+ const terminal = i === issue.path.length - 1;
739
+ if (!terminal) {
740
+ curr[el] = curr[el] || { _errors: [] };
741
+ // if (typeof el === "string") {
742
+ // curr[el] = curr[el] || { _errors: [] };
743
+ // } else if (typeof el === "number") {
744
+ // const errorArray: any = [];
745
+ // errorArray._errors = [];
746
+ // curr[el] = curr[el] || errorArray;
747
+ // }
748
+ }
749
+ else {
750
+ curr[el] = curr[el] || { _errors: [] };
751
+ curr[el]._errors.push(mapper(issue));
752
+ }
753
+ curr = curr[el];
754
+ i++;
755
+ }
756
+ }
757
+ }
758
+ };
759
+ processError(this);
760
+ return fieldErrors;
761
+ }
762
+ static assert(value) {
763
+ if (!(value instanceof ZodError)) {
764
+ throw new Error(`Not a ZodError: ${value}`);
765
+ }
766
+ }
767
+ toString() {
768
+ return this.message;
769
+ }
770
+ get message() {
771
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
772
+ }
773
+ get isEmpty() {
774
+ return this.issues.length === 0;
775
+ }
776
+ flatten(mapper = (issue) => issue.message) {
777
+ const fieldErrors = {};
778
+ const formErrors = [];
779
+ for (const sub of this.issues) {
780
+ if (sub.path.length > 0) {
781
+ const firstEl = sub.path[0];
782
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
783
+ fieldErrors[firstEl].push(mapper(sub));
784
+ }
785
+ else {
786
+ formErrors.push(mapper(sub));
787
+ }
788
+ }
789
+ return { formErrors, fieldErrors };
790
+ }
791
+ get formErrors() {
792
+ return this.flatten();
793
+ }
794
+ }
795
+ ZodError.create = (issues) => {
796
+ const error = new ZodError(issues);
797
+ return error;
798
+ };
799
+
800
+ const errorMap = (issue, _ctx) => {
801
+ let message;
802
+ switch (issue.code) {
803
+ case ZodIssueCode.invalid_type:
804
+ if (issue.received === ZodParsedType.undefined) {
805
+ message = "Required";
806
+ }
807
+ else {
808
+ message = `Expected ${issue.expected}, received ${issue.received}`;
809
+ }
810
+ break;
811
+ case ZodIssueCode.invalid_literal:
812
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
813
+ break;
814
+ case ZodIssueCode.unrecognized_keys:
815
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
816
+ break;
817
+ case ZodIssueCode.invalid_union:
818
+ message = `Invalid input`;
819
+ break;
820
+ case ZodIssueCode.invalid_union_discriminator:
821
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
822
+ break;
823
+ case ZodIssueCode.invalid_enum_value:
824
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
825
+ break;
826
+ case ZodIssueCode.invalid_arguments:
827
+ message = `Invalid function arguments`;
828
+ break;
829
+ case ZodIssueCode.invalid_return_type:
830
+ message = `Invalid function return type`;
831
+ break;
832
+ case ZodIssueCode.invalid_date:
833
+ message = `Invalid date`;
834
+ break;
835
+ case ZodIssueCode.invalid_string:
836
+ if (typeof issue.validation === "object") {
837
+ if ("includes" in issue.validation) {
838
+ message = `Invalid input: must include "${issue.validation.includes}"`;
839
+ if (typeof issue.validation.position === "number") {
840
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
841
+ }
842
+ }
843
+ else if ("startsWith" in issue.validation) {
844
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
845
+ }
846
+ else if ("endsWith" in issue.validation) {
847
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
848
+ }
849
+ else {
850
+ util.assertNever(issue.validation);
851
+ }
852
+ }
853
+ else if (issue.validation !== "regex") {
854
+ message = `Invalid ${issue.validation}`;
855
+ }
856
+ else {
857
+ message = "Invalid";
858
+ }
859
+ break;
860
+ case ZodIssueCode.too_small:
861
+ if (issue.type === "array")
862
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
863
+ else if (issue.type === "string")
864
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
865
+ else if (issue.type === "number")
866
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
867
+ else if (issue.type === "bigint")
868
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
869
+ else if (issue.type === "date")
870
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
871
+ else
872
+ message = "Invalid input";
873
+ break;
874
+ case ZodIssueCode.too_big:
875
+ if (issue.type === "array")
876
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
877
+ else if (issue.type === "string")
878
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
879
+ else if (issue.type === "number")
880
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
881
+ else if (issue.type === "bigint")
882
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
883
+ else if (issue.type === "date")
884
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
885
+ else
886
+ message = "Invalid input";
887
+ break;
888
+ case ZodIssueCode.custom:
889
+ message = `Invalid input`;
890
+ break;
891
+ case ZodIssueCode.invalid_intersection_types:
892
+ message = `Intersection results could not be merged`;
893
+ break;
894
+ case ZodIssueCode.not_multiple_of:
895
+ message = `Number must be a multiple of ${issue.multipleOf}`;
896
+ break;
897
+ case ZodIssueCode.not_finite:
898
+ message = "Number must be finite";
899
+ break;
900
+ default:
901
+ message = _ctx.defaultError;
902
+ util.assertNever(issue);
903
+ }
904
+ return { message };
905
+ };
906
+
907
+ let overrideErrorMap = errorMap;
908
+ function setErrorMap(map) {
909
+ overrideErrorMap = map;
910
+ }
911
+ function getErrorMap() {
912
+ return overrideErrorMap;
913
+ }
914
+
915
+ const makeIssue = (params) => {
916
+ const { data, path, errorMaps, issueData } = params;
917
+ const fullPath = [...path, ...(issueData.path || [])];
918
+ const fullIssue = {
919
+ ...issueData,
920
+ path: fullPath,
921
+ };
922
+ if (issueData.message !== undefined) {
923
+ return {
924
+ ...issueData,
925
+ path: fullPath,
926
+ message: issueData.message,
927
+ };
928
+ }
929
+ let errorMessage = "";
930
+ const maps = errorMaps
931
+ .filter((m) => !!m)
932
+ .slice()
933
+ .reverse();
934
+ for (const map of maps) {
935
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
936
+ }
937
+ return {
938
+ ...issueData,
939
+ path: fullPath,
940
+ message: errorMessage,
941
+ };
942
+ };
943
+ const EMPTY_PATH = [];
944
+ function addIssueToContext(ctx, issueData) {
945
+ const overrideMap = getErrorMap();
946
+ const issue = makeIssue({
947
+ issueData: issueData,
948
+ data: ctx.data,
949
+ path: ctx.path,
950
+ errorMaps: [
951
+ ctx.common.contextualErrorMap, // contextual error map is first priority
952
+ ctx.schemaErrorMap, // then schema-bound map if available
953
+ overrideMap, // then global override map
954
+ overrideMap === errorMap ? undefined : errorMap, // then global default map
955
+ ].filter((x) => !!x),
956
+ });
957
+ ctx.common.issues.push(issue);
958
+ }
959
+ class ParseStatus {
960
+ constructor() {
961
+ this.value = "valid";
962
+ }
963
+ dirty() {
964
+ if (this.value === "valid")
965
+ this.value = "dirty";
966
+ }
967
+ abort() {
968
+ if (this.value !== "aborted")
969
+ this.value = "aborted";
970
+ }
971
+ static mergeArray(status, results) {
972
+ const arrayValue = [];
973
+ for (const s of results) {
974
+ if (s.status === "aborted")
975
+ return INVALID;
976
+ if (s.status === "dirty")
977
+ status.dirty();
978
+ arrayValue.push(s.value);
979
+ }
980
+ return { status: status.value, value: arrayValue };
981
+ }
982
+ static async mergeObjectAsync(status, pairs) {
983
+ const syncPairs = [];
984
+ for (const pair of pairs) {
985
+ const key = await pair.key;
986
+ const value = await pair.value;
987
+ syncPairs.push({
988
+ key,
989
+ value,
990
+ });
991
+ }
992
+ return ParseStatus.mergeObjectSync(status, syncPairs);
993
+ }
994
+ static mergeObjectSync(status, pairs) {
995
+ const finalObject = {};
996
+ for (const pair of pairs) {
997
+ const { key, value } = pair;
998
+ if (key.status === "aborted")
999
+ return INVALID;
1000
+ if (value.status === "aborted")
1001
+ return INVALID;
1002
+ if (key.status === "dirty")
1003
+ status.dirty();
1004
+ if (value.status === "dirty")
1005
+ status.dirty();
1006
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
1007
+ finalObject[key.value] = value.value;
1008
+ }
1009
+ }
1010
+ return { status: status.value, value: finalObject };
1011
+ }
1012
+ }
1013
+ const INVALID = Object.freeze({
1014
+ status: "aborted",
1015
+ });
1016
+ const DIRTY = (value) => ({ status: "dirty", value });
1017
+ const OK = (value) => ({ status: "valid", value });
1018
+ const isAborted = (x) => x.status === "aborted";
1019
+ const isDirty = (x) => x.status === "dirty";
1020
+ const isValid = (x) => x.status === "valid";
1021
+ const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1022
+
1023
+ var errorUtil;
1024
+ (function (errorUtil) {
1025
+ errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1026
+ // biome-ignore lint:
1027
+ errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
1028
+ })(errorUtil || (errorUtil = {}));
1029
+
1030
+ class ParseInputLazyPath {
1031
+ constructor(parent, value, path, key) {
1032
+ this._cachedPath = [];
1033
+ this.parent = parent;
1034
+ this.data = value;
1035
+ this._path = path;
1036
+ this._key = key;
1037
+ }
1038
+ get path() {
1039
+ if (!this._cachedPath.length) {
1040
+ if (Array.isArray(this._key)) {
1041
+ this._cachedPath.push(...this._path, ...this._key);
1042
+ }
1043
+ else {
1044
+ this._cachedPath.push(...this._path, this._key);
1045
+ }
1046
+ }
1047
+ return this._cachedPath;
1048
+ }
1049
+ }
1050
+ const handleResult = (ctx, result) => {
1051
+ if (isValid(result)) {
1052
+ return { success: true, data: result.value };
1053
+ }
1054
+ else {
1055
+ if (!ctx.common.issues.length) {
1056
+ throw new Error("Validation failed but no issues detected.");
1057
+ }
1058
+ return {
1059
+ success: false,
1060
+ get error() {
1061
+ if (this._error)
1062
+ return this._error;
1063
+ const error = new ZodError(ctx.common.issues);
1064
+ this._error = error;
1065
+ return this._error;
1066
+ },
1067
+ };
1068
+ }
1069
+ };
1070
+ function processCreateParams(params) {
1071
+ if (!params)
1072
+ return {};
1073
+ const { errorMap, invalid_type_error, required_error, description } = params;
1074
+ if (errorMap && (invalid_type_error || required_error)) {
1075
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
1076
+ }
1077
+ if (errorMap)
1078
+ return { errorMap: errorMap, description };
1079
+ const customMap = (iss, ctx) => {
1080
+ const { message } = params;
1081
+ if (iss.code === "invalid_enum_value") {
1082
+ return { message: message ?? ctx.defaultError };
1083
+ }
1084
+ if (typeof ctx.data === "undefined") {
1085
+ return { message: message ?? required_error ?? ctx.defaultError };
1086
+ }
1087
+ if (iss.code !== "invalid_type")
1088
+ return { message: ctx.defaultError };
1089
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
1090
+ };
1091
+ return { errorMap: customMap, description };
1092
+ }
1093
+ class ZodType {
1094
+ get description() {
1095
+ return this._def.description;
1096
+ }
1097
+ _getType(input) {
1098
+ return getParsedType(input.data);
1099
+ }
1100
+ _getOrReturnCtx(input, ctx) {
1101
+ return (ctx || {
1102
+ common: input.parent.common,
1103
+ data: input.data,
1104
+ parsedType: getParsedType(input.data),
1105
+ schemaErrorMap: this._def.errorMap,
1106
+ path: input.path,
1107
+ parent: input.parent,
1108
+ });
1109
+ }
1110
+ _processInputParams(input) {
1111
+ return {
1112
+ status: new ParseStatus(),
1113
+ ctx: {
1114
+ common: input.parent.common,
1115
+ data: input.data,
1116
+ parsedType: getParsedType(input.data),
1117
+ schemaErrorMap: this._def.errorMap,
1118
+ path: input.path,
1119
+ parent: input.parent,
1120
+ },
1121
+ };
1122
+ }
1123
+ _parseSync(input) {
1124
+ const result = this._parse(input);
1125
+ if (isAsync(result)) {
1126
+ throw new Error("Synchronous parse encountered promise.");
1127
+ }
1128
+ return result;
1129
+ }
1130
+ _parseAsync(input) {
1131
+ const result = this._parse(input);
1132
+ return Promise.resolve(result);
1133
+ }
1134
+ parse(data, params) {
1135
+ const result = this.safeParse(data, params);
1136
+ if (result.success)
1137
+ return result.data;
1138
+ throw result.error;
1139
+ }
1140
+ safeParse(data, params) {
1141
+ const ctx = {
1142
+ common: {
1143
+ issues: [],
1144
+ async: params?.async ?? false,
1145
+ contextualErrorMap: params?.errorMap,
1146
+ },
1147
+ path: params?.path || [],
1148
+ schemaErrorMap: this._def.errorMap,
1149
+ parent: null,
1150
+ data,
1151
+ parsedType: getParsedType(data),
1152
+ };
1153
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1154
+ return handleResult(ctx, result);
1155
+ }
1156
+ "~validate"(data) {
1157
+ const ctx = {
1158
+ common: {
1159
+ issues: [],
1160
+ async: !!this["~standard"].async,
1161
+ },
1162
+ path: [],
1163
+ schemaErrorMap: this._def.errorMap,
1164
+ parent: null,
1165
+ data,
1166
+ parsedType: getParsedType(data),
1167
+ };
1168
+ if (!this["~standard"].async) {
1169
+ try {
1170
+ const result = this._parseSync({ data, path: [], parent: ctx });
1171
+ return isValid(result)
1172
+ ? {
1173
+ value: result.value,
1174
+ }
1175
+ : {
1176
+ issues: ctx.common.issues,
1177
+ };
1178
+ }
1179
+ catch (err) {
1180
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
1181
+ this["~standard"].async = true;
1182
+ }
1183
+ ctx.common = {
1184
+ issues: [],
1185
+ async: true,
1186
+ };
1187
+ }
1188
+ }
1189
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)
1190
+ ? {
1191
+ value: result.value,
1192
+ }
1193
+ : {
1194
+ issues: ctx.common.issues,
1195
+ });
1196
+ }
1197
+ async parseAsync(data, params) {
1198
+ const result = await this.safeParseAsync(data, params);
1199
+ if (result.success)
1200
+ return result.data;
1201
+ throw result.error;
1202
+ }
1203
+ async safeParseAsync(data, params) {
1204
+ const ctx = {
1205
+ common: {
1206
+ issues: [],
1207
+ contextualErrorMap: params?.errorMap,
1208
+ async: true,
1209
+ },
1210
+ path: params?.path || [],
1211
+ schemaErrorMap: this._def.errorMap,
1212
+ parent: null,
1213
+ data,
1214
+ parsedType: getParsedType(data),
1215
+ };
1216
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1217
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1218
+ return handleResult(ctx, result);
1219
+ }
1220
+ refine(check, message) {
1221
+ const getIssueProperties = (val) => {
1222
+ if (typeof message === "string" || typeof message === "undefined") {
1223
+ return { message };
1224
+ }
1225
+ else if (typeof message === "function") {
1226
+ return message(val);
1227
+ }
1228
+ else {
1229
+ return message;
1230
+ }
1231
+ };
1232
+ return this._refinement((val, ctx) => {
1233
+ const result = check(val);
1234
+ const setError = () => ctx.addIssue({
1235
+ code: ZodIssueCode.custom,
1236
+ ...getIssueProperties(val),
1237
+ });
1238
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
1239
+ return result.then((data) => {
1240
+ if (!data) {
1241
+ setError();
1242
+ return false;
1243
+ }
1244
+ else {
1245
+ return true;
1246
+ }
1247
+ });
1248
+ }
1249
+ if (!result) {
1250
+ setError();
1251
+ return false;
1252
+ }
1253
+ else {
1254
+ return true;
1255
+ }
1256
+ });
1257
+ }
1258
+ refinement(check, refinementData) {
1259
+ return this._refinement((val, ctx) => {
1260
+ if (!check(val)) {
1261
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1262
+ return false;
1263
+ }
1264
+ else {
1265
+ return true;
1266
+ }
1267
+ });
1268
+ }
1269
+ _refinement(refinement) {
1270
+ return new ZodEffects({
1271
+ schema: this,
1272
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1273
+ effect: { type: "refinement", refinement },
1274
+ });
1275
+ }
1276
+ superRefine(refinement) {
1277
+ return this._refinement(refinement);
1278
+ }
1279
+ constructor(def) {
1280
+ /** Alias of safeParseAsync */
1281
+ this.spa = this.safeParseAsync;
1282
+ this._def = def;
1283
+ this.parse = this.parse.bind(this);
1284
+ this.safeParse = this.safeParse.bind(this);
1285
+ this.parseAsync = this.parseAsync.bind(this);
1286
+ this.safeParseAsync = this.safeParseAsync.bind(this);
1287
+ this.spa = this.spa.bind(this);
1288
+ this.refine = this.refine.bind(this);
1289
+ this.refinement = this.refinement.bind(this);
1290
+ this.superRefine = this.superRefine.bind(this);
1291
+ this.optional = this.optional.bind(this);
1292
+ this.nullable = this.nullable.bind(this);
1293
+ this.nullish = this.nullish.bind(this);
1294
+ this.array = this.array.bind(this);
1295
+ this.promise = this.promise.bind(this);
1296
+ this.or = this.or.bind(this);
1297
+ this.and = this.and.bind(this);
1298
+ this.transform = this.transform.bind(this);
1299
+ this.brand = this.brand.bind(this);
1300
+ this.default = this.default.bind(this);
1301
+ this.catch = this.catch.bind(this);
1302
+ this.describe = this.describe.bind(this);
1303
+ this.pipe = this.pipe.bind(this);
1304
+ this.readonly = this.readonly.bind(this);
1305
+ this.isNullable = this.isNullable.bind(this);
1306
+ this.isOptional = this.isOptional.bind(this);
1307
+ this["~standard"] = {
1308
+ version: 1,
1309
+ vendor: "zod",
1310
+ validate: (data) => this["~validate"](data),
1311
+ };
1312
+ }
1313
+ optional() {
1314
+ return ZodOptional.create(this, this._def);
1315
+ }
1316
+ nullable() {
1317
+ return ZodNullable.create(this, this._def);
1318
+ }
1319
+ nullish() {
1320
+ return this.nullable().optional();
1321
+ }
1322
+ array() {
1323
+ return ZodArray.create(this);
1324
+ }
1325
+ promise() {
1326
+ return ZodPromise.create(this, this._def);
1327
+ }
1328
+ or(option) {
1329
+ return ZodUnion.create([this, option], this._def);
1330
+ }
1331
+ and(incoming) {
1332
+ return ZodIntersection.create(this, incoming, this._def);
1333
+ }
1334
+ transform(transform) {
1335
+ return new ZodEffects({
1336
+ ...processCreateParams(this._def),
1337
+ schema: this,
1338
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1339
+ effect: { type: "transform", transform },
1340
+ });
1341
+ }
1342
+ default(def) {
1343
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1344
+ return new ZodDefault({
1345
+ ...processCreateParams(this._def),
1346
+ innerType: this,
1347
+ defaultValue: defaultValueFunc,
1348
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
1349
+ });
1350
+ }
1351
+ brand() {
1352
+ return new ZodBranded({
1353
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1354
+ type: this,
1355
+ ...processCreateParams(this._def),
1356
+ });
1357
+ }
1358
+ catch(def) {
1359
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1360
+ return new ZodCatch({
1361
+ ...processCreateParams(this._def),
1362
+ innerType: this,
1363
+ catchValue: catchValueFunc,
1364
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
1365
+ });
1366
+ }
1367
+ describe(description) {
1368
+ const This = this.constructor;
1369
+ return new This({
1370
+ ...this._def,
1371
+ description,
1372
+ });
1373
+ }
1374
+ pipe(target) {
1375
+ return ZodPipeline.create(this, target);
1376
+ }
1377
+ readonly() {
1378
+ return ZodReadonly.create(this);
1379
+ }
1380
+ isOptional() {
1381
+ return this.safeParse(undefined).success;
1382
+ }
1383
+ isNullable() {
1384
+ return this.safeParse(null).success;
1385
+ }
1386
+ }
1387
+ const cuidRegex = /^c[^\s-]{8,}$/i;
1388
+ const cuid2Regex = /^[0-9a-z]+$/;
1389
+ const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1390
+ // const uuidRegex =
1391
+ // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
1392
+ const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
1393
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
1394
+ const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1395
+ const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1396
+ // from https://stackoverflow.com/a/46181/1550155
1397
+ // old version: too slow, didn't support unicode
1398
+ // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
1399
+ //old email regex
1400
+ // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
1401
+ // eslint-disable-next-line
1402
+ // const emailRegex =
1403
+ // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
1404
+ // const emailRegex =
1405
+ // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
1406
+ // const emailRegex =
1407
+ // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
1408
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1409
+ // const emailRegex =
1410
+ // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
1411
+ // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
1412
+ const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1413
+ let emojiRegex;
1414
+ // faster, simpler, safer
1415
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1416
+ const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
1417
+ // const ipv6Regex =
1418
+ // /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
1419
+ const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
1420
+ const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1421
+ // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
1422
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1423
+ // https://base64.guru/standards/base64url
1424
+ const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1425
+ // simple
1426
+ // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
1427
+ // no leap year validation
1428
+ // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
1429
+ // with leap year validation
1430
+ const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
1431
+ const dateRegex = new RegExp(`^${dateRegexSource}$`);
1432
+ function timeRegexSource(args) {
1433
+ let secondsRegexSource = `[0-5]\\d`;
1434
+ if (args.precision) {
1435
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1436
+ }
1437
+ else if (args.precision == null) {
1438
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1439
+ }
1440
+ const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero
1441
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1442
+ }
1443
+ function timeRegex(args) {
1444
+ return new RegExp(`^${timeRegexSource(args)}$`);
1445
+ }
1446
+ // Adapted from https://stackoverflow.com/a/3143231
1447
+ function datetimeRegex(args) {
1448
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1449
+ const opts = [];
1450
+ opts.push(args.local ? `Z?` : `Z`);
1451
+ if (args.offset)
1452
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1453
+ regex = `${regex}(${opts.join("|")})`;
1454
+ return new RegExp(`^${regex}$`);
1455
+ }
1456
+ function isValidIP(ip, version) {
1457
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1458
+ return true;
1459
+ }
1460
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1461
+ return true;
1462
+ }
1463
+ return false;
1464
+ }
1465
+ function isValidJWT(jwt, alg) {
1466
+ if (!jwtRegex.test(jwt))
1467
+ return false;
1468
+ try {
1469
+ const [header] = jwt.split(".");
1470
+ if (!header)
1471
+ return false;
1472
+ // Convert base64url to base64
1473
+ const base64 = header
1474
+ .replace(/-/g, "+")
1475
+ .replace(/_/g, "/")
1476
+ .padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
1477
+ const decoded = JSON.parse(atob(base64));
1478
+ if (typeof decoded !== "object" || decoded === null)
1479
+ return false;
1480
+ if ("typ" in decoded && decoded?.typ !== "JWT")
1481
+ return false;
1482
+ if (!decoded.alg)
1483
+ return false;
1484
+ if (alg && decoded.alg !== alg)
1485
+ return false;
1486
+ return true;
1487
+ }
1488
+ catch {
1489
+ return false;
1490
+ }
1491
+ }
1492
+ function isValidCidr(ip, version) {
1493
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1494
+ return true;
1495
+ }
1496
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1497
+ return true;
1498
+ }
1499
+ return false;
1500
+ }
1501
+ class ZodString extends ZodType {
1502
+ _parse(input) {
1503
+ if (this._def.coerce) {
1504
+ input.data = String(input.data);
1505
+ }
1506
+ const parsedType = this._getType(input);
1507
+ if (parsedType !== ZodParsedType.string) {
1508
+ const ctx = this._getOrReturnCtx(input);
1509
+ addIssueToContext(ctx, {
1510
+ code: ZodIssueCode.invalid_type,
1511
+ expected: ZodParsedType.string,
1512
+ received: ctx.parsedType,
1513
+ });
1514
+ return INVALID;
1515
+ }
1516
+ const status = new ParseStatus();
1517
+ let ctx = undefined;
1518
+ for (const check of this._def.checks) {
1519
+ if (check.kind === "min") {
1520
+ if (input.data.length < check.value) {
1521
+ ctx = this._getOrReturnCtx(input, ctx);
1522
+ addIssueToContext(ctx, {
1523
+ code: ZodIssueCode.too_small,
1524
+ minimum: check.value,
1525
+ type: "string",
1526
+ inclusive: true,
1527
+ exact: false,
1528
+ message: check.message,
1529
+ });
1530
+ status.dirty();
1531
+ }
1532
+ }
1533
+ else if (check.kind === "max") {
1534
+ if (input.data.length > check.value) {
1535
+ ctx = this._getOrReturnCtx(input, ctx);
1536
+ addIssueToContext(ctx, {
1537
+ code: ZodIssueCode.too_big,
1538
+ maximum: check.value,
1539
+ type: "string",
1540
+ inclusive: true,
1541
+ exact: false,
1542
+ message: check.message,
1543
+ });
1544
+ status.dirty();
1545
+ }
1546
+ }
1547
+ else if (check.kind === "length") {
1548
+ const tooBig = input.data.length > check.value;
1549
+ const tooSmall = input.data.length < check.value;
1550
+ if (tooBig || tooSmall) {
1551
+ ctx = this._getOrReturnCtx(input, ctx);
1552
+ if (tooBig) {
1553
+ addIssueToContext(ctx, {
1554
+ code: ZodIssueCode.too_big,
1555
+ maximum: check.value,
1556
+ type: "string",
1557
+ inclusive: true,
1558
+ exact: true,
1559
+ message: check.message,
1560
+ });
1561
+ }
1562
+ else if (tooSmall) {
1563
+ addIssueToContext(ctx, {
1564
+ code: ZodIssueCode.too_small,
1565
+ minimum: check.value,
1566
+ type: "string",
1567
+ inclusive: true,
1568
+ exact: true,
1569
+ message: check.message,
1570
+ });
1571
+ }
1572
+ status.dirty();
1573
+ }
1574
+ }
1575
+ else if (check.kind === "email") {
1576
+ if (!emailRegex.test(input.data)) {
1577
+ ctx = this._getOrReturnCtx(input, ctx);
1578
+ addIssueToContext(ctx, {
1579
+ validation: "email",
1580
+ code: ZodIssueCode.invalid_string,
1581
+ message: check.message,
1582
+ });
1583
+ status.dirty();
1584
+ }
1585
+ }
1586
+ else if (check.kind === "emoji") {
1587
+ if (!emojiRegex) {
1588
+ emojiRegex = new RegExp(_emojiRegex, "u");
1589
+ }
1590
+ if (!emojiRegex.test(input.data)) {
1591
+ ctx = this._getOrReturnCtx(input, ctx);
1592
+ addIssueToContext(ctx, {
1593
+ validation: "emoji",
1594
+ code: ZodIssueCode.invalid_string,
1595
+ message: check.message,
1596
+ });
1597
+ status.dirty();
1598
+ }
1599
+ }
1600
+ else if (check.kind === "uuid") {
1601
+ if (!uuidRegex.test(input.data)) {
1602
+ ctx = this._getOrReturnCtx(input, ctx);
1603
+ addIssueToContext(ctx, {
1604
+ validation: "uuid",
1605
+ code: ZodIssueCode.invalid_string,
1606
+ message: check.message,
1607
+ });
1608
+ status.dirty();
1609
+ }
1610
+ }
1611
+ else if (check.kind === "nanoid") {
1612
+ if (!nanoidRegex.test(input.data)) {
1613
+ ctx = this._getOrReturnCtx(input, ctx);
1614
+ addIssueToContext(ctx, {
1615
+ validation: "nanoid",
1616
+ code: ZodIssueCode.invalid_string,
1617
+ message: check.message,
1618
+ });
1619
+ status.dirty();
1620
+ }
1621
+ }
1622
+ else if (check.kind === "cuid") {
1623
+ if (!cuidRegex.test(input.data)) {
1624
+ ctx = this._getOrReturnCtx(input, ctx);
1625
+ addIssueToContext(ctx, {
1626
+ validation: "cuid",
1627
+ code: ZodIssueCode.invalid_string,
1628
+ message: check.message,
1629
+ });
1630
+ status.dirty();
1631
+ }
1632
+ }
1633
+ else if (check.kind === "cuid2") {
1634
+ if (!cuid2Regex.test(input.data)) {
1635
+ ctx = this._getOrReturnCtx(input, ctx);
1636
+ addIssueToContext(ctx, {
1637
+ validation: "cuid2",
1638
+ code: ZodIssueCode.invalid_string,
1639
+ message: check.message,
1640
+ });
1641
+ status.dirty();
1642
+ }
1643
+ }
1644
+ else if (check.kind === "ulid") {
1645
+ if (!ulidRegex.test(input.data)) {
1646
+ ctx = this._getOrReturnCtx(input, ctx);
1647
+ addIssueToContext(ctx, {
1648
+ validation: "ulid",
1649
+ code: ZodIssueCode.invalid_string,
1650
+ message: check.message,
1651
+ });
1652
+ status.dirty();
1653
+ }
1654
+ }
1655
+ else if (check.kind === "url") {
1656
+ try {
1657
+ new URL(input.data);
1658
+ }
1659
+ catch {
1660
+ ctx = this._getOrReturnCtx(input, ctx);
1661
+ addIssueToContext(ctx, {
1662
+ validation: "url",
1663
+ code: ZodIssueCode.invalid_string,
1664
+ message: check.message,
1665
+ });
1666
+ status.dirty();
1667
+ }
1668
+ }
1669
+ else if (check.kind === "regex") {
1670
+ check.regex.lastIndex = 0;
1671
+ const testResult = check.regex.test(input.data);
1672
+ if (!testResult) {
1673
+ ctx = this._getOrReturnCtx(input, ctx);
1674
+ addIssueToContext(ctx, {
1675
+ validation: "regex",
1676
+ code: ZodIssueCode.invalid_string,
1677
+ message: check.message,
1678
+ });
1679
+ status.dirty();
1680
+ }
1681
+ }
1682
+ else if (check.kind === "trim") {
1683
+ input.data = input.data.trim();
1684
+ }
1685
+ else if (check.kind === "includes") {
1686
+ if (!input.data.includes(check.value, check.position)) {
1687
+ ctx = this._getOrReturnCtx(input, ctx);
1688
+ addIssueToContext(ctx, {
1689
+ code: ZodIssueCode.invalid_string,
1690
+ validation: { includes: check.value, position: check.position },
1691
+ message: check.message,
1692
+ });
1693
+ status.dirty();
1694
+ }
1695
+ }
1696
+ else if (check.kind === "toLowerCase") {
1697
+ input.data = input.data.toLowerCase();
1698
+ }
1699
+ else if (check.kind === "toUpperCase") {
1700
+ input.data = input.data.toUpperCase();
1701
+ }
1702
+ else if (check.kind === "startsWith") {
1703
+ if (!input.data.startsWith(check.value)) {
1704
+ ctx = this._getOrReturnCtx(input, ctx);
1705
+ addIssueToContext(ctx, {
1706
+ code: ZodIssueCode.invalid_string,
1707
+ validation: { startsWith: check.value },
1708
+ message: check.message,
1709
+ });
1710
+ status.dirty();
1711
+ }
1712
+ }
1713
+ else if (check.kind === "endsWith") {
1714
+ if (!input.data.endsWith(check.value)) {
1715
+ ctx = this._getOrReturnCtx(input, ctx);
1716
+ addIssueToContext(ctx, {
1717
+ code: ZodIssueCode.invalid_string,
1718
+ validation: { endsWith: check.value },
1719
+ message: check.message,
1720
+ });
1721
+ status.dirty();
1722
+ }
1723
+ }
1724
+ else if (check.kind === "datetime") {
1725
+ const regex = datetimeRegex(check);
1726
+ if (!regex.test(input.data)) {
1727
+ ctx = this._getOrReturnCtx(input, ctx);
1728
+ addIssueToContext(ctx, {
1729
+ code: ZodIssueCode.invalid_string,
1730
+ validation: "datetime",
1731
+ message: check.message,
1732
+ });
1733
+ status.dirty();
1734
+ }
1735
+ }
1736
+ else if (check.kind === "date") {
1737
+ const regex = dateRegex;
1738
+ if (!regex.test(input.data)) {
1739
+ ctx = this._getOrReturnCtx(input, ctx);
1740
+ addIssueToContext(ctx, {
1741
+ code: ZodIssueCode.invalid_string,
1742
+ validation: "date",
1743
+ message: check.message,
1744
+ });
1745
+ status.dirty();
1746
+ }
1747
+ }
1748
+ else if (check.kind === "time") {
1749
+ const regex = timeRegex(check);
1750
+ if (!regex.test(input.data)) {
1751
+ ctx = this._getOrReturnCtx(input, ctx);
1752
+ addIssueToContext(ctx, {
1753
+ code: ZodIssueCode.invalid_string,
1754
+ validation: "time",
1755
+ message: check.message,
1756
+ });
1757
+ status.dirty();
1758
+ }
1759
+ }
1760
+ else if (check.kind === "duration") {
1761
+ if (!durationRegex.test(input.data)) {
1762
+ ctx = this._getOrReturnCtx(input, ctx);
1763
+ addIssueToContext(ctx, {
1764
+ validation: "duration",
1765
+ code: ZodIssueCode.invalid_string,
1766
+ message: check.message,
1767
+ });
1768
+ status.dirty();
1769
+ }
1770
+ }
1771
+ else if (check.kind === "ip") {
1772
+ if (!isValidIP(input.data, check.version)) {
1773
+ ctx = this._getOrReturnCtx(input, ctx);
1774
+ addIssueToContext(ctx, {
1775
+ validation: "ip",
1776
+ code: ZodIssueCode.invalid_string,
1777
+ message: check.message,
1778
+ });
1779
+ status.dirty();
1780
+ }
1781
+ }
1782
+ else if (check.kind === "jwt") {
1783
+ if (!isValidJWT(input.data, check.alg)) {
1784
+ ctx = this._getOrReturnCtx(input, ctx);
1785
+ addIssueToContext(ctx, {
1786
+ validation: "jwt",
1787
+ code: ZodIssueCode.invalid_string,
1788
+ message: check.message,
1789
+ });
1790
+ status.dirty();
1791
+ }
1792
+ }
1793
+ else if (check.kind === "cidr") {
1794
+ if (!isValidCidr(input.data, check.version)) {
1795
+ ctx = this._getOrReturnCtx(input, ctx);
1796
+ addIssueToContext(ctx, {
1797
+ validation: "cidr",
1798
+ code: ZodIssueCode.invalid_string,
1799
+ message: check.message,
1800
+ });
1801
+ status.dirty();
1802
+ }
1803
+ }
1804
+ else if (check.kind === "base64") {
1805
+ if (!base64Regex.test(input.data)) {
1806
+ ctx = this._getOrReturnCtx(input, ctx);
1807
+ addIssueToContext(ctx, {
1808
+ validation: "base64",
1809
+ code: ZodIssueCode.invalid_string,
1810
+ message: check.message,
1811
+ });
1812
+ status.dirty();
1813
+ }
1814
+ }
1815
+ else if (check.kind === "base64url") {
1816
+ if (!base64urlRegex.test(input.data)) {
1817
+ ctx = this._getOrReturnCtx(input, ctx);
1818
+ addIssueToContext(ctx, {
1819
+ validation: "base64url",
1820
+ code: ZodIssueCode.invalid_string,
1821
+ message: check.message,
1822
+ });
1823
+ status.dirty();
1824
+ }
1825
+ }
1826
+ else {
1827
+ util.assertNever(check);
1828
+ }
1829
+ }
1830
+ return { status: status.value, value: input.data };
1831
+ }
1832
+ _regex(regex, validation, message) {
1833
+ return this.refinement((data) => regex.test(data), {
1834
+ validation,
1835
+ code: ZodIssueCode.invalid_string,
1836
+ ...errorUtil.errToObj(message),
1837
+ });
1838
+ }
1839
+ _addCheck(check) {
1840
+ return new ZodString({
1841
+ ...this._def,
1842
+ checks: [...this._def.checks, check],
1843
+ });
1844
+ }
1845
+ email(message) {
1846
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1847
+ }
1848
+ url(message) {
1849
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1850
+ }
1851
+ emoji(message) {
1852
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1853
+ }
1854
+ uuid(message) {
1855
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1856
+ }
1857
+ nanoid(message) {
1858
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1859
+ }
1860
+ cuid(message) {
1861
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1862
+ }
1863
+ cuid2(message) {
1864
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1865
+ }
1866
+ ulid(message) {
1867
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1868
+ }
1869
+ base64(message) {
1870
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1871
+ }
1872
+ base64url(message) {
1873
+ // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
1874
+ return this._addCheck({
1875
+ kind: "base64url",
1876
+ ...errorUtil.errToObj(message),
1877
+ });
1878
+ }
1879
+ jwt(options) {
1880
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
1881
+ }
1882
+ ip(options) {
1883
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1884
+ }
1885
+ cidr(options) {
1886
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
1887
+ }
1888
+ datetime(options) {
1889
+ if (typeof options === "string") {
1890
+ return this._addCheck({
1891
+ kind: "datetime",
1892
+ precision: null,
1893
+ offset: false,
1894
+ local: false,
1895
+ message: options,
1896
+ });
1897
+ }
1898
+ return this._addCheck({
1899
+ kind: "datetime",
1900
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1901
+ offset: options?.offset ?? false,
1902
+ local: options?.local ?? false,
1903
+ ...errorUtil.errToObj(options?.message),
1904
+ });
1905
+ }
1906
+ date(message) {
1907
+ return this._addCheck({ kind: "date", message });
1908
+ }
1909
+ time(options) {
1910
+ if (typeof options === "string") {
1911
+ return this._addCheck({
1912
+ kind: "time",
1913
+ precision: null,
1914
+ message: options,
1915
+ });
1916
+ }
1917
+ return this._addCheck({
1918
+ kind: "time",
1919
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1920
+ ...errorUtil.errToObj(options?.message),
1921
+ });
1922
+ }
1923
+ duration(message) {
1924
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1925
+ }
1926
+ regex(regex, message) {
1927
+ return this._addCheck({
1928
+ kind: "regex",
1929
+ regex: regex,
1930
+ ...errorUtil.errToObj(message),
1931
+ });
1932
+ }
1933
+ includes(value, options) {
1934
+ return this._addCheck({
1935
+ kind: "includes",
1936
+ value: value,
1937
+ position: options?.position,
1938
+ ...errorUtil.errToObj(options?.message),
1939
+ });
1940
+ }
1941
+ startsWith(value, message) {
1942
+ return this._addCheck({
1943
+ kind: "startsWith",
1944
+ value: value,
1945
+ ...errorUtil.errToObj(message),
1946
+ });
1947
+ }
1948
+ endsWith(value, message) {
1949
+ return this._addCheck({
1950
+ kind: "endsWith",
1951
+ value: value,
1952
+ ...errorUtil.errToObj(message),
1953
+ });
1954
+ }
1955
+ min(minLength, message) {
1956
+ return this._addCheck({
1957
+ kind: "min",
1958
+ value: minLength,
1959
+ ...errorUtil.errToObj(message),
1960
+ });
1961
+ }
1962
+ max(maxLength, message) {
1963
+ return this._addCheck({
1964
+ kind: "max",
1965
+ value: maxLength,
1966
+ ...errorUtil.errToObj(message),
1967
+ });
1968
+ }
1969
+ length(len, message) {
1970
+ return this._addCheck({
1971
+ kind: "length",
1972
+ value: len,
1973
+ ...errorUtil.errToObj(message),
1974
+ });
1975
+ }
1976
+ /**
1977
+ * Equivalent to `.min(1)`
1978
+ */
1979
+ nonempty(message) {
1980
+ return this.min(1, errorUtil.errToObj(message));
1981
+ }
1982
+ trim() {
1983
+ return new ZodString({
1984
+ ...this._def,
1985
+ checks: [...this._def.checks, { kind: "trim" }],
1986
+ });
1987
+ }
1988
+ toLowerCase() {
1989
+ return new ZodString({
1990
+ ...this._def,
1991
+ checks: [...this._def.checks, { kind: "toLowerCase" }],
1992
+ });
1993
+ }
1994
+ toUpperCase() {
1995
+ return new ZodString({
1996
+ ...this._def,
1997
+ checks: [...this._def.checks, { kind: "toUpperCase" }],
1998
+ });
1999
+ }
2000
+ get isDatetime() {
2001
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
2002
+ }
2003
+ get isDate() {
2004
+ return !!this._def.checks.find((ch) => ch.kind === "date");
2005
+ }
2006
+ get isTime() {
2007
+ return !!this._def.checks.find((ch) => ch.kind === "time");
2008
+ }
2009
+ get isDuration() {
2010
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
2011
+ }
2012
+ get isEmail() {
2013
+ return !!this._def.checks.find((ch) => ch.kind === "email");
2014
+ }
2015
+ get isURL() {
2016
+ return !!this._def.checks.find((ch) => ch.kind === "url");
2017
+ }
2018
+ get isEmoji() {
2019
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
2020
+ }
2021
+ get isUUID() {
2022
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
2023
+ }
2024
+ get isNANOID() {
2025
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
2026
+ }
2027
+ get isCUID() {
2028
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
2029
+ }
2030
+ get isCUID2() {
2031
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
2032
+ }
2033
+ get isULID() {
2034
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
2035
+ }
2036
+ get isIP() {
2037
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
2038
+ }
2039
+ get isCIDR() {
2040
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
2041
+ }
2042
+ get isBase64() {
2043
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
2044
+ }
2045
+ get isBase64url() {
2046
+ // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
2047
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
2048
+ }
2049
+ get minLength() {
2050
+ let min = null;
2051
+ for (const ch of this._def.checks) {
2052
+ if (ch.kind === "min") {
2053
+ if (min === null || ch.value > min)
2054
+ min = ch.value;
2055
+ }
2056
+ }
2057
+ return min;
2058
+ }
2059
+ get maxLength() {
2060
+ let max = null;
2061
+ for (const ch of this._def.checks) {
2062
+ if (ch.kind === "max") {
2063
+ if (max === null || ch.value < max)
2064
+ max = ch.value;
2065
+ }
2066
+ }
2067
+ return max;
2068
+ }
2069
+ }
2070
+ ZodString.create = (params) => {
2071
+ return new ZodString({
2072
+ checks: [],
2073
+ typeName: ZodFirstPartyTypeKind.ZodString,
2074
+ coerce: params?.coerce ?? false,
2075
+ ...processCreateParams(params),
2076
+ });
2077
+ };
2078
+ // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
2079
+ function floatSafeRemainder(val, step) {
2080
+ const valDecCount = (val.toString().split(".")[1] || "").length;
2081
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
2082
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
2083
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
2084
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
2085
+ return (valInt % stepInt) / 10 ** decCount;
2086
+ }
2087
+ class ZodNumber extends ZodType {
2088
+ constructor() {
2089
+ super(...arguments);
2090
+ this.min = this.gte;
2091
+ this.max = this.lte;
2092
+ this.step = this.multipleOf;
2093
+ }
2094
+ _parse(input) {
2095
+ if (this._def.coerce) {
2096
+ input.data = Number(input.data);
2097
+ }
2098
+ const parsedType = this._getType(input);
2099
+ if (parsedType !== ZodParsedType.number) {
2100
+ const ctx = this._getOrReturnCtx(input);
2101
+ addIssueToContext(ctx, {
2102
+ code: ZodIssueCode.invalid_type,
2103
+ expected: ZodParsedType.number,
2104
+ received: ctx.parsedType,
2105
+ });
2106
+ return INVALID;
2107
+ }
2108
+ let ctx = undefined;
2109
+ const status = new ParseStatus();
2110
+ for (const check of this._def.checks) {
2111
+ if (check.kind === "int") {
2112
+ if (!util.isInteger(input.data)) {
2113
+ ctx = this._getOrReturnCtx(input, ctx);
2114
+ addIssueToContext(ctx, {
2115
+ code: ZodIssueCode.invalid_type,
2116
+ expected: "integer",
2117
+ received: "float",
2118
+ message: check.message,
2119
+ });
2120
+ status.dirty();
2121
+ }
2122
+ }
2123
+ else if (check.kind === "min") {
2124
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2125
+ if (tooSmall) {
2126
+ ctx = this._getOrReturnCtx(input, ctx);
2127
+ addIssueToContext(ctx, {
2128
+ code: ZodIssueCode.too_small,
2129
+ minimum: check.value,
2130
+ type: "number",
2131
+ inclusive: check.inclusive,
2132
+ exact: false,
2133
+ message: check.message,
2134
+ });
2135
+ status.dirty();
2136
+ }
2137
+ }
2138
+ else if (check.kind === "max") {
2139
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2140
+ if (tooBig) {
2141
+ ctx = this._getOrReturnCtx(input, ctx);
2142
+ addIssueToContext(ctx, {
2143
+ code: ZodIssueCode.too_big,
2144
+ maximum: check.value,
2145
+ type: "number",
2146
+ inclusive: check.inclusive,
2147
+ exact: false,
2148
+ message: check.message,
2149
+ });
2150
+ status.dirty();
2151
+ }
2152
+ }
2153
+ else if (check.kind === "multipleOf") {
2154
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
2155
+ ctx = this._getOrReturnCtx(input, ctx);
2156
+ addIssueToContext(ctx, {
2157
+ code: ZodIssueCode.not_multiple_of,
2158
+ multipleOf: check.value,
2159
+ message: check.message,
2160
+ });
2161
+ status.dirty();
2162
+ }
2163
+ }
2164
+ else if (check.kind === "finite") {
2165
+ if (!Number.isFinite(input.data)) {
2166
+ ctx = this._getOrReturnCtx(input, ctx);
2167
+ addIssueToContext(ctx, {
2168
+ code: ZodIssueCode.not_finite,
2169
+ message: check.message,
2170
+ });
2171
+ status.dirty();
2172
+ }
2173
+ }
2174
+ else {
2175
+ util.assertNever(check);
2176
+ }
2177
+ }
2178
+ return { status: status.value, value: input.data };
2179
+ }
2180
+ gte(value, message) {
2181
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2182
+ }
2183
+ gt(value, message) {
2184
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2185
+ }
2186
+ lte(value, message) {
2187
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2188
+ }
2189
+ lt(value, message) {
2190
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2191
+ }
2192
+ setLimit(kind, value, inclusive, message) {
2193
+ return new ZodNumber({
2194
+ ...this._def,
2195
+ checks: [
2196
+ ...this._def.checks,
2197
+ {
2198
+ kind,
2199
+ value,
2200
+ inclusive,
2201
+ message: errorUtil.toString(message),
2202
+ },
2203
+ ],
2204
+ });
2205
+ }
2206
+ _addCheck(check) {
2207
+ return new ZodNumber({
2208
+ ...this._def,
2209
+ checks: [...this._def.checks, check],
2210
+ });
2211
+ }
2212
+ int(message) {
2213
+ return this._addCheck({
2214
+ kind: "int",
2215
+ message: errorUtil.toString(message),
2216
+ });
2217
+ }
2218
+ positive(message) {
2219
+ return this._addCheck({
2220
+ kind: "min",
2221
+ value: 0,
2222
+ inclusive: false,
2223
+ message: errorUtil.toString(message),
2224
+ });
2225
+ }
2226
+ negative(message) {
2227
+ return this._addCheck({
2228
+ kind: "max",
2229
+ value: 0,
2230
+ inclusive: false,
2231
+ message: errorUtil.toString(message),
2232
+ });
2233
+ }
2234
+ nonpositive(message) {
2235
+ return this._addCheck({
2236
+ kind: "max",
2237
+ value: 0,
2238
+ inclusive: true,
2239
+ message: errorUtil.toString(message),
2240
+ });
2241
+ }
2242
+ nonnegative(message) {
2243
+ return this._addCheck({
2244
+ kind: "min",
2245
+ value: 0,
2246
+ inclusive: true,
2247
+ message: errorUtil.toString(message),
2248
+ });
2249
+ }
2250
+ multipleOf(value, message) {
2251
+ return this._addCheck({
2252
+ kind: "multipleOf",
2253
+ value: value,
2254
+ message: errorUtil.toString(message),
2255
+ });
2256
+ }
2257
+ finite(message) {
2258
+ return this._addCheck({
2259
+ kind: "finite",
2260
+ message: errorUtil.toString(message),
2261
+ });
2262
+ }
2263
+ safe(message) {
2264
+ return this._addCheck({
2265
+ kind: "min",
2266
+ inclusive: true,
2267
+ value: Number.MIN_SAFE_INTEGER,
2268
+ message: errorUtil.toString(message),
2269
+ })._addCheck({
2270
+ kind: "max",
2271
+ inclusive: true,
2272
+ value: Number.MAX_SAFE_INTEGER,
2273
+ message: errorUtil.toString(message),
2274
+ });
2275
+ }
2276
+ get minValue() {
2277
+ let min = null;
2278
+ for (const ch of this._def.checks) {
2279
+ if (ch.kind === "min") {
2280
+ if (min === null || ch.value > min)
2281
+ min = ch.value;
2282
+ }
2283
+ }
2284
+ return min;
2285
+ }
2286
+ get maxValue() {
2287
+ let max = null;
2288
+ for (const ch of this._def.checks) {
2289
+ if (ch.kind === "max") {
2290
+ if (max === null || ch.value < max)
2291
+ max = ch.value;
2292
+ }
2293
+ }
2294
+ return max;
2295
+ }
2296
+ get isInt() {
2297
+ return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value)));
2298
+ }
2299
+ get isFinite() {
2300
+ let max = null;
2301
+ let min = null;
2302
+ for (const ch of this._def.checks) {
2303
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
2304
+ return true;
2305
+ }
2306
+ else if (ch.kind === "min") {
2307
+ if (min === null || ch.value > min)
2308
+ min = ch.value;
2309
+ }
2310
+ else if (ch.kind === "max") {
2311
+ if (max === null || ch.value < max)
2312
+ max = ch.value;
2313
+ }
2314
+ }
2315
+ return Number.isFinite(min) && Number.isFinite(max);
2316
+ }
2317
+ }
2318
+ ZodNumber.create = (params) => {
2319
+ return new ZodNumber({
2320
+ checks: [],
2321
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
2322
+ coerce: params?.coerce || false,
2323
+ ...processCreateParams(params),
2324
+ });
2325
+ };
2326
+ class ZodBigInt extends ZodType {
2327
+ constructor() {
2328
+ super(...arguments);
2329
+ this.min = this.gte;
2330
+ this.max = this.lte;
2331
+ }
2332
+ _parse(input) {
2333
+ if (this._def.coerce) {
2334
+ try {
2335
+ input.data = BigInt(input.data);
2336
+ }
2337
+ catch {
2338
+ return this._getInvalidInput(input);
2339
+ }
2340
+ }
2341
+ const parsedType = this._getType(input);
2342
+ if (parsedType !== ZodParsedType.bigint) {
2343
+ return this._getInvalidInput(input);
2344
+ }
2345
+ let ctx = undefined;
2346
+ const status = new ParseStatus();
2347
+ for (const check of this._def.checks) {
2348
+ if (check.kind === "min") {
2349
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2350
+ if (tooSmall) {
2351
+ ctx = this._getOrReturnCtx(input, ctx);
2352
+ addIssueToContext(ctx, {
2353
+ code: ZodIssueCode.too_small,
2354
+ type: "bigint",
2355
+ minimum: check.value,
2356
+ inclusive: check.inclusive,
2357
+ message: check.message,
2358
+ });
2359
+ status.dirty();
2360
+ }
2361
+ }
2362
+ else if (check.kind === "max") {
2363
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2364
+ if (tooBig) {
2365
+ ctx = this._getOrReturnCtx(input, ctx);
2366
+ addIssueToContext(ctx, {
2367
+ code: ZodIssueCode.too_big,
2368
+ type: "bigint",
2369
+ maximum: check.value,
2370
+ inclusive: check.inclusive,
2371
+ message: check.message,
2372
+ });
2373
+ status.dirty();
2374
+ }
2375
+ }
2376
+ else if (check.kind === "multipleOf") {
2377
+ if (input.data % check.value !== BigInt(0)) {
2378
+ ctx = this._getOrReturnCtx(input, ctx);
2379
+ addIssueToContext(ctx, {
2380
+ code: ZodIssueCode.not_multiple_of,
2381
+ multipleOf: check.value,
2382
+ message: check.message,
2383
+ });
2384
+ status.dirty();
2385
+ }
2386
+ }
2387
+ else {
2388
+ util.assertNever(check);
2389
+ }
2390
+ }
2391
+ return { status: status.value, value: input.data };
2392
+ }
2393
+ _getInvalidInput(input) {
2394
+ const ctx = this._getOrReturnCtx(input);
2395
+ addIssueToContext(ctx, {
2396
+ code: ZodIssueCode.invalid_type,
2397
+ expected: ZodParsedType.bigint,
2398
+ received: ctx.parsedType,
2399
+ });
2400
+ return INVALID;
2401
+ }
2402
+ gte(value, message) {
2403
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2404
+ }
2405
+ gt(value, message) {
2406
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2407
+ }
2408
+ lte(value, message) {
2409
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2410
+ }
2411
+ lt(value, message) {
2412
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2413
+ }
2414
+ setLimit(kind, value, inclusive, message) {
2415
+ return new ZodBigInt({
2416
+ ...this._def,
2417
+ checks: [
2418
+ ...this._def.checks,
2419
+ {
2420
+ kind,
2421
+ value,
2422
+ inclusive,
2423
+ message: errorUtil.toString(message),
2424
+ },
2425
+ ],
2426
+ });
2427
+ }
2428
+ _addCheck(check) {
2429
+ return new ZodBigInt({
2430
+ ...this._def,
2431
+ checks: [...this._def.checks, check],
2432
+ });
2433
+ }
2434
+ positive(message) {
2435
+ return this._addCheck({
2436
+ kind: "min",
2437
+ value: BigInt(0),
2438
+ inclusive: false,
2439
+ message: errorUtil.toString(message),
2440
+ });
2441
+ }
2442
+ negative(message) {
2443
+ return this._addCheck({
2444
+ kind: "max",
2445
+ value: BigInt(0),
2446
+ inclusive: false,
2447
+ message: errorUtil.toString(message),
2448
+ });
2449
+ }
2450
+ nonpositive(message) {
2451
+ return this._addCheck({
2452
+ kind: "max",
2453
+ value: BigInt(0),
2454
+ inclusive: true,
2455
+ message: errorUtil.toString(message),
2456
+ });
2457
+ }
2458
+ nonnegative(message) {
2459
+ return this._addCheck({
2460
+ kind: "min",
2461
+ value: BigInt(0),
2462
+ inclusive: true,
2463
+ message: errorUtil.toString(message),
2464
+ });
2465
+ }
2466
+ multipleOf(value, message) {
2467
+ return this._addCheck({
2468
+ kind: "multipleOf",
2469
+ value,
2470
+ message: errorUtil.toString(message),
2471
+ });
2472
+ }
2473
+ get minValue() {
2474
+ let min = null;
2475
+ for (const ch of this._def.checks) {
2476
+ if (ch.kind === "min") {
2477
+ if (min === null || ch.value > min)
2478
+ min = ch.value;
2479
+ }
2480
+ }
2481
+ return min;
2482
+ }
2483
+ get maxValue() {
2484
+ let max = null;
2485
+ for (const ch of this._def.checks) {
2486
+ if (ch.kind === "max") {
2487
+ if (max === null || ch.value < max)
2488
+ max = ch.value;
2489
+ }
2490
+ }
2491
+ return max;
2492
+ }
2493
+ }
2494
+ ZodBigInt.create = (params) => {
2495
+ return new ZodBigInt({
2496
+ checks: [],
2497
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
2498
+ coerce: params?.coerce ?? false,
2499
+ ...processCreateParams(params),
2500
+ });
2501
+ };
2502
+ class ZodBoolean extends ZodType {
2503
+ _parse(input) {
2504
+ if (this._def.coerce) {
2505
+ input.data = Boolean(input.data);
2506
+ }
2507
+ const parsedType = this._getType(input);
2508
+ if (parsedType !== ZodParsedType.boolean) {
2509
+ const ctx = this._getOrReturnCtx(input);
2510
+ addIssueToContext(ctx, {
2511
+ code: ZodIssueCode.invalid_type,
2512
+ expected: ZodParsedType.boolean,
2513
+ received: ctx.parsedType,
2514
+ });
2515
+ return INVALID;
2516
+ }
2517
+ return OK(input.data);
2518
+ }
2519
+ }
2520
+ ZodBoolean.create = (params) => {
2521
+ return new ZodBoolean({
2522
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2523
+ coerce: params?.coerce || false,
2524
+ ...processCreateParams(params),
2525
+ });
2526
+ };
2527
+ class ZodDate extends ZodType {
2528
+ _parse(input) {
2529
+ if (this._def.coerce) {
2530
+ input.data = new Date(input.data);
2531
+ }
2532
+ const parsedType = this._getType(input);
2533
+ if (parsedType !== ZodParsedType.date) {
2534
+ const ctx = this._getOrReturnCtx(input);
2535
+ addIssueToContext(ctx, {
2536
+ code: ZodIssueCode.invalid_type,
2537
+ expected: ZodParsedType.date,
2538
+ received: ctx.parsedType,
2539
+ });
2540
+ return INVALID;
2541
+ }
2542
+ if (Number.isNaN(input.data.getTime())) {
2543
+ const ctx = this._getOrReturnCtx(input);
2544
+ addIssueToContext(ctx, {
2545
+ code: ZodIssueCode.invalid_date,
2546
+ });
2547
+ return INVALID;
2548
+ }
2549
+ const status = new ParseStatus();
2550
+ let ctx = undefined;
2551
+ for (const check of this._def.checks) {
2552
+ if (check.kind === "min") {
2553
+ if (input.data.getTime() < check.value) {
2554
+ ctx = this._getOrReturnCtx(input, ctx);
2555
+ addIssueToContext(ctx, {
2556
+ code: ZodIssueCode.too_small,
2557
+ message: check.message,
2558
+ inclusive: true,
2559
+ exact: false,
2560
+ minimum: check.value,
2561
+ type: "date",
2562
+ });
2563
+ status.dirty();
2564
+ }
2565
+ }
2566
+ else if (check.kind === "max") {
2567
+ if (input.data.getTime() > check.value) {
2568
+ ctx = this._getOrReturnCtx(input, ctx);
2569
+ addIssueToContext(ctx, {
2570
+ code: ZodIssueCode.too_big,
2571
+ message: check.message,
2572
+ inclusive: true,
2573
+ exact: false,
2574
+ maximum: check.value,
2575
+ type: "date",
2576
+ });
2577
+ status.dirty();
2578
+ }
2579
+ }
2580
+ else {
2581
+ util.assertNever(check);
2582
+ }
2583
+ }
2584
+ return {
2585
+ status: status.value,
2586
+ value: new Date(input.data.getTime()),
2587
+ };
2588
+ }
2589
+ _addCheck(check) {
2590
+ return new ZodDate({
2591
+ ...this._def,
2592
+ checks: [...this._def.checks, check],
2593
+ });
2594
+ }
2595
+ min(minDate, message) {
2596
+ return this._addCheck({
2597
+ kind: "min",
2598
+ value: minDate.getTime(),
2599
+ message: errorUtil.toString(message),
2600
+ });
2601
+ }
2602
+ max(maxDate, message) {
2603
+ return this._addCheck({
2604
+ kind: "max",
2605
+ value: maxDate.getTime(),
2606
+ message: errorUtil.toString(message),
2607
+ });
2608
+ }
2609
+ get minDate() {
2610
+ let min = null;
2611
+ for (const ch of this._def.checks) {
2612
+ if (ch.kind === "min") {
2613
+ if (min === null || ch.value > min)
2614
+ min = ch.value;
2615
+ }
2616
+ }
2617
+ return min != null ? new Date(min) : null;
2618
+ }
2619
+ get maxDate() {
2620
+ let max = null;
2621
+ for (const ch of this._def.checks) {
2622
+ if (ch.kind === "max") {
2623
+ if (max === null || ch.value < max)
2624
+ max = ch.value;
2625
+ }
2626
+ }
2627
+ return max != null ? new Date(max) : null;
2628
+ }
2629
+ }
2630
+ ZodDate.create = (params) => {
2631
+ return new ZodDate({
2632
+ checks: [],
2633
+ coerce: params?.coerce || false,
2634
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2635
+ ...processCreateParams(params),
2636
+ });
2637
+ };
2638
+ class ZodSymbol extends ZodType {
2639
+ _parse(input) {
2640
+ const parsedType = this._getType(input);
2641
+ if (parsedType !== ZodParsedType.symbol) {
2642
+ const ctx = this._getOrReturnCtx(input);
2643
+ addIssueToContext(ctx, {
2644
+ code: ZodIssueCode.invalid_type,
2645
+ expected: ZodParsedType.symbol,
2646
+ received: ctx.parsedType,
2647
+ });
2648
+ return INVALID;
2649
+ }
2650
+ return OK(input.data);
2651
+ }
2652
+ }
2653
+ ZodSymbol.create = (params) => {
2654
+ return new ZodSymbol({
2655
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2656
+ ...processCreateParams(params),
2657
+ });
2658
+ };
2659
+ class ZodUndefined extends ZodType {
2660
+ _parse(input) {
2661
+ const parsedType = this._getType(input);
2662
+ if (parsedType !== ZodParsedType.undefined) {
2663
+ const ctx = this._getOrReturnCtx(input);
2664
+ addIssueToContext(ctx, {
2665
+ code: ZodIssueCode.invalid_type,
2666
+ expected: ZodParsedType.undefined,
2667
+ received: ctx.parsedType,
2668
+ });
2669
+ return INVALID;
2670
+ }
2671
+ return OK(input.data);
2672
+ }
2673
+ }
2674
+ ZodUndefined.create = (params) => {
2675
+ return new ZodUndefined({
2676
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2677
+ ...processCreateParams(params),
2678
+ });
2679
+ };
2680
+ class ZodNull extends ZodType {
2681
+ _parse(input) {
2682
+ const parsedType = this._getType(input);
2683
+ if (parsedType !== ZodParsedType.null) {
2684
+ const ctx = this._getOrReturnCtx(input);
2685
+ addIssueToContext(ctx, {
2686
+ code: ZodIssueCode.invalid_type,
2687
+ expected: ZodParsedType.null,
2688
+ received: ctx.parsedType,
2689
+ });
2690
+ return INVALID;
2691
+ }
2692
+ return OK(input.data);
2693
+ }
2694
+ }
2695
+ ZodNull.create = (params) => {
2696
+ return new ZodNull({
2697
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2698
+ ...processCreateParams(params),
2699
+ });
2700
+ };
2701
+ class ZodAny extends ZodType {
2702
+ constructor() {
2703
+ super(...arguments);
2704
+ // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
2705
+ this._any = true;
2706
+ }
2707
+ _parse(input) {
2708
+ return OK(input.data);
2709
+ }
2710
+ }
2711
+ ZodAny.create = (params) => {
2712
+ return new ZodAny({
2713
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2714
+ ...processCreateParams(params),
2715
+ });
2716
+ };
2717
+ class ZodUnknown extends ZodType {
2718
+ constructor() {
2719
+ super(...arguments);
2720
+ // required
2721
+ this._unknown = true;
2722
+ }
2723
+ _parse(input) {
2724
+ return OK(input.data);
2725
+ }
2726
+ }
2727
+ ZodUnknown.create = (params) => {
2728
+ return new ZodUnknown({
2729
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2730
+ ...processCreateParams(params),
2731
+ });
2732
+ };
2733
+ class ZodNever extends ZodType {
2734
+ _parse(input) {
2735
+ const ctx = this._getOrReturnCtx(input);
2736
+ addIssueToContext(ctx, {
2737
+ code: ZodIssueCode.invalid_type,
2738
+ expected: ZodParsedType.never,
2739
+ received: ctx.parsedType,
2740
+ });
2741
+ return INVALID;
2742
+ }
2743
+ }
2744
+ ZodNever.create = (params) => {
2745
+ return new ZodNever({
2746
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2747
+ ...processCreateParams(params),
2748
+ });
2749
+ };
2750
+ class ZodVoid extends ZodType {
2751
+ _parse(input) {
2752
+ const parsedType = this._getType(input);
2753
+ if (parsedType !== ZodParsedType.undefined) {
2754
+ const ctx = this._getOrReturnCtx(input);
2755
+ addIssueToContext(ctx, {
2756
+ code: ZodIssueCode.invalid_type,
2757
+ expected: ZodParsedType.void,
2758
+ received: ctx.parsedType,
2759
+ });
2760
+ return INVALID;
2761
+ }
2762
+ return OK(input.data);
2763
+ }
2764
+ }
2765
+ ZodVoid.create = (params) => {
2766
+ return new ZodVoid({
2767
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2768
+ ...processCreateParams(params),
2769
+ });
2770
+ };
2771
+ class ZodArray extends ZodType {
2772
+ _parse(input) {
2773
+ const { ctx, status } = this._processInputParams(input);
2774
+ const def = this._def;
2775
+ if (ctx.parsedType !== ZodParsedType.array) {
2776
+ addIssueToContext(ctx, {
2777
+ code: ZodIssueCode.invalid_type,
2778
+ expected: ZodParsedType.array,
2779
+ received: ctx.parsedType,
2780
+ });
2781
+ return INVALID;
2782
+ }
2783
+ if (def.exactLength !== null) {
2784
+ const tooBig = ctx.data.length > def.exactLength.value;
2785
+ const tooSmall = ctx.data.length < def.exactLength.value;
2786
+ if (tooBig || tooSmall) {
2787
+ addIssueToContext(ctx, {
2788
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2789
+ minimum: (tooSmall ? def.exactLength.value : undefined),
2790
+ maximum: (tooBig ? def.exactLength.value : undefined),
2791
+ type: "array",
2792
+ inclusive: true,
2793
+ exact: true,
2794
+ message: def.exactLength.message,
2795
+ });
2796
+ status.dirty();
2797
+ }
2798
+ }
2799
+ if (def.minLength !== null) {
2800
+ if (ctx.data.length < def.minLength.value) {
2801
+ addIssueToContext(ctx, {
2802
+ code: ZodIssueCode.too_small,
2803
+ minimum: def.minLength.value,
2804
+ type: "array",
2805
+ inclusive: true,
2806
+ exact: false,
2807
+ message: def.minLength.message,
2808
+ });
2809
+ status.dirty();
2810
+ }
2811
+ }
2812
+ if (def.maxLength !== null) {
2813
+ if (ctx.data.length > def.maxLength.value) {
2814
+ addIssueToContext(ctx, {
2815
+ code: ZodIssueCode.too_big,
2816
+ maximum: def.maxLength.value,
2817
+ type: "array",
2818
+ inclusive: true,
2819
+ exact: false,
2820
+ message: def.maxLength.message,
2821
+ });
2822
+ status.dirty();
2823
+ }
2824
+ }
2825
+ if (ctx.common.async) {
2826
+ return Promise.all([...ctx.data].map((item, i) => {
2827
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2828
+ })).then((result) => {
2829
+ return ParseStatus.mergeArray(status, result);
2830
+ });
2831
+ }
2832
+ const result = [...ctx.data].map((item, i) => {
2833
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2834
+ });
2835
+ return ParseStatus.mergeArray(status, result);
2836
+ }
2837
+ get element() {
2838
+ return this._def.type;
2839
+ }
2840
+ min(minLength, message) {
2841
+ return new ZodArray({
2842
+ ...this._def,
2843
+ minLength: { value: minLength, message: errorUtil.toString(message) },
2844
+ });
2845
+ }
2846
+ max(maxLength, message) {
2847
+ return new ZodArray({
2848
+ ...this._def,
2849
+ maxLength: { value: maxLength, message: errorUtil.toString(message) },
2850
+ });
2851
+ }
2852
+ length(len, message) {
2853
+ return new ZodArray({
2854
+ ...this._def,
2855
+ exactLength: { value: len, message: errorUtil.toString(message) },
2856
+ });
2857
+ }
2858
+ nonempty(message) {
2859
+ return this.min(1, message);
2860
+ }
2861
+ }
2862
+ ZodArray.create = (schema, params) => {
2863
+ return new ZodArray({
2864
+ type: schema,
2865
+ minLength: null,
2866
+ maxLength: null,
2867
+ exactLength: null,
2868
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2869
+ ...processCreateParams(params),
2870
+ });
2871
+ };
2872
+ function deepPartialify(schema) {
2873
+ if (schema instanceof ZodObject) {
2874
+ const newShape = {};
2875
+ for (const key in schema.shape) {
2876
+ const fieldSchema = schema.shape[key];
2877
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2878
+ }
2879
+ return new ZodObject({
2880
+ ...schema._def,
2881
+ shape: () => newShape,
2882
+ });
2883
+ }
2884
+ else if (schema instanceof ZodArray) {
2885
+ return new ZodArray({
2886
+ ...schema._def,
2887
+ type: deepPartialify(schema.element),
2888
+ });
2889
+ }
2890
+ else if (schema instanceof ZodOptional) {
2891
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
2892
+ }
2893
+ else if (schema instanceof ZodNullable) {
2894
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
2895
+ }
2896
+ else if (schema instanceof ZodTuple) {
2897
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2898
+ }
2899
+ else {
2900
+ return schema;
2901
+ }
2902
+ }
2903
+ class ZodObject extends ZodType {
2904
+ constructor() {
2905
+ super(...arguments);
2906
+ this._cached = null;
2907
+ /**
2908
+ * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
2909
+ * If you want to pass through unknown properties, use `.passthrough()` instead.
2910
+ */
2911
+ this.nonstrict = this.passthrough;
2912
+ // extend<
2913
+ // Augmentation extends ZodRawShape,
2914
+ // NewOutput extends util.flatten<{
2915
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2916
+ // ? Augmentation[k]["_output"]
2917
+ // : k extends keyof Output
2918
+ // ? Output[k]
2919
+ // : never;
2920
+ // }>,
2921
+ // NewInput extends util.flatten<{
2922
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2923
+ // ? Augmentation[k]["_input"]
2924
+ // : k extends keyof Input
2925
+ // ? Input[k]
2926
+ // : never;
2927
+ // }>
2928
+ // >(
2929
+ // augmentation: Augmentation
2930
+ // ): ZodObject<
2931
+ // extendShape<T, Augmentation>,
2932
+ // UnknownKeys,
2933
+ // Catchall,
2934
+ // NewOutput,
2935
+ // NewInput
2936
+ // > {
2937
+ // return new ZodObject({
2938
+ // ...this._def,
2939
+ // shape: () => ({
2940
+ // ...this._def.shape(),
2941
+ // ...augmentation,
2942
+ // }),
2943
+ // }) as any;
2944
+ // }
2945
+ /**
2946
+ * @deprecated Use `.extend` instead
2947
+ * */
2948
+ this.augment = this.extend;
2949
+ }
2950
+ _getCached() {
2951
+ if (this._cached !== null)
2952
+ return this._cached;
2953
+ const shape = this._def.shape();
2954
+ const keys = util.objectKeys(shape);
2955
+ this._cached = { shape, keys };
2956
+ return this._cached;
2957
+ }
2958
+ _parse(input) {
2959
+ const parsedType = this._getType(input);
2960
+ if (parsedType !== ZodParsedType.object) {
2961
+ const ctx = this._getOrReturnCtx(input);
2962
+ addIssueToContext(ctx, {
2963
+ code: ZodIssueCode.invalid_type,
2964
+ expected: ZodParsedType.object,
2965
+ received: ctx.parsedType,
2966
+ });
2967
+ return INVALID;
2968
+ }
2969
+ const { status, ctx } = this._processInputParams(input);
2970
+ const { shape, keys: shapeKeys } = this._getCached();
2971
+ const extraKeys = [];
2972
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2973
+ for (const key in ctx.data) {
2974
+ if (!shapeKeys.includes(key)) {
2975
+ extraKeys.push(key);
2976
+ }
2977
+ }
2978
+ }
2979
+ const pairs = [];
2980
+ for (const key of shapeKeys) {
2981
+ const keyValidator = shape[key];
2982
+ const value = ctx.data[key];
2983
+ pairs.push({
2984
+ key: { status: "valid", value: key },
2985
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2986
+ alwaysSet: key in ctx.data,
2987
+ });
2988
+ }
2989
+ if (this._def.catchall instanceof ZodNever) {
2990
+ const unknownKeys = this._def.unknownKeys;
2991
+ if (unknownKeys === "passthrough") {
2992
+ for (const key of extraKeys) {
2993
+ pairs.push({
2994
+ key: { status: "valid", value: key },
2995
+ value: { status: "valid", value: ctx.data[key] },
2996
+ });
2997
+ }
2998
+ }
2999
+ else if (unknownKeys === "strict") {
3000
+ if (extraKeys.length > 0) {
3001
+ addIssueToContext(ctx, {
3002
+ code: ZodIssueCode.unrecognized_keys,
3003
+ keys: extraKeys,
3004
+ });
3005
+ status.dirty();
3006
+ }
3007
+ }
3008
+ else if (unknownKeys === "strip") ;
3009
+ else {
3010
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
3011
+ }
3012
+ }
3013
+ else {
3014
+ // run catchall validation
3015
+ const catchall = this._def.catchall;
3016
+ for (const key of extraKeys) {
3017
+ const value = ctx.data[key];
3018
+ pairs.push({
3019
+ key: { status: "valid", value: key },
3020
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
3021
+ ),
3022
+ alwaysSet: key in ctx.data,
3023
+ });
3024
+ }
3025
+ }
3026
+ if (ctx.common.async) {
3027
+ return Promise.resolve()
3028
+ .then(async () => {
3029
+ const syncPairs = [];
3030
+ for (const pair of pairs) {
3031
+ const key = await pair.key;
3032
+ const value = await pair.value;
3033
+ syncPairs.push({
3034
+ key,
3035
+ value,
3036
+ alwaysSet: pair.alwaysSet,
3037
+ });
3038
+ }
3039
+ return syncPairs;
3040
+ })
3041
+ .then((syncPairs) => {
3042
+ return ParseStatus.mergeObjectSync(status, syncPairs);
3043
+ });
3044
+ }
3045
+ else {
3046
+ return ParseStatus.mergeObjectSync(status, pairs);
3047
+ }
3048
+ }
3049
+ get shape() {
3050
+ return this._def.shape();
3051
+ }
3052
+ strict(message) {
3053
+ errorUtil.errToObj;
3054
+ return new ZodObject({
3055
+ ...this._def,
3056
+ unknownKeys: "strict",
3057
+ ...(message !== undefined
3058
+ ? {
3059
+ errorMap: (issue, ctx) => {
3060
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
3061
+ if (issue.code === "unrecognized_keys")
3062
+ return {
3063
+ message: errorUtil.errToObj(message).message ?? defaultError,
3064
+ };
3065
+ return {
3066
+ message: defaultError,
3067
+ };
3068
+ },
3069
+ }
3070
+ : {}),
3071
+ });
3072
+ }
3073
+ strip() {
3074
+ return new ZodObject({
3075
+ ...this._def,
3076
+ unknownKeys: "strip",
3077
+ });
3078
+ }
3079
+ passthrough() {
3080
+ return new ZodObject({
3081
+ ...this._def,
3082
+ unknownKeys: "passthrough",
3083
+ });
3084
+ }
3085
+ // const AugmentFactory =
3086
+ // <Def extends ZodObjectDef>(def: Def) =>
3087
+ // <Augmentation extends ZodRawShape>(
3088
+ // augmentation: Augmentation
3089
+ // ): ZodObject<
3090
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
3091
+ // Def["unknownKeys"],
3092
+ // Def["catchall"]
3093
+ // > => {
3094
+ // return new ZodObject({
3095
+ // ...def,
3096
+ // shape: () => ({
3097
+ // ...def.shape(),
3098
+ // ...augmentation,
3099
+ // }),
3100
+ // }) as any;
3101
+ // };
3102
+ extend(augmentation) {
3103
+ return new ZodObject({
3104
+ ...this._def,
3105
+ shape: () => ({
3106
+ ...this._def.shape(),
3107
+ ...augmentation,
3108
+ }),
3109
+ });
3110
+ }
3111
+ /**
3112
+ * Prior to zod@1.0.12 there was a bug in the
3113
+ * inferred type of merged objects. Please
3114
+ * upgrade if you are experiencing issues.
3115
+ */
3116
+ merge(merging) {
3117
+ const merged = new ZodObject({
3118
+ unknownKeys: merging._def.unknownKeys,
3119
+ catchall: merging._def.catchall,
3120
+ shape: () => ({
3121
+ ...this._def.shape(),
3122
+ ...merging._def.shape(),
3123
+ }),
3124
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3125
+ });
3126
+ return merged;
3127
+ }
3128
+ // merge<
3129
+ // Incoming extends AnyZodObject,
3130
+ // Augmentation extends Incoming["shape"],
3131
+ // NewOutput extends {
3132
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
3133
+ // ? Augmentation[k]["_output"]
3134
+ // : k extends keyof Output
3135
+ // ? Output[k]
3136
+ // : never;
3137
+ // },
3138
+ // NewInput extends {
3139
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
3140
+ // ? Augmentation[k]["_input"]
3141
+ // : k extends keyof Input
3142
+ // ? Input[k]
3143
+ // : never;
3144
+ // }
3145
+ // >(
3146
+ // merging: Incoming
3147
+ // ): ZodObject<
3148
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
3149
+ // Incoming["_def"]["unknownKeys"],
3150
+ // Incoming["_def"]["catchall"],
3151
+ // NewOutput,
3152
+ // NewInput
3153
+ // > {
3154
+ // const merged: any = new ZodObject({
3155
+ // unknownKeys: merging._def.unknownKeys,
3156
+ // catchall: merging._def.catchall,
3157
+ // shape: () =>
3158
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
3159
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
3160
+ // }) as any;
3161
+ // return merged;
3162
+ // }
3163
+ setKey(key, schema) {
3164
+ return this.augment({ [key]: schema });
3165
+ }
3166
+ // merge<Incoming extends AnyZodObject>(
3167
+ // merging: Incoming
3168
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
3169
+ // ZodObject<
3170
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
3171
+ // Incoming["_def"]["unknownKeys"],
3172
+ // Incoming["_def"]["catchall"]
3173
+ // > {
3174
+ // // const mergedShape = objectUtil.mergeShapes(
3175
+ // // this._def.shape(),
3176
+ // // merging._def.shape()
3177
+ // // );
3178
+ // const merged: any = new ZodObject({
3179
+ // unknownKeys: merging._def.unknownKeys,
3180
+ // catchall: merging._def.catchall,
3181
+ // shape: () =>
3182
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
3183
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
3184
+ // }) as any;
3185
+ // return merged;
3186
+ // }
3187
+ catchall(index) {
3188
+ return new ZodObject({
3189
+ ...this._def,
3190
+ catchall: index,
3191
+ });
3192
+ }
3193
+ pick(mask) {
3194
+ const shape = {};
3195
+ for (const key of util.objectKeys(mask)) {
3196
+ if (mask[key] && this.shape[key]) {
3197
+ shape[key] = this.shape[key];
3198
+ }
3199
+ }
3200
+ return new ZodObject({
3201
+ ...this._def,
3202
+ shape: () => shape,
3203
+ });
3204
+ }
3205
+ omit(mask) {
3206
+ const shape = {};
3207
+ for (const key of util.objectKeys(this.shape)) {
3208
+ if (!mask[key]) {
3209
+ shape[key] = this.shape[key];
3210
+ }
3211
+ }
3212
+ return new ZodObject({
3213
+ ...this._def,
3214
+ shape: () => shape,
3215
+ });
3216
+ }
3217
+ /**
3218
+ * @deprecated
3219
+ */
3220
+ deepPartial() {
3221
+ return deepPartialify(this);
3222
+ }
3223
+ partial(mask) {
3224
+ const newShape = {};
3225
+ for (const key of util.objectKeys(this.shape)) {
3226
+ const fieldSchema = this.shape[key];
3227
+ if (mask && !mask[key]) {
3228
+ newShape[key] = fieldSchema;
3229
+ }
3230
+ else {
3231
+ newShape[key] = fieldSchema.optional();
3232
+ }
3233
+ }
3234
+ return new ZodObject({
3235
+ ...this._def,
3236
+ shape: () => newShape,
3237
+ });
3238
+ }
3239
+ required(mask) {
3240
+ const newShape = {};
3241
+ for (const key of util.objectKeys(this.shape)) {
3242
+ if (mask && !mask[key]) {
3243
+ newShape[key] = this.shape[key];
3244
+ }
3245
+ else {
3246
+ const fieldSchema = this.shape[key];
3247
+ let newField = fieldSchema;
3248
+ while (newField instanceof ZodOptional) {
3249
+ newField = newField._def.innerType;
3250
+ }
3251
+ newShape[key] = newField;
3252
+ }
3253
+ }
3254
+ return new ZodObject({
3255
+ ...this._def,
3256
+ shape: () => newShape,
3257
+ });
3258
+ }
3259
+ keyof() {
3260
+ return createZodEnum(util.objectKeys(this.shape));
3261
+ }
3262
+ }
3263
+ ZodObject.create = (shape, params) => {
3264
+ return new ZodObject({
3265
+ shape: () => shape,
3266
+ unknownKeys: "strip",
3267
+ catchall: ZodNever.create(),
3268
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3269
+ ...processCreateParams(params),
3270
+ });
3271
+ };
3272
+ ZodObject.strictCreate = (shape, params) => {
3273
+ return new ZodObject({
3274
+ shape: () => shape,
3275
+ unknownKeys: "strict",
3276
+ catchall: ZodNever.create(),
3277
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3278
+ ...processCreateParams(params),
3279
+ });
3280
+ };
3281
+ ZodObject.lazycreate = (shape, params) => {
3282
+ return new ZodObject({
3283
+ shape,
3284
+ unknownKeys: "strip",
3285
+ catchall: ZodNever.create(),
3286
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3287
+ ...processCreateParams(params),
3288
+ });
3289
+ };
3290
+ class ZodUnion extends ZodType {
3291
+ _parse(input) {
3292
+ const { ctx } = this._processInputParams(input);
3293
+ const options = this._def.options;
3294
+ function handleResults(results) {
3295
+ // return first issue-free validation if it exists
3296
+ for (const result of results) {
3297
+ if (result.result.status === "valid") {
3298
+ return result.result;
3299
+ }
3300
+ }
3301
+ for (const result of results) {
3302
+ if (result.result.status === "dirty") {
3303
+ // add issues from dirty option
3304
+ ctx.common.issues.push(...result.ctx.common.issues);
3305
+ return result.result;
3306
+ }
3307
+ }
3308
+ // return invalid
3309
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
3310
+ addIssueToContext(ctx, {
3311
+ code: ZodIssueCode.invalid_union,
3312
+ unionErrors,
3313
+ });
3314
+ return INVALID;
3315
+ }
3316
+ if (ctx.common.async) {
3317
+ return Promise.all(options.map(async (option) => {
3318
+ const childCtx = {
3319
+ ...ctx,
3320
+ common: {
3321
+ ...ctx.common,
3322
+ issues: [],
3323
+ },
3324
+ parent: null,
3325
+ };
3326
+ return {
3327
+ result: await option._parseAsync({
3328
+ data: ctx.data,
3329
+ path: ctx.path,
3330
+ parent: childCtx,
3331
+ }),
3332
+ ctx: childCtx,
3333
+ };
3334
+ })).then(handleResults);
3335
+ }
3336
+ else {
3337
+ let dirty = undefined;
3338
+ const issues = [];
3339
+ for (const option of options) {
3340
+ const childCtx = {
3341
+ ...ctx,
3342
+ common: {
3343
+ ...ctx.common,
3344
+ issues: [],
3345
+ },
3346
+ parent: null,
3347
+ };
3348
+ const result = option._parseSync({
3349
+ data: ctx.data,
3350
+ path: ctx.path,
3351
+ parent: childCtx,
3352
+ });
3353
+ if (result.status === "valid") {
3354
+ return result;
3355
+ }
3356
+ else if (result.status === "dirty" && !dirty) {
3357
+ dirty = { result, ctx: childCtx };
3358
+ }
3359
+ if (childCtx.common.issues.length) {
3360
+ issues.push(childCtx.common.issues);
3361
+ }
3362
+ }
3363
+ if (dirty) {
3364
+ ctx.common.issues.push(...dirty.ctx.common.issues);
3365
+ return dirty.result;
3366
+ }
3367
+ const unionErrors = issues.map((issues) => new ZodError(issues));
3368
+ addIssueToContext(ctx, {
3369
+ code: ZodIssueCode.invalid_union,
3370
+ unionErrors,
3371
+ });
3372
+ return INVALID;
3373
+ }
3374
+ }
3375
+ get options() {
3376
+ return this._def.options;
3377
+ }
3378
+ }
3379
+ ZodUnion.create = (types, params) => {
3380
+ return new ZodUnion({
3381
+ options: types,
3382
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
3383
+ ...processCreateParams(params),
3384
+ });
3385
+ };
3386
+ /////////////////////////////////////////////////////
3387
+ /////////////////////////////////////////////////////
3388
+ ////////// //////////
3389
+ ////////// ZodDiscriminatedUnion //////////
3390
+ ////////// //////////
3391
+ /////////////////////////////////////////////////////
3392
+ /////////////////////////////////////////////////////
3393
+ const getDiscriminator = (type) => {
3394
+ if (type instanceof ZodLazy) {
3395
+ return getDiscriminator(type.schema);
3396
+ }
3397
+ else if (type instanceof ZodEffects) {
3398
+ return getDiscriminator(type.innerType());
3399
+ }
3400
+ else if (type instanceof ZodLiteral) {
3401
+ return [type.value];
3402
+ }
3403
+ else if (type instanceof ZodEnum) {
3404
+ return type.options;
3405
+ }
3406
+ else if (type instanceof ZodNativeEnum) {
3407
+ // eslint-disable-next-line ban/ban
3408
+ return util.objectValues(type.enum);
3409
+ }
3410
+ else if (type instanceof ZodDefault) {
3411
+ return getDiscriminator(type._def.innerType);
3412
+ }
3413
+ else if (type instanceof ZodUndefined) {
3414
+ return [undefined];
3415
+ }
3416
+ else if (type instanceof ZodNull) {
3417
+ return [null];
3418
+ }
3419
+ else if (type instanceof ZodOptional) {
3420
+ return [undefined, ...getDiscriminator(type.unwrap())];
3421
+ }
3422
+ else if (type instanceof ZodNullable) {
3423
+ return [null, ...getDiscriminator(type.unwrap())];
3424
+ }
3425
+ else if (type instanceof ZodBranded) {
3426
+ return getDiscriminator(type.unwrap());
3427
+ }
3428
+ else if (type instanceof ZodReadonly) {
3429
+ return getDiscriminator(type.unwrap());
3430
+ }
3431
+ else if (type instanceof ZodCatch) {
3432
+ return getDiscriminator(type._def.innerType);
3433
+ }
3434
+ else {
3435
+ return [];
3436
+ }
3437
+ };
3438
+ class ZodDiscriminatedUnion extends ZodType {
3439
+ _parse(input) {
3440
+ const { ctx } = this._processInputParams(input);
3441
+ if (ctx.parsedType !== ZodParsedType.object) {
3442
+ addIssueToContext(ctx, {
3443
+ code: ZodIssueCode.invalid_type,
3444
+ expected: ZodParsedType.object,
3445
+ received: ctx.parsedType,
3446
+ });
3447
+ return INVALID;
3448
+ }
3449
+ const discriminator = this.discriminator;
3450
+ const discriminatorValue = ctx.data[discriminator];
3451
+ const option = this.optionsMap.get(discriminatorValue);
3452
+ if (!option) {
3453
+ addIssueToContext(ctx, {
3454
+ code: ZodIssueCode.invalid_union_discriminator,
3455
+ options: Array.from(this.optionsMap.keys()),
3456
+ path: [discriminator],
3457
+ });
3458
+ return INVALID;
3459
+ }
3460
+ if (ctx.common.async) {
3461
+ return option._parseAsync({
3462
+ data: ctx.data,
3463
+ path: ctx.path,
3464
+ parent: ctx,
3465
+ });
3466
+ }
3467
+ else {
3468
+ return option._parseSync({
3469
+ data: ctx.data,
3470
+ path: ctx.path,
3471
+ parent: ctx,
3472
+ });
3473
+ }
3474
+ }
3475
+ get discriminator() {
3476
+ return this._def.discriminator;
3477
+ }
3478
+ get options() {
3479
+ return this._def.options;
3480
+ }
3481
+ get optionsMap() {
3482
+ return this._def.optionsMap;
3483
+ }
3484
+ /**
3485
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
3486
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
3487
+ * have a different value for each object in the union.
3488
+ * @param discriminator the name of the discriminator property
3489
+ * @param types an array of object schemas
3490
+ * @param params
3491
+ */
3492
+ static create(discriminator, options, params) {
3493
+ // Get all the valid discriminator values
3494
+ const optionsMap = new Map();
3495
+ // try {
3496
+ for (const type of options) {
3497
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3498
+ if (!discriminatorValues.length) {
3499
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3500
+ }
3501
+ for (const value of discriminatorValues) {
3502
+ if (optionsMap.has(value)) {
3503
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
3504
+ }
3505
+ optionsMap.set(value, type);
3506
+ }
3507
+ }
3508
+ return new ZodDiscriminatedUnion({
3509
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
3510
+ discriminator,
3511
+ options,
3512
+ optionsMap,
3513
+ ...processCreateParams(params),
3514
+ });
3515
+ }
3516
+ }
3517
+ function mergeValues(a, b) {
3518
+ const aType = getParsedType(a);
3519
+ const bType = getParsedType(b);
3520
+ if (a === b) {
3521
+ return { valid: true, data: a };
3522
+ }
3523
+ else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
3524
+ const bKeys = util.objectKeys(b);
3525
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
3526
+ const newObj = { ...a, ...b };
3527
+ for (const key of sharedKeys) {
3528
+ const sharedValue = mergeValues(a[key], b[key]);
3529
+ if (!sharedValue.valid) {
3530
+ return { valid: false };
3531
+ }
3532
+ newObj[key] = sharedValue.data;
3533
+ }
3534
+ return { valid: true, data: newObj };
3535
+ }
3536
+ else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
3537
+ if (a.length !== b.length) {
3538
+ return { valid: false };
3539
+ }
3540
+ const newArray = [];
3541
+ for (let index = 0; index < a.length; index++) {
3542
+ const itemA = a[index];
3543
+ const itemB = b[index];
3544
+ const sharedValue = mergeValues(itemA, itemB);
3545
+ if (!sharedValue.valid) {
3546
+ return { valid: false };
3547
+ }
3548
+ newArray.push(sharedValue.data);
3549
+ }
3550
+ return { valid: true, data: newArray };
3551
+ }
3552
+ else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
3553
+ return { valid: true, data: a };
3554
+ }
3555
+ else {
3556
+ return { valid: false };
3557
+ }
3558
+ }
3559
+ class ZodIntersection extends ZodType {
3560
+ _parse(input) {
3561
+ const { status, ctx } = this._processInputParams(input);
3562
+ const handleParsed = (parsedLeft, parsedRight) => {
3563
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
3564
+ return INVALID;
3565
+ }
3566
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
3567
+ if (!merged.valid) {
3568
+ addIssueToContext(ctx, {
3569
+ code: ZodIssueCode.invalid_intersection_types,
3570
+ });
3571
+ return INVALID;
3572
+ }
3573
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
3574
+ status.dirty();
3575
+ }
3576
+ return { status: status.value, value: merged.data };
3577
+ };
3578
+ if (ctx.common.async) {
3579
+ return Promise.all([
3580
+ this._def.left._parseAsync({
3581
+ data: ctx.data,
3582
+ path: ctx.path,
3583
+ parent: ctx,
3584
+ }),
3585
+ this._def.right._parseAsync({
3586
+ data: ctx.data,
3587
+ path: ctx.path,
3588
+ parent: ctx,
3589
+ }),
3590
+ ]).then(([left, right]) => handleParsed(left, right));
3591
+ }
3592
+ else {
3593
+ return handleParsed(this._def.left._parseSync({
3594
+ data: ctx.data,
3595
+ path: ctx.path,
3596
+ parent: ctx,
3597
+ }), this._def.right._parseSync({
3598
+ data: ctx.data,
3599
+ path: ctx.path,
3600
+ parent: ctx,
3601
+ }));
3602
+ }
3603
+ }
3604
+ }
3605
+ ZodIntersection.create = (left, right, params) => {
3606
+ return new ZodIntersection({
3607
+ left: left,
3608
+ right: right,
3609
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
3610
+ ...processCreateParams(params),
3611
+ });
3612
+ };
3613
+ // type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];
3614
+ class ZodTuple extends ZodType {
3615
+ _parse(input) {
3616
+ const { status, ctx } = this._processInputParams(input);
3617
+ if (ctx.parsedType !== ZodParsedType.array) {
3618
+ addIssueToContext(ctx, {
3619
+ code: ZodIssueCode.invalid_type,
3620
+ expected: ZodParsedType.array,
3621
+ received: ctx.parsedType,
3622
+ });
3623
+ return INVALID;
3624
+ }
3625
+ if (ctx.data.length < this._def.items.length) {
3626
+ addIssueToContext(ctx, {
3627
+ code: ZodIssueCode.too_small,
3628
+ minimum: this._def.items.length,
3629
+ inclusive: true,
3630
+ exact: false,
3631
+ type: "array",
3632
+ });
3633
+ return INVALID;
3634
+ }
3635
+ const rest = this._def.rest;
3636
+ if (!rest && ctx.data.length > this._def.items.length) {
3637
+ addIssueToContext(ctx, {
3638
+ code: ZodIssueCode.too_big,
3639
+ maximum: this._def.items.length,
3640
+ inclusive: true,
3641
+ exact: false,
3642
+ type: "array",
3643
+ });
3644
+ status.dirty();
3645
+ }
3646
+ const items = [...ctx.data]
3647
+ .map((item, itemIndex) => {
3648
+ const schema = this._def.items[itemIndex] || this._def.rest;
3649
+ if (!schema)
3650
+ return null;
3651
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3652
+ })
3653
+ .filter((x) => !!x); // filter nulls
3654
+ if (ctx.common.async) {
3655
+ return Promise.all(items).then((results) => {
3656
+ return ParseStatus.mergeArray(status, results);
3657
+ });
3658
+ }
3659
+ else {
3660
+ return ParseStatus.mergeArray(status, items);
3661
+ }
3662
+ }
3663
+ get items() {
3664
+ return this._def.items;
3665
+ }
3666
+ rest(rest) {
3667
+ return new ZodTuple({
3668
+ ...this._def,
3669
+ rest,
3670
+ });
3671
+ }
3672
+ }
3673
+ ZodTuple.create = (schemas, params) => {
3674
+ if (!Array.isArray(schemas)) {
3675
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3676
+ }
3677
+ return new ZodTuple({
3678
+ items: schemas,
3679
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
3680
+ rest: null,
3681
+ ...processCreateParams(params),
3682
+ });
3683
+ };
3684
+ class ZodRecord extends ZodType {
3685
+ get keySchema() {
3686
+ return this._def.keyType;
3687
+ }
3688
+ get valueSchema() {
3689
+ return this._def.valueType;
3690
+ }
3691
+ _parse(input) {
3692
+ const { status, ctx } = this._processInputParams(input);
3693
+ if (ctx.parsedType !== ZodParsedType.object) {
3694
+ addIssueToContext(ctx, {
3695
+ code: ZodIssueCode.invalid_type,
3696
+ expected: ZodParsedType.object,
3697
+ received: ctx.parsedType,
3698
+ });
3699
+ return INVALID;
3700
+ }
3701
+ const pairs = [];
3702
+ const keyType = this._def.keyType;
3703
+ const valueType = this._def.valueType;
3704
+ for (const key in ctx.data) {
3705
+ pairs.push({
3706
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3707
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3708
+ alwaysSet: key in ctx.data,
3709
+ });
3710
+ }
3711
+ if (ctx.common.async) {
3712
+ return ParseStatus.mergeObjectAsync(status, pairs);
3713
+ }
3714
+ else {
3715
+ return ParseStatus.mergeObjectSync(status, pairs);
3716
+ }
3717
+ }
3718
+ get element() {
3719
+ return this._def.valueType;
3720
+ }
3721
+ static create(first, second, third) {
3722
+ if (second instanceof ZodType) {
3723
+ return new ZodRecord({
3724
+ keyType: first,
3725
+ valueType: second,
3726
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3727
+ ...processCreateParams(third),
3728
+ });
3729
+ }
3730
+ return new ZodRecord({
3731
+ keyType: ZodString.create(),
3732
+ valueType: first,
3733
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3734
+ ...processCreateParams(second),
3735
+ });
3736
+ }
3737
+ }
3738
+ class ZodMap extends ZodType {
3739
+ get keySchema() {
3740
+ return this._def.keyType;
3741
+ }
3742
+ get valueSchema() {
3743
+ return this._def.valueType;
3744
+ }
3745
+ _parse(input) {
3746
+ const { status, ctx } = this._processInputParams(input);
3747
+ if (ctx.parsedType !== ZodParsedType.map) {
3748
+ addIssueToContext(ctx, {
3749
+ code: ZodIssueCode.invalid_type,
3750
+ expected: ZodParsedType.map,
3751
+ received: ctx.parsedType,
3752
+ });
3753
+ return INVALID;
3754
+ }
3755
+ const keyType = this._def.keyType;
3756
+ const valueType = this._def.valueType;
3757
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3758
+ return {
3759
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3760
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
3761
+ };
3762
+ });
3763
+ if (ctx.common.async) {
3764
+ const finalMap = new Map();
3765
+ return Promise.resolve().then(async () => {
3766
+ for (const pair of pairs) {
3767
+ const key = await pair.key;
3768
+ const value = await pair.value;
3769
+ if (key.status === "aborted" || value.status === "aborted") {
3770
+ return INVALID;
3771
+ }
3772
+ if (key.status === "dirty" || value.status === "dirty") {
3773
+ status.dirty();
3774
+ }
3775
+ finalMap.set(key.value, value.value);
3776
+ }
3777
+ return { status: status.value, value: finalMap };
3778
+ });
3779
+ }
3780
+ else {
3781
+ const finalMap = new Map();
3782
+ for (const pair of pairs) {
3783
+ const key = pair.key;
3784
+ const value = pair.value;
3785
+ if (key.status === "aborted" || value.status === "aborted") {
3786
+ return INVALID;
3787
+ }
3788
+ if (key.status === "dirty" || value.status === "dirty") {
3789
+ status.dirty();
3790
+ }
3791
+ finalMap.set(key.value, value.value);
3792
+ }
3793
+ return { status: status.value, value: finalMap };
3794
+ }
3795
+ }
3796
+ }
3797
+ ZodMap.create = (keyType, valueType, params) => {
3798
+ return new ZodMap({
3799
+ valueType,
3800
+ keyType,
3801
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3802
+ ...processCreateParams(params),
3803
+ });
3804
+ };
3805
+ class ZodSet extends ZodType {
3806
+ _parse(input) {
3807
+ const { status, ctx } = this._processInputParams(input);
3808
+ if (ctx.parsedType !== ZodParsedType.set) {
3809
+ addIssueToContext(ctx, {
3810
+ code: ZodIssueCode.invalid_type,
3811
+ expected: ZodParsedType.set,
3812
+ received: ctx.parsedType,
3813
+ });
3814
+ return INVALID;
3815
+ }
3816
+ const def = this._def;
3817
+ if (def.minSize !== null) {
3818
+ if (ctx.data.size < def.minSize.value) {
3819
+ addIssueToContext(ctx, {
3820
+ code: ZodIssueCode.too_small,
3821
+ minimum: def.minSize.value,
3822
+ type: "set",
3823
+ inclusive: true,
3824
+ exact: false,
3825
+ message: def.minSize.message,
3826
+ });
3827
+ status.dirty();
3828
+ }
3829
+ }
3830
+ if (def.maxSize !== null) {
3831
+ if (ctx.data.size > def.maxSize.value) {
3832
+ addIssueToContext(ctx, {
3833
+ code: ZodIssueCode.too_big,
3834
+ maximum: def.maxSize.value,
3835
+ type: "set",
3836
+ inclusive: true,
3837
+ exact: false,
3838
+ message: def.maxSize.message,
3839
+ });
3840
+ status.dirty();
3841
+ }
3842
+ }
3843
+ const valueType = this._def.valueType;
3844
+ function finalizeSet(elements) {
3845
+ const parsedSet = new Set();
3846
+ for (const element of elements) {
3847
+ if (element.status === "aborted")
3848
+ return INVALID;
3849
+ if (element.status === "dirty")
3850
+ status.dirty();
3851
+ parsedSet.add(element.value);
3852
+ }
3853
+ return { status: status.value, value: parsedSet };
3854
+ }
3855
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3856
+ if (ctx.common.async) {
3857
+ return Promise.all(elements).then((elements) => finalizeSet(elements));
3858
+ }
3859
+ else {
3860
+ return finalizeSet(elements);
3861
+ }
3862
+ }
3863
+ min(minSize, message) {
3864
+ return new ZodSet({
3865
+ ...this._def,
3866
+ minSize: { value: minSize, message: errorUtil.toString(message) },
3867
+ });
3868
+ }
3869
+ max(maxSize, message) {
3870
+ return new ZodSet({
3871
+ ...this._def,
3872
+ maxSize: { value: maxSize, message: errorUtil.toString(message) },
3873
+ });
3874
+ }
3875
+ size(size, message) {
3876
+ return this.min(size, message).max(size, message);
3877
+ }
3878
+ nonempty(message) {
3879
+ return this.min(1, message);
3880
+ }
3881
+ }
3882
+ ZodSet.create = (valueType, params) => {
3883
+ return new ZodSet({
3884
+ valueType,
3885
+ minSize: null,
3886
+ maxSize: null,
3887
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3888
+ ...processCreateParams(params),
3889
+ });
3890
+ };
3891
+ class ZodFunction extends ZodType {
3892
+ constructor() {
3893
+ super(...arguments);
3894
+ this.validate = this.implement;
3895
+ }
3896
+ _parse(input) {
3897
+ const { ctx } = this._processInputParams(input);
3898
+ if (ctx.parsedType !== ZodParsedType.function) {
3899
+ addIssueToContext(ctx, {
3900
+ code: ZodIssueCode.invalid_type,
3901
+ expected: ZodParsedType.function,
3902
+ received: ctx.parsedType,
3903
+ });
3904
+ return INVALID;
3905
+ }
3906
+ function makeArgsIssue(args, error) {
3907
+ return makeIssue({
3908
+ data: args,
3909
+ path: ctx.path,
3910
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap].filter((x) => !!x),
3911
+ issueData: {
3912
+ code: ZodIssueCode.invalid_arguments,
3913
+ argumentsError: error,
3914
+ },
3915
+ });
3916
+ }
3917
+ function makeReturnsIssue(returns, error) {
3918
+ return makeIssue({
3919
+ data: returns,
3920
+ path: ctx.path,
3921
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap].filter((x) => !!x),
3922
+ issueData: {
3923
+ code: ZodIssueCode.invalid_return_type,
3924
+ returnTypeError: error,
3925
+ },
3926
+ });
3927
+ }
3928
+ const params = { errorMap: ctx.common.contextualErrorMap };
3929
+ const fn = ctx.data;
3930
+ if (this._def.returns instanceof ZodPromise) {
3931
+ // Would love a way to avoid disabling this rule, but we need
3932
+ // an alias (using an arrow function was what caused 2651).
3933
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
3934
+ const me = this;
3935
+ return OK(async function (...args) {
3936
+ const error = new ZodError([]);
3937
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3938
+ error.addIssue(makeArgsIssue(args, e));
3939
+ throw error;
3940
+ });
3941
+ const result = await Reflect.apply(fn, this, parsedArgs);
3942
+ const parsedReturns = await me._def.returns._def.type
3943
+ .parseAsync(result, params)
3944
+ .catch((e) => {
3945
+ error.addIssue(makeReturnsIssue(result, e));
3946
+ throw error;
3947
+ });
3948
+ return parsedReturns;
3949
+ });
3950
+ }
3951
+ else {
3952
+ // Would love a way to avoid disabling this rule, but we need
3953
+ // an alias (using an arrow function was what caused 2651).
3954
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
3955
+ const me = this;
3956
+ return OK(function (...args) {
3957
+ const parsedArgs = me._def.args.safeParse(args, params);
3958
+ if (!parsedArgs.success) {
3959
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3960
+ }
3961
+ const result = Reflect.apply(fn, this, parsedArgs.data);
3962
+ const parsedReturns = me._def.returns.safeParse(result, params);
3963
+ if (!parsedReturns.success) {
3964
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3965
+ }
3966
+ return parsedReturns.data;
3967
+ });
3968
+ }
3969
+ }
3970
+ parameters() {
3971
+ return this._def.args;
3972
+ }
3973
+ returnType() {
3974
+ return this._def.returns;
3975
+ }
3976
+ args(...items) {
3977
+ return new ZodFunction({
3978
+ ...this._def,
3979
+ args: ZodTuple.create(items).rest(ZodUnknown.create()),
3980
+ });
3981
+ }
3982
+ returns(returnType) {
3983
+ return new ZodFunction({
3984
+ ...this._def,
3985
+ returns: returnType,
3986
+ });
3987
+ }
3988
+ implement(func) {
3989
+ const validatedFunc = this.parse(func);
3990
+ return validatedFunc;
3991
+ }
3992
+ strictImplement(func) {
3993
+ const validatedFunc = this.parse(func);
3994
+ return validatedFunc;
3995
+ }
3996
+ static create(args, returns, params) {
3997
+ return new ZodFunction({
3998
+ args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),
3999
+ returns: returns || ZodUnknown.create(),
4000
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
4001
+ ...processCreateParams(params),
4002
+ });
4003
+ }
4004
+ }
4005
+ class ZodLazy extends ZodType {
4006
+ get schema() {
4007
+ return this._def.getter();
4008
+ }
4009
+ _parse(input) {
4010
+ const { ctx } = this._processInputParams(input);
4011
+ const lazySchema = this._def.getter();
4012
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
4013
+ }
4014
+ }
4015
+ ZodLazy.create = (getter, params) => {
4016
+ return new ZodLazy({
4017
+ getter: getter,
4018
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
4019
+ ...processCreateParams(params),
4020
+ });
4021
+ };
4022
+ class ZodLiteral extends ZodType {
4023
+ _parse(input) {
4024
+ if (input.data !== this._def.value) {
4025
+ const ctx = this._getOrReturnCtx(input);
4026
+ addIssueToContext(ctx, {
4027
+ received: ctx.data,
4028
+ code: ZodIssueCode.invalid_literal,
4029
+ expected: this._def.value,
4030
+ });
4031
+ return INVALID;
4032
+ }
4033
+ return { status: "valid", value: input.data };
4034
+ }
4035
+ get value() {
4036
+ return this._def.value;
4037
+ }
4038
+ }
4039
+ ZodLiteral.create = (value, params) => {
4040
+ return new ZodLiteral({
4041
+ value: value,
4042
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
4043
+ ...processCreateParams(params),
4044
+ });
4045
+ };
4046
+ function createZodEnum(values, params) {
4047
+ return new ZodEnum({
4048
+ values,
4049
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
4050
+ ...processCreateParams(params),
4051
+ });
4052
+ }
4053
+ class ZodEnum extends ZodType {
4054
+ _parse(input) {
4055
+ if (typeof input.data !== "string") {
4056
+ const ctx = this._getOrReturnCtx(input);
4057
+ const expectedValues = this._def.values;
4058
+ addIssueToContext(ctx, {
4059
+ expected: util.joinValues(expectedValues),
4060
+ received: ctx.parsedType,
4061
+ code: ZodIssueCode.invalid_type,
4062
+ });
4063
+ return INVALID;
4064
+ }
4065
+ if (!this._cache) {
4066
+ this._cache = new Set(this._def.values);
4067
+ }
4068
+ if (!this._cache.has(input.data)) {
4069
+ const ctx = this._getOrReturnCtx(input);
4070
+ const expectedValues = this._def.values;
4071
+ addIssueToContext(ctx, {
4072
+ received: ctx.data,
4073
+ code: ZodIssueCode.invalid_enum_value,
4074
+ options: expectedValues,
4075
+ });
4076
+ return INVALID;
4077
+ }
4078
+ return OK(input.data);
4079
+ }
4080
+ get options() {
4081
+ return this._def.values;
4082
+ }
4083
+ get enum() {
4084
+ const enumValues = {};
4085
+ for (const val of this._def.values) {
4086
+ enumValues[val] = val;
4087
+ }
4088
+ return enumValues;
4089
+ }
4090
+ get Values() {
4091
+ const enumValues = {};
4092
+ for (const val of this._def.values) {
4093
+ enumValues[val] = val;
4094
+ }
4095
+ return enumValues;
4096
+ }
4097
+ get Enum() {
4098
+ const enumValues = {};
4099
+ for (const val of this._def.values) {
4100
+ enumValues[val] = val;
4101
+ }
4102
+ return enumValues;
4103
+ }
4104
+ extract(values, newDef = this._def) {
4105
+ return ZodEnum.create(values, {
4106
+ ...this._def,
4107
+ ...newDef,
4108
+ });
4109
+ }
4110
+ exclude(values, newDef = this._def) {
4111
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
4112
+ ...this._def,
4113
+ ...newDef,
4114
+ });
4115
+ }
4116
+ }
4117
+ ZodEnum.create = createZodEnum;
4118
+ class ZodNativeEnum extends ZodType {
4119
+ _parse(input) {
4120
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
4121
+ const ctx = this._getOrReturnCtx(input);
4122
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
4123
+ const expectedValues = util.objectValues(nativeEnumValues);
4124
+ addIssueToContext(ctx, {
4125
+ expected: util.joinValues(expectedValues),
4126
+ received: ctx.parsedType,
4127
+ code: ZodIssueCode.invalid_type,
4128
+ });
4129
+ return INVALID;
4130
+ }
4131
+ if (!this._cache) {
4132
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
4133
+ }
4134
+ if (!this._cache.has(input.data)) {
4135
+ const expectedValues = util.objectValues(nativeEnumValues);
4136
+ addIssueToContext(ctx, {
4137
+ received: ctx.data,
4138
+ code: ZodIssueCode.invalid_enum_value,
4139
+ options: expectedValues,
4140
+ });
4141
+ return INVALID;
4142
+ }
4143
+ return OK(input.data);
4144
+ }
4145
+ get enum() {
4146
+ return this._def.values;
4147
+ }
4148
+ }
4149
+ ZodNativeEnum.create = (values, params) => {
4150
+ return new ZodNativeEnum({
4151
+ values: values,
4152
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
4153
+ ...processCreateParams(params),
4154
+ });
4155
+ };
4156
+ class ZodPromise extends ZodType {
4157
+ unwrap() {
4158
+ return this._def.type;
4159
+ }
4160
+ _parse(input) {
4161
+ const { ctx } = this._processInputParams(input);
4162
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
4163
+ addIssueToContext(ctx, {
4164
+ code: ZodIssueCode.invalid_type,
4165
+ expected: ZodParsedType.promise,
4166
+ received: ctx.parsedType,
4167
+ });
4168
+ return INVALID;
4169
+ }
4170
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
4171
+ return OK(promisified.then((data) => {
4172
+ return this._def.type.parseAsync(data, {
4173
+ path: ctx.path,
4174
+ errorMap: ctx.common.contextualErrorMap,
4175
+ });
4176
+ }));
4177
+ }
4178
+ }
4179
+ ZodPromise.create = (schema, params) => {
4180
+ return new ZodPromise({
4181
+ type: schema,
4182
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
4183
+ ...processCreateParams(params),
4184
+ });
4185
+ };
4186
+ class ZodEffects extends ZodType {
4187
+ innerType() {
4188
+ return this._def.schema;
4189
+ }
4190
+ sourceType() {
4191
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
4192
+ ? this._def.schema.sourceType()
4193
+ : this._def.schema;
4194
+ }
4195
+ _parse(input) {
4196
+ const { status, ctx } = this._processInputParams(input);
4197
+ const effect = this._def.effect || null;
4198
+ const checkCtx = {
4199
+ addIssue: (arg) => {
4200
+ addIssueToContext(ctx, arg);
4201
+ if (arg.fatal) {
4202
+ status.abort();
4203
+ }
4204
+ else {
4205
+ status.dirty();
4206
+ }
4207
+ },
4208
+ get path() {
4209
+ return ctx.path;
4210
+ },
4211
+ };
4212
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
4213
+ if (effect.type === "preprocess") {
4214
+ const processed = effect.transform(ctx.data, checkCtx);
4215
+ if (ctx.common.async) {
4216
+ return Promise.resolve(processed).then(async (processed) => {
4217
+ if (status.value === "aborted")
4218
+ return INVALID;
4219
+ const result = await this._def.schema._parseAsync({
4220
+ data: processed,
4221
+ path: ctx.path,
4222
+ parent: ctx,
4223
+ });
4224
+ if (result.status === "aborted")
4225
+ return INVALID;
4226
+ if (result.status === "dirty")
4227
+ return DIRTY(result.value);
4228
+ if (status.value === "dirty")
4229
+ return DIRTY(result.value);
4230
+ return result;
4231
+ });
4232
+ }
4233
+ else {
4234
+ if (status.value === "aborted")
4235
+ return INVALID;
4236
+ const result = this._def.schema._parseSync({
4237
+ data: processed,
4238
+ path: ctx.path,
4239
+ parent: ctx,
4240
+ });
4241
+ if (result.status === "aborted")
4242
+ return INVALID;
4243
+ if (result.status === "dirty")
4244
+ return DIRTY(result.value);
4245
+ if (status.value === "dirty")
4246
+ return DIRTY(result.value);
4247
+ return result;
4248
+ }
4249
+ }
4250
+ if (effect.type === "refinement") {
4251
+ const executeRefinement = (acc) => {
4252
+ const result = effect.refinement(acc, checkCtx);
4253
+ if (ctx.common.async) {
4254
+ return Promise.resolve(result);
4255
+ }
4256
+ if (result instanceof Promise) {
4257
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
4258
+ }
4259
+ return acc;
4260
+ };
4261
+ if (ctx.common.async === false) {
4262
+ const inner = this._def.schema._parseSync({
4263
+ data: ctx.data,
4264
+ path: ctx.path,
4265
+ parent: ctx,
4266
+ });
4267
+ if (inner.status === "aborted")
4268
+ return INVALID;
4269
+ if (inner.status === "dirty")
4270
+ status.dirty();
4271
+ // return value is ignored
4272
+ executeRefinement(inner.value);
4273
+ return { status: status.value, value: inner.value };
4274
+ }
4275
+ else {
4276
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
4277
+ if (inner.status === "aborted")
4278
+ return INVALID;
4279
+ if (inner.status === "dirty")
4280
+ status.dirty();
4281
+ return executeRefinement(inner.value).then(() => {
4282
+ return { status: status.value, value: inner.value };
4283
+ });
4284
+ });
4285
+ }
4286
+ }
4287
+ if (effect.type === "transform") {
4288
+ if (ctx.common.async === false) {
4289
+ const base = this._def.schema._parseSync({
4290
+ data: ctx.data,
4291
+ path: ctx.path,
4292
+ parent: ctx,
4293
+ });
4294
+ if (!isValid(base))
4295
+ return INVALID;
4296
+ const result = effect.transform(base.value, checkCtx);
4297
+ if (result instanceof Promise) {
4298
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
4299
+ }
4300
+ return { status: status.value, value: result };
4301
+ }
4302
+ else {
4303
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
4304
+ if (!isValid(base))
4305
+ return INVALID;
4306
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
4307
+ status: status.value,
4308
+ value: result,
4309
+ }));
4310
+ });
4311
+ }
4312
+ }
4313
+ util.assertNever(effect);
4314
+ }
4315
+ }
4316
+ ZodEffects.create = (schema, effect, params) => {
4317
+ return new ZodEffects({
4318
+ schema,
4319
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4320
+ effect,
4321
+ ...processCreateParams(params),
4322
+ });
4323
+ };
4324
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
4325
+ return new ZodEffects({
4326
+ schema,
4327
+ effect: { type: "preprocess", transform: preprocess },
4328
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4329
+ ...processCreateParams(params),
4330
+ });
4331
+ };
4332
+ class ZodOptional extends ZodType {
4333
+ _parse(input) {
4334
+ const parsedType = this._getType(input);
4335
+ if (parsedType === ZodParsedType.undefined) {
4336
+ return OK(undefined);
4337
+ }
4338
+ return this._def.innerType._parse(input);
4339
+ }
4340
+ unwrap() {
4341
+ return this._def.innerType;
4342
+ }
4343
+ }
4344
+ ZodOptional.create = (type, params) => {
4345
+ return new ZodOptional({
4346
+ innerType: type,
4347
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
4348
+ ...processCreateParams(params),
4349
+ });
4350
+ };
4351
+ class ZodNullable extends ZodType {
4352
+ _parse(input) {
4353
+ const parsedType = this._getType(input);
4354
+ if (parsedType === ZodParsedType.null) {
4355
+ return OK(null);
4356
+ }
4357
+ return this._def.innerType._parse(input);
4358
+ }
4359
+ unwrap() {
4360
+ return this._def.innerType;
4361
+ }
4362
+ }
4363
+ ZodNullable.create = (type, params) => {
4364
+ return new ZodNullable({
4365
+ innerType: type,
4366
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
4367
+ ...processCreateParams(params),
4368
+ });
4369
+ };
4370
+ class ZodDefault extends ZodType {
4371
+ _parse(input) {
4372
+ const { ctx } = this._processInputParams(input);
4373
+ let data = ctx.data;
4374
+ if (ctx.parsedType === ZodParsedType.undefined) {
4375
+ data = this._def.defaultValue();
4376
+ }
4377
+ return this._def.innerType._parse({
4378
+ data,
4379
+ path: ctx.path,
4380
+ parent: ctx,
4381
+ });
4382
+ }
4383
+ removeDefault() {
4384
+ return this._def.innerType;
4385
+ }
4386
+ }
4387
+ ZodDefault.create = (type, params) => {
4388
+ return new ZodDefault({
4389
+ innerType: type,
4390
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
4391
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
4392
+ ...processCreateParams(params),
4393
+ });
4394
+ };
4395
+ class ZodCatch extends ZodType {
4396
+ _parse(input) {
4397
+ const { ctx } = this._processInputParams(input);
4398
+ // newCtx is used to not collect issues from inner types in ctx
4399
+ const newCtx = {
4400
+ ...ctx,
4401
+ common: {
4402
+ ...ctx.common,
4403
+ issues: [],
4404
+ },
4405
+ };
4406
+ const result = this._def.innerType._parse({
4407
+ data: newCtx.data,
4408
+ path: newCtx.path,
4409
+ parent: {
4410
+ ...newCtx,
4411
+ },
4412
+ });
4413
+ if (isAsync(result)) {
4414
+ return result.then((result) => {
4415
+ return {
4416
+ status: "valid",
4417
+ value: result.status === "valid"
4418
+ ? result.value
4419
+ : this._def.catchValue({
4420
+ get error() {
4421
+ return new ZodError(newCtx.common.issues);
4422
+ },
4423
+ input: newCtx.data,
4424
+ }),
4425
+ };
4426
+ });
4427
+ }
4428
+ else {
4429
+ return {
4430
+ status: "valid",
4431
+ value: result.status === "valid"
4432
+ ? result.value
4433
+ : this._def.catchValue({
4434
+ get error() {
4435
+ return new ZodError(newCtx.common.issues);
4436
+ },
4437
+ input: newCtx.data,
4438
+ }),
4439
+ };
4440
+ }
4441
+ }
4442
+ removeCatch() {
4443
+ return this._def.innerType;
4444
+ }
4445
+ }
4446
+ ZodCatch.create = (type, params) => {
4447
+ return new ZodCatch({
4448
+ innerType: type,
4449
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
4450
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
4451
+ ...processCreateParams(params),
4452
+ });
4453
+ };
4454
+ class ZodNaN extends ZodType {
4455
+ _parse(input) {
4456
+ const parsedType = this._getType(input);
4457
+ if (parsedType !== ZodParsedType.nan) {
4458
+ const ctx = this._getOrReturnCtx(input);
4459
+ addIssueToContext(ctx, {
4460
+ code: ZodIssueCode.invalid_type,
4461
+ expected: ZodParsedType.nan,
4462
+ received: ctx.parsedType,
4463
+ });
4464
+ return INVALID;
4465
+ }
4466
+ return { status: "valid", value: input.data };
4467
+ }
4468
+ }
4469
+ ZodNaN.create = (params) => {
4470
+ return new ZodNaN({
4471
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
4472
+ ...processCreateParams(params),
4473
+ });
4474
+ };
4475
+ const BRAND = Symbol("zod_brand");
4476
+ class ZodBranded extends ZodType {
4477
+ _parse(input) {
4478
+ const { ctx } = this._processInputParams(input);
4479
+ const data = ctx.data;
4480
+ return this._def.type._parse({
4481
+ data,
4482
+ path: ctx.path,
4483
+ parent: ctx,
4484
+ });
4485
+ }
4486
+ unwrap() {
4487
+ return this._def.type;
4488
+ }
4489
+ }
4490
+ class ZodPipeline extends ZodType {
4491
+ _parse(input) {
4492
+ const { status, ctx } = this._processInputParams(input);
4493
+ if (ctx.common.async) {
4494
+ const handleAsync = async () => {
4495
+ const inResult = await this._def.in._parseAsync({
4496
+ data: ctx.data,
4497
+ path: ctx.path,
4498
+ parent: ctx,
4499
+ });
4500
+ if (inResult.status === "aborted")
4501
+ return INVALID;
4502
+ if (inResult.status === "dirty") {
4503
+ status.dirty();
4504
+ return DIRTY(inResult.value);
4505
+ }
4506
+ else {
4507
+ return this._def.out._parseAsync({
4508
+ data: inResult.value,
4509
+ path: ctx.path,
4510
+ parent: ctx,
4511
+ });
4512
+ }
4513
+ };
4514
+ return handleAsync();
4515
+ }
4516
+ else {
4517
+ const inResult = this._def.in._parseSync({
4518
+ data: ctx.data,
4519
+ path: ctx.path,
4520
+ parent: ctx,
4521
+ });
4522
+ if (inResult.status === "aborted")
4523
+ return INVALID;
4524
+ if (inResult.status === "dirty") {
4525
+ status.dirty();
4526
+ return {
4527
+ status: "dirty",
4528
+ value: inResult.value,
4529
+ };
4530
+ }
4531
+ else {
4532
+ return this._def.out._parseSync({
4533
+ data: inResult.value,
4534
+ path: ctx.path,
4535
+ parent: ctx,
4536
+ });
4537
+ }
4538
+ }
4539
+ }
4540
+ static create(a, b) {
4541
+ return new ZodPipeline({
4542
+ in: a,
4543
+ out: b,
4544
+ typeName: ZodFirstPartyTypeKind.ZodPipeline,
4545
+ });
4546
+ }
4547
+ }
4548
+ class ZodReadonly extends ZodType {
4549
+ _parse(input) {
4550
+ const result = this._def.innerType._parse(input);
4551
+ const freeze = (data) => {
4552
+ if (isValid(data)) {
4553
+ data.value = Object.freeze(data.value);
4554
+ }
4555
+ return data;
4556
+ };
4557
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
4558
+ }
4559
+ unwrap() {
4560
+ return this._def.innerType;
4561
+ }
4562
+ }
4563
+ ZodReadonly.create = (type, params) => {
4564
+ return new ZodReadonly({
4565
+ innerType: type,
4566
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
4567
+ ...processCreateParams(params),
4568
+ });
4569
+ };
4570
+ ////////////////////////////////////////
4571
+ ////////////////////////////////////////
4572
+ ////////// //////////
4573
+ ////////// z.custom //////////
4574
+ ////////// //////////
4575
+ ////////////////////////////////////////
4576
+ ////////////////////////////////////////
4577
+ function cleanParams(params, data) {
4578
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
4579
+ const p2 = typeof p === "string" ? { message: p } : p;
4580
+ return p2;
4581
+ }
4582
+ function custom(check, _params = {},
4583
+ /**
4584
+ * @deprecated
4585
+ *
4586
+ * Pass `fatal` into the params object instead:
4587
+ *
4588
+ * ```ts
4589
+ * z.string().custom((val) => val.length > 5, { fatal: false })
4590
+ * ```
4591
+ *
4592
+ */
4593
+ fatal) {
4594
+ if (check)
4595
+ return ZodAny.create().superRefine((data, ctx) => {
4596
+ const r = check(data);
4597
+ if (r instanceof Promise) {
4598
+ return r.then((r) => {
4599
+ if (!r) {
4600
+ const params = cleanParams(_params, data);
4601
+ const _fatal = params.fatal ?? fatal ?? true;
4602
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4603
+ }
4604
+ });
4605
+ }
4606
+ if (!r) {
4607
+ const params = cleanParams(_params, data);
4608
+ const _fatal = params.fatal ?? fatal ?? true;
4609
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4610
+ }
4611
+ return;
4612
+ });
4613
+ return ZodAny.create();
4614
+ }
4615
+ const late = {
4616
+ object: ZodObject.lazycreate,
4617
+ };
4618
+ var ZodFirstPartyTypeKind;
4619
+ (function (ZodFirstPartyTypeKind) {
4620
+ ZodFirstPartyTypeKind["ZodString"] = "ZodString";
4621
+ ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
4622
+ ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
4623
+ ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
4624
+ ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
4625
+ ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
4626
+ ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
4627
+ ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
4628
+ ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
4629
+ ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
4630
+ ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
4631
+ ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
4632
+ ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
4633
+ ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
4634
+ ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
4635
+ ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
4636
+ ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4637
+ ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
4638
+ ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
4639
+ ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
4640
+ ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
4641
+ ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
4642
+ ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
4643
+ ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
4644
+ ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
4645
+ ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
4646
+ ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
4647
+ ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
4648
+ ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
4649
+ ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
4650
+ ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
4651
+ ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
4652
+ ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
4653
+ ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
4654
+ ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
4655
+ ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
4656
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4657
+ const instanceOfType = (
4658
+ // const instanceOfType = <T extends new (...args: any[]) => any>(
4659
+ cls, params = {
4660
+ message: `Input not instance of ${cls.name}`,
4661
+ }) => custom((data) => data instanceof cls, params);
4662
+ const stringType = ZodString.create;
4663
+ const numberType = ZodNumber.create;
4664
+ const nanType = ZodNaN.create;
4665
+ const bigIntType = ZodBigInt.create;
4666
+ const booleanType = ZodBoolean.create;
4667
+ const dateType = ZodDate.create;
4668
+ const symbolType = ZodSymbol.create;
4669
+ const undefinedType = ZodUndefined.create;
4670
+ const nullType = ZodNull.create;
4671
+ const anyType = ZodAny.create;
4672
+ const unknownType = ZodUnknown.create;
4673
+ const neverType = ZodNever.create;
4674
+ const voidType = ZodVoid.create;
4675
+ const arrayType = ZodArray.create;
4676
+ const objectType = ZodObject.create;
4677
+ const strictObjectType = ZodObject.strictCreate;
4678
+ const unionType = ZodUnion.create;
4679
+ const discriminatedUnionType = ZodDiscriminatedUnion.create;
4680
+ const intersectionType = ZodIntersection.create;
4681
+ const tupleType = ZodTuple.create;
4682
+ const recordType = ZodRecord.create;
4683
+ const mapType = ZodMap.create;
4684
+ const setType = ZodSet.create;
4685
+ const functionType = ZodFunction.create;
4686
+ const lazyType = ZodLazy.create;
4687
+ const literalType = ZodLiteral.create;
4688
+ const enumType = ZodEnum.create;
4689
+ const nativeEnumType = ZodNativeEnum.create;
4690
+ const promiseType = ZodPromise.create;
4691
+ const effectsType = ZodEffects.create;
4692
+ const optionalType = ZodOptional.create;
4693
+ const nullableType = ZodNullable.create;
4694
+ const preprocessType = ZodEffects.createWithPreprocess;
4695
+ const pipelineType = ZodPipeline.create;
4696
+ const ostring = () => stringType().optional();
4697
+ const onumber = () => numberType().optional();
4698
+ const oboolean = () => booleanType().optional();
4699
+ const coerce = {
4700
+ string: ((arg) => ZodString.create({ ...arg, coerce: true })),
4701
+ number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
4702
+ boolean: ((arg) => ZodBoolean.create({
4703
+ ...arg,
4704
+ coerce: true,
4705
+ })),
4706
+ bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
4707
+ date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
4708
+ };
4709
+ const NEVER = INVALID;
4710
+
4711
+ var z = /*#__PURE__*/Object.freeze({
4712
+ __proto__: null,
4713
+ BRAND: BRAND,
4714
+ DIRTY: DIRTY,
4715
+ EMPTY_PATH: EMPTY_PATH,
4716
+ INVALID: INVALID,
4717
+ NEVER: NEVER,
4718
+ OK: OK,
4719
+ ParseStatus: ParseStatus,
4720
+ Schema: ZodType,
4721
+ ZodAny: ZodAny,
4722
+ ZodArray: ZodArray,
4723
+ ZodBigInt: ZodBigInt,
4724
+ ZodBoolean: ZodBoolean,
4725
+ ZodBranded: ZodBranded,
4726
+ ZodCatch: ZodCatch,
4727
+ ZodDate: ZodDate,
4728
+ ZodDefault: ZodDefault,
4729
+ ZodDiscriminatedUnion: ZodDiscriminatedUnion,
4730
+ ZodEffects: ZodEffects,
4731
+ ZodEnum: ZodEnum,
4732
+ ZodError: ZodError,
4733
+ get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
4734
+ ZodFunction: ZodFunction,
4735
+ ZodIntersection: ZodIntersection,
4736
+ ZodIssueCode: ZodIssueCode,
4737
+ ZodLazy: ZodLazy,
4738
+ ZodLiteral: ZodLiteral,
4739
+ ZodMap: ZodMap,
4740
+ ZodNaN: ZodNaN,
4741
+ ZodNativeEnum: ZodNativeEnum,
4742
+ ZodNever: ZodNever,
4743
+ ZodNull: ZodNull,
4744
+ ZodNullable: ZodNullable,
4745
+ ZodNumber: ZodNumber,
4746
+ ZodObject: ZodObject,
4747
+ ZodOptional: ZodOptional,
4748
+ ZodParsedType: ZodParsedType,
4749
+ ZodPipeline: ZodPipeline,
4750
+ ZodPromise: ZodPromise,
4751
+ ZodReadonly: ZodReadonly,
4752
+ ZodRecord: ZodRecord,
4753
+ ZodSchema: ZodType,
4754
+ ZodSet: ZodSet,
4755
+ ZodString: ZodString,
4756
+ ZodSymbol: ZodSymbol,
4757
+ ZodTransformer: ZodEffects,
4758
+ ZodTuple: ZodTuple,
4759
+ ZodType: ZodType,
4760
+ ZodUndefined: ZodUndefined,
4761
+ ZodUnion: ZodUnion,
4762
+ ZodUnknown: ZodUnknown,
4763
+ ZodVoid: ZodVoid,
4764
+ addIssueToContext: addIssueToContext,
4765
+ any: anyType,
4766
+ array: arrayType,
4767
+ bigint: bigIntType,
4768
+ boolean: booleanType,
4769
+ coerce: coerce,
4770
+ custom: custom,
4771
+ date: dateType,
4772
+ datetimeRegex: datetimeRegex,
4773
+ defaultErrorMap: errorMap,
4774
+ discriminatedUnion: discriminatedUnionType,
4775
+ effect: effectsType,
4776
+ enum: enumType,
4777
+ function: functionType,
4778
+ getErrorMap: getErrorMap,
4779
+ getParsedType: getParsedType,
4780
+ instanceof: instanceOfType,
4781
+ intersection: intersectionType,
4782
+ isAborted: isAborted,
4783
+ isAsync: isAsync,
4784
+ isDirty: isDirty,
4785
+ isValid: isValid,
4786
+ late: late,
4787
+ lazy: lazyType,
4788
+ literal: literalType,
4789
+ makeIssue: makeIssue,
4790
+ map: mapType,
4791
+ nan: nanType,
4792
+ nativeEnum: nativeEnumType,
4793
+ never: neverType,
4794
+ null: nullType,
4795
+ nullable: nullableType,
4796
+ number: numberType,
4797
+ object: objectType,
4798
+ get objectUtil () { return objectUtil; },
4799
+ oboolean: oboolean,
4800
+ onumber: onumber,
4801
+ optional: optionalType,
4802
+ ostring: ostring,
4803
+ pipeline: pipelineType,
4804
+ preprocess: preprocessType,
4805
+ promise: promiseType,
4806
+ quotelessJson: quotelessJson,
4807
+ record: recordType,
4808
+ set: setType,
4809
+ setErrorMap: setErrorMap,
4810
+ strictObject: strictObjectType,
4811
+ string: stringType,
4812
+ symbol: symbolType,
4813
+ transformer: effectsType,
4814
+ tuple: tupleType,
4815
+ undefined: undefinedType,
4816
+ union: unionType,
4817
+ unknown: unknownType,
4818
+ get util () { return util; },
4819
+ void: voidType
4820
+ });
4821
+
4822
+ const ChainSchema = custom((chain) => chain != null &&
4823
+ typeof chain === "object" &&
4824
+ "id" in chain &&
4825
+ typeof chain.id === "number");
4826
+ const HexSchema = custom((val) => {
4827
+ return viem.isHex(val, { strict: true });
4828
+ });
4829
+ // [!region BigNumberish]
4830
+ const BigNumberishSchema = unionType([HexSchema, numberType(), bigIntType()]);
4831
+ // [!endregion BigNumberish]
4832
+ // [!region BigNumberishRange]
4833
+ const BigNumberishRangeSchema = objectType({
4834
+ min: BigNumberishSchema.optional(),
4835
+ max: BigNumberishSchema.optional(),
4836
+ })
4837
+ .strict();
4838
+ // [!endregion BigNumberishRange]
4839
+ // [!region Multiplier]
4840
+ const MultiplierSchema = objectType({
4841
+ /**
4842
+ * Multiplier value with max precision of 4 decimal places
4843
+ */
4844
+ multiplier: numberType().refine((n) => {
4845
+ return (n.toString().split(".")[1]?.length ?? 0) <= 4;
4846
+ }, { message: "Max precision is 4 decimal places" }),
4847
+ })
4848
+ .strict();
4849
+
4850
+ // [!region ConnectionConfigSchema]
4851
+ // TODO: in v5 either remove this or simplify it (either way this should be moved out of aa-sdk/core)
4852
+ const ConnectionConfigSchema = intersectionType(unionType([
4853
+ objectType({
4854
+ rpcUrl: neverType().optional(),
4855
+ apiKey: stringType(),
4856
+ jwt: neverType().optional(),
4857
+ }),
4858
+ objectType({
4859
+ rpcUrl: neverType().optional(),
4860
+ apiKey: neverType().optional(),
4861
+ jwt: stringType(),
4862
+ }),
4863
+ objectType({
4864
+ rpcUrl: stringType(),
4865
+ apiKey: neverType().optional(),
4866
+ jwt: neverType().optional(),
4867
+ }),
4868
+ objectType({
4869
+ rpcUrl: stringType(),
4870
+ apiKey: neverType().optional(),
4871
+ jwt: stringType(),
4872
+ }),
4873
+ ]), objectType({
4874
+ chainAgnosticUrl: stringType().optional(),
4875
+ }));
4876
+ // [!endregion ConnectionConfigSchema]
4877
+ const UserOperationFeeOptionsFieldSchema = BigNumberishRangeSchema.merge(MultiplierSchema).partial();
4878
+ const UserOperationFeeOptionsSchema_v6 = objectType({
4879
+ maxFeePerGas: UserOperationFeeOptionsFieldSchema,
4880
+ maxPriorityFeePerGas: UserOperationFeeOptionsFieldSchema,
4881
+ callGasLimit: UserOperationFeeOptionsFieldSchema,
4882
+ verificationGasLimit: UserOperationFeeOptionsFieldSchema,
4883
+ preVerificationGas: UserOperationFeeOptionsFieldSchema,
4884
+ })
4885
+ .partial()
4886
+ .strict();
4887
+ const UserOperationFeeOptionsSchema_v7 = UserOperationFeeOptionsSchema_v6.extend({
4888
+ paymasterVerificationGasLimit: UserOperationFeeOptionsFieldSchema,
4889
+ paymasterPostOpGasLimit: UserOperationFeeOptionsFieldSchema,
4890
+ })
4891
+ .partial()
4892
+ .strict();
4893
+ const UserOperationFeeOptionsSchema = UserOperationFeeOptionsSchema_v7;
4894
+ objectType({
4895
+ /**
4896
+ * The maximum number of times to try fetching a transaction receipt before giving up (default: 5)
4897
+ */
4898
+ txMaxRetries: numberType().min(0).optional().default(5),
4899
+ /**
4900
+ * The interval in milliseconds to wait between retries while waiting for tx receipts (default: 2_000)
4901
+ */
4902
+ txRetryIntervalMs: numberType().min(0).optional().default(2000),
4903
+ /**
4904
+ * The multiplier on interval length to wait between retries while waiting for tx receipts (default: 1.5)
4905
+ */
4906
+ txRetryMultiplier: numberType().min(0).optional().default(1.5),
4907
+ /**
4908
+ * Optional user operation fee options to be set globally at the provider level
4909
+ */
4910
+ feeOptions: UserOperationFeeOptionsSchema.optional(),
4911
+ })
4912
+ .strict();
4913
+
4914
+ /**
4915
+ * The Split Transport allows you to split RPC traffic for specific methods across
4916
+ * different RPC providers. This is done by specifying the methods you want handled
4917
+ * specially as overrides and providing a fallback transport for all other methods.
4918
+ *
4919
+ * @example
4920
+ * ```ts
4921
+ * import { createPublicClient, http } from "viem";
4922
+ * import { split } from "@aa-sdk/core";
4923
+ *
4924
+ * const bundlerMethods = [
4925
+ * "eth_sendUserOperation",
4926
+ * "eth_estimateUserOperationGas",
4927
+ * "eth_getUserOperationReceipt",
4928
+ * "eth_getUserOperationByHash",
4929
+ * "eth_supportedEntryPoints"
4930
+ * ];
4931
+ *
4932
+ * const clientWithSplit = createPublicClient({
4933
+ * transport: split({
4934
+ * overrides: [{
4935
+ * methods: bundlerMethods,
4936
+ * transport: http(BUNDLER_RPC_URL)
4937
+ * }],
4938
+ * fallback: http(OTHER_RPC_URL)
4939
+ * }),
4940
+ * });
4941
+ * ```
4942
+ *
4943
+ * @param {SplitTransportParams} params split transport configuration containing the methods overrides and fallback transport
4944
+ * @returns {CustomTransport} a viem Transport that splits traffic
4945
+ */
4946
+ const split = (params) => {
4947
+ const overrideMap = params.overrides.reduce((accum, curr) => {
4948
+ curr.methods.forEach((method) => {
4949
+ if (accum.has(method) && accum.get(method) !== curr.transport) {
4950
+ throw new Error("A method cannot be handled by more than one transport");
4951
+ }
4952
+ accum.set(method, curr.transport);
4953
+ });
4954
+ return accum;
4955
+ }, new Map());
4956
+ return (opts) => viem.custom({
4957
+ request: async (args) => {
4958
+ const transportOverride = overrideMap.get(args.method);
4959
+ if (transportOverride != null) {
4960
+ return transportOverride(opts).request(args);
4961
+ }
4962
+ return params.fallback(opts).request(args);
4963
+ },
4964
+ })(opts);
4965
+ };
4966
+
4967
+ function generateRandomHexString(numBytes) {
4968
+ const hexPairs = new Array(numBytes).fill(0).map(() => Math.floor(Math.random() * 16)
4969
+ .toString(16)
4970
+ .padStart(2, "0"));
4971
+ return hexPairs.join("");
4972
+ }
4973
+ /**
4974
+ * These are the headers that are used in the trace headers, could be found in the spec
4975
+ *
4976
+ * @see https://www.w3.org/TR/trace-context/#design-overview
4977
+ */
4978
+ const TRACE_HEADER_NAME = "traceparent";
4979
+ /**
4980
+ * These are the headers that are used in the trace headers, could be found in the spec
4981
+ *
4982
+ * @see https://www.w3.org/TR/trace-context/#design-overview
4983
+ */
4984
+ const TRACE_HEADER_STATE = "tracestate";
4985
+ generateRandomHexString(16);
4986
+
4987
+ /**
4988
+ * The header that is used to track the trace id.
4989
+ * We use a client specific one to not mess with the span tracing of the servers.
4990
+ *
4991
+ * @see headersUpdate
4992
+ */
4993
+ const TRACKER_HEADER = "X-Alchemy-Client-Trace-Id";
4994
+ /**
4995
+ * The header that is used to track the breadcrumb.
4996
+ *
4997
+ * @see headersUpdate
4998
+ */
4999
+ const TRACKER_BREADCRUMB = "X-Alchemy-Client-Breadcrumb";
5000
+ /**
5001
+ * Remove the tracking headers. This is used in our split transport to ensure that we remove the headers that
5002
+ * are not used by the other systems.
5003
+ *
5004
+ * @param {unknown} x The headers to remove the tracking headers from
5005
+ */
5006
+ function mutateRemoveTrackingHeaders(x) {
5007
+ if (!x)
5008
+ return;
5009
+ if (Array.isArray(x))
5010
+ return;
5011
+ if (typeof x !== "object")
5012
+ return;
5013
+ TRACKER_HEADER in x && delete x[TRACKER_HEADER];
5014
+ TRACKER_BREADCRUMB in x && delete x[TRACKER_BREADCRUMB];
5015
+ TRACE_HEADER_NAME in x && delete x[TRACE_HEADER_NAME];
5016
+ TRACE_HEADER_STATE in x && delete x[TRACE_HEADER_STATE];
5017
+ }
5018
+
5019
+ const AlchemyChainSchema = z.custom((chain) => {
5020
+ const chain_ = ChainSchema.parse(chain);
5021
+ return chain_.rpcUrls.alchemy != null;
5022
+ }, "chain must include an alchemy rpc url. See `defineAlchemyChain` or import a chain from `@account-kit/infra`.");
5023
+
5024
+ // This file is autogenerated by inject-version.ts. Any changes will be
5025
+ // overwritten on commit!
5026
+ const VERSION = "4.81.3";
5027
+
5028
+ const alchemyMethods = [
5029
+ "eth_sendUserOperation",
5030
+ "eth_estimateUserOperationGas",
5031
+ "eth_getUserOperationReceipt",
5032
+ "eth_getUserOperationByHash",
5033
+ "eth_supportedEntryPoints",
5034
+ "rundler_maxPriorityFeePerGas",
5035
+ "pm_getPaymasterData",
5036
+ "pm_getPaymasterStubData",
5037
+ "alchemy_requestGasAndPaymasterAndData",
5038
+ ];
5039
+ const chainAgnosticMethods = [
5040
+ "wallet_prepareCalls",
5041
+ "wallet_sendPreparedCalls",
5042
+ "wallet_requestAccount",
5043
+ "wallet_createAccount",
5044
+ "wallet_listAccounts",
5045
+ "wallet_createSession",
5046
+ "wallet_getCallsStatus",
5047
+ "wallet_requestQuote_v0",
5048
+ ];
5049
+ /**
5050
+ * Creates an Alchemy transport with the specified configuration options.
5051
+ * When sending all traffic to Alchemy, you must pass in one of rpcUrl, apiKey, or jwt.
5052
+ * If you want to send Bundler and Paymaster traffic to Alchemy and Node traffic to a different RPC, you must pass in alchemyConnection and nodeRpcUrl.
5053
+ *
5054
+ * @example
5055
+ * ### Basic Example
5056
+ * If the chain you're using is supported for both Bundler and Node RPCs, then you can do the following:
5057
+ * ```ts
5058
+ * import { alchemy } from "@account-kit/infra";
5059
+ *
5060
+ * const transport = alchemy({
5061
+ * // NOTE: you can also pass in an rpcUrl or jwt here or rpcUrl and jwt
5062
+ * apiKey: "your-api-key",
5063
+ * });
5064
+ * ```
5065
+ *
5066
+ * ### AA Only Chains
5067
+ * For AA-only chains, you need to specify the alchemyConnection and nodeRpcUrl since Alchemy only
5068
+ * handles the Bundler and Paymaster RPCs for these chains.
5069
+ * ```ts
5070
+ * import { alchemy } from "@account-kit/infra";
5071
+ *
5072
+ * const transport = alchemy({
5073
+ * alchemyConnection: {
5074
+ * apiKey: "your-api-key",
5075
+ * },
5076
+ * nodeRpcUrl: "https://zora.rpc.url",
5077
+ * });
5078
+ * ```
5079
+ *
5080
+ * @param {AlchemyTransportConfig} config The configuration object for the Alchemy transport.
5081
+ * @param {number} config.retryDelay Optional The delay between retries, in milliseconds.
5082
+ * @param {number} config.retryCount Optional The number of retry attempts.
5083
+ * @param {string} [config.alchemyConnection] Optional Alchemy connection configuration (if this is passed in, nodeRpcUrl is required).
5084
+ * @param {string} [config.fetchOptions] Optional fetch options for HTTP requests.
5085
+ * @param {string} [config.nodeRpcUrl] Optional RPC URL for node (if this is passed in, alchemyConnection is required).
5086
+ * @param {string} [config.rpcUrl] Optional RPC URL.
5087
+ * @param {string} [config.apiKey] Optional API key for Alchemy.
5088
+ * @param {string} [config.jwt] Optional JSON Web Token for authorization.
5089
+ * @returns {AlchemyTransport} The configured Alchemy transport object.
5090
+ */
5091
+ function alchemy(config) {
5092
+ const { retryDelay, retryCount = 0 } = config;
5093
+ // we create a copy here in case we create a split transport down below
5094
+ // we don't want to add alchemy headers to 3rd party nodes
5095
+ const fetchOptions = { ...config.fetchOptions };
5096
+ const connectionConfig = ConnectionConfigSchema.parse(config.alchemyConnection ?? config);
5097
+ const headersAsObject = convertHeadersToObject(fetchOptions.headers);
5098
+ // TODO: we probably should just log these headers during telemetry logging instead of doing this mutable header stuff
5099
+ fetchOptions.headers = {
5100
+ ...headersAsObject,
5101
+ "Alchemy-AA-Sdk-Version": VERSION,
5102
+ };
5103
+ if (connectionConfig.jwt != null || connectionConfig.apiKey != null) {
5104
+ fetchOptions.headers = {
5105
+ ...fetchOptions.headers,
5106
+ Authorization: `Bearer ${connectionConfig.jwt ?? connectionConfig.apiKey}`,
5107
+ };
5108
+ }
5109
+ const transport = (opts) => {
5110
+ const { chain: chain_ } = opts;
5111
+ if (!chain_) {
5112
+ throw new ChainNotFoundError();
5113
+ }
5114
+ const chain = AlchemyChainSchema.parse(chain_);
5115
+ const rpcUrl = connectionConfig.rpcUrl == null
5116
+ ? chain.rpcUrls.alchemy.http[0]
5117
+ : connectionConfig.rpcUrl;
5118
+ const chainAgnosticRpcUrl = connectionConfig.rpcUrl == null
5119
+ ? "https://api.g.alchemy.com/v2"
5120
+ : (connectionConfig.chainAgnosticUrl ?? connectionConfig.rpcUrl);
5121
+ const innerTransport = (() => {
5122
+ mutateRemoveTrackingHeaders(config?.fetchOptions?.headers);
5123
+ if (config.alchemyConnection && config.nodeRpcUrl) {
5124
+ return split({
5125
+ overrides: [
5126
+ {
5127
+ methods: alchemyMethods,
5128
+ transport: viem.http(rpcUrl, { fetchOptions, retryCount }),
5129
+ },
5130
+ {
5131
+ methods: chainAgnosticMethods,
5132
+ transport: viem.http(chainAgnosticRpcUrl, {
5133
+ fetchOptions,
5134
+ retryCount,
5135
+ retryDelay,
5136
+ }),
5137
+ },
5138
+ ],
5139
+ fallback: viem.http(config.nodeRpcUrl, {
5140
+ fetchOptions: config.fetchOptions,
5141
+ retryCount,
5142
+ retryDelay,
5143
+ }),
5144
+ });
5145
+ }
5146
+ return split({
5147
+ overrides: [
5148
+ {
5149
+ methods: chainAgnosticMethods,
5150
+ transport: viem.http(chainAgnosticRpcUrl, {
5151
+ fetchOptions,
5152
+ retryCount,
5153
+ retryDelay,
5154
+ }),
5155
+ },
5156
+ ],
5157
+ fallback: viem.http(rpcUrl, { fetchOptions, retryCount, retryDelay }),
5158
+ });
5159
+ })();
5160
+ return viem.createTransport({
5161
+ key: "alchemy",
5162
+ name: "Alchemy Transport",
5163
+ request: innerTransport({
5164
+ ...opts,
5165
+ // Retries are already handled above within the split transport,
5166
+ // so `retryCount` must be 0 here for the expected behavior.
5167
+ retryCount: 0,
5168
+ }).request,
5169
+ // Retries are already handled above within the split transport,
5170
+ // so `retryCount` must be 0 here too for the expected behavior.
5171
+ retryCount: 0,
5172
+ retryDelay,
5173
+ type: "alchemy",
5174
+ }, { alchemyRpcUrl: rpcUrl, fetchOptions });
5175
+ };
5176
+ return Object.assign(transport, {
5177
+ dynamicFetchOptions: fetchOptions,
5178
+ updateHeaders(newHeaders_) {
5179
+ const newHeaders = convertHeadersToObject(newHeaders_);
5180
+ fetchOptions.headers = {
5181
+ ...fetchOptions.headers,
5182
+ ...newHeaders,
5183
+ };
5184
+ },
5185
+ config,
5186
+ });
5187
+ }
5188
+ const convertHeadersToObject = (headers) => {
5189
+ if (!headers) {
5190
+ return {};
5191
+ }
5192
+ if (headers instanceof Headers) {
5193
+ const headersObject = {};
5194
+ headers.forEach((value, key) => {
5195
+ headersObject[key] = value;
5196
+ });
5197
+ return headersObject;
5198
+ }
5199
+ if (Array.isArray(headers)) {
5200
+ return headers.reduce((acc, header) => {
5201
+ acc[header[0]] = header[1];
5202
+ return acc;
5203
+ }, {});
5204
+ }
5205
+ return headers;
5206
+ };
5207
+
473
5208
  // Coinbase CDP API Key
474
5209
  const COINBASE_API_KEY = 'snPdXqIzOGhRkGNJvEHM5bl9Hm3yRO3m';
475
5210
  /**
@@ -498,6 +5233,13 @@ function getCoinbasePaymasterUrl(chainId) {
498
5233
  throw new Error(`Unsupported chain ID for Coinbase paymaster: ${chainId}`);
499
5234
  }
500
5235
  }
5236
+ /**
5237
+ * Check if Alchemy is configured via environment variables.
5238
+ * Both ALCHEMY_API_KEY and ALCHEMY_GAS_POLICY_ID must be set.
5239
+ */
5240
+ function isAlchemyConfigured() {
5241
+ return !!(process.env.ALCHEMY_API_KEY && process.env.ALCHEMY_GAS_POLICY_ID);
5242
+ }
501
5243
  /**
502
5244
  * Get Base chain configuration by chain ID
503
5245
  */
@@ -512,11 +5254,52 @@ function getBaseChain(chainId) {
512
5254
  }
513
5255
  }
514
5256
  /**
515
- * Creates an ephemeral smart wallet with paymaster support
5257
+ * Creates an ephemeral smart wallet with paymaster support using Alchemy infrastructure.
5258
+ * Uses the official @account-kit/infra transport for proper Alchemy integration.
516
5259
  * @param privateKey - Private key for the wallet signer
517
5260
  * @param chainId - Chain ID (defaults to 8453 for Base mainnet, can be 84532 for Base Sepolia)
518
5261
  */
519
- async function toEphemeralSmartWallet(privateKey, chainId = chains.base.id) {
5262
+ async function toEphemeralSmartWalletAlchemy(privateKey, chainId = chains.base.id) {
5263
+ const alchemyApiKey = process.env.ALCHEMY_API_KEY;
5264
+ const alchemyPolicyId = process.env.ALCHEMY_GAS_POLICY_ID;
5265
+ const signer = accounts.privateKeyToAccount(privateKey);
5266
+ const chain = getBaseChain(chainId);
5267
+ // Use the official Alchemy transport from @account-kit/infra
5268
+ const alchemyTransport = alchemy({ apiKey: alchemyApiKey });
5269
+ const publicClient = viem.createPublicClient({
5270
+ chain,
5271
+ transport: alchemyTransport
5272
+ });
5273
+ // Create the Coinbase smart wallet (works with any ERC-4337 bundler)
5274
+ const account = await accountAbstraction.toCoinbaseSmartAccount({
5275
+ client: publicClient,
5276
+ owners: [signer],
5277
+ version: '1'
5278
+ });
5279
+ // Create bundler client with Alchemy paymaster support
5280
+ const bundlerClient = accountAbstraction.createBundlerClient({
5281
+ account,
5282
+ client: publicClient,
5283
+ transport: alchemyTransport,
5284
+ chain,
5285
+ paymaster: true,
5286
+ paymasterContext: {
5287
+ policyId: alchemyPolicyId
5288
+ }
5289
+ });
5290
+ return {
5291
+ address: account.address,
5292
+ client: bundlerClient,
5293
+ account,
5294
+ signer,
5295
+ };
5296
+ }
5297
+ /**
5298
+ * Creates an ephemeral smart wallet with paymaster support using Coinbase infrastructure.
5299
+ * @param privateKey - Private key for the wallet signer
5300
+ * @param chainId - Chain ID (defaults to 8453 for Base mainnet, can be 84532 for Base Sepolia)
5301
+ */
5302
+ async function toEphemeralSmartWalletCoinbase(privateKey, chainId = chains.base.id) {
520
5303
  const apiKey = COINBASE_API_KEY;
521
5304
  const signer = accounts.privateKeyToAccount(privateKey);
522
5305
  const chain = getBaseChain(chainId);
@@ -538,7 +5321,7 @@ async function toEphemeralSmartWallet(privateKey, chainId = chains.base.id) {
538
5321
  client: publicClient,
539
5322
  transport: viem.http(`${bundlerUrl}/${apiKey}`),
540
5323
  chain,
541
- paymaster: true, // Enable paymaster sponsorship
5324
+ paymaster: true,
542
5325
  paymasterContext: {
543
5326
  transport: viem.http(`${paymasterUrl}/${apiKey}`)
544
5327
  }
@@ -550,6 +5333,21 @@ async function toEphemeralSmartWallet(privateKey, chainId = chains.base.id) {
550
5333
  signer,
551
5334
  };
552
5335
  }
5336
+ /**
5337
+ * Creates an ephemeral smart wallet with paymaster support.
5338
+ *
5339
+ * Uses Alchemy infrastructure if ALCHEMY_API_KEY and ALCHEMY_GAS_POLICY_ID
5340
+ * environment variables are set, otherwise falls back to Coinbase.
5341
+ *
5342
+ * @param privateKey - Private key for the wallet signer
5343
+ * @param chainId - Chain ID (defaults to 8453 for Base mainnet, can be 84532 for Base Sepolia)
5344
+ */
5345
+ async function toEphemeralSmartWallet(privateKey, chainId = chains.base.id) {
5346
+ if (isAlchemyConfigured()) {
5347
+ return toEphemeralSmartWalletAlchemy(privateKey, chainId);
5348
+ }
5349
+ return toEphemeralSmartWalletCoinbase(privateKey, chainId);
5350
+ }
553
5351
 
554
5352
  const DEFAULT_ALLOWANCE = 10n;
555
5353
  const DEFAULT_PERIOD_IN_DAYS = 7;
@@ -797,7 +5595,7 @@ class BasePaymentMaker {
797
5595
  const currency = dest.currency;
798
5596
  const receiver = dest.address;
799
5597
  if (currency.toUpperCase() !== 'USDC') {
800
- throw new client.PaymentNetworkError('Only USDC currency is supported; received ' + currency);
5598
+ throw new client.UnsupportedCurrencyError(currency, 'base', ['USDC']);
801
5599
  }
802
5600
  this.logger.info(`Making payment of ${amount} ${currency} to ${receiver} on Base from ${this.signingClient.account.address}`);
803
5601
  try {
@@ -835,7 +5633,9 @@ class BasePaymentMaker {
835
5633
  confirmations: 1
836
5634
  });
837
5635
  if (receipt.status === 'reverted') {
838
- throw new client.PaymentNetworkError(`Transaction reverted: ${hash}`, new Error('Transaction reverted on chain'));
5636
+ // Try to extract revert reason if available
5637
+ // Note: viem doesn't provide revert reason in receipt, would need additional call
5638
+ throw new client.TransactionRevertedError(hash, 'base');
839
5639
  }
840
5640
  this.logger.info(`Transaction confirmed: ${hash} in block ${receipt.blockNumber}`);
841
5641
  // Return payment result with chain and currency
@@ -846,11 +5646,36 @@ class BasePaymentMaker {
846
5646
  };
847
5647
  }
848
5648
  catch (error) {
849
- if (error instanceof client.InsufficientFundsError || error instanceof client.PaymentNetworkError) {
5649
+ // Re-throw our custom payment errors
5650
+ if (error instanceof client.ATXPPaymentError) {
850
5651
  throw error;
851
5652
  }
852
- // Wrap other errors in PaymentNetworkError
853
- throw new client.PaymentNetworkError(`Payment failed on Base network: ${error.message}`, error);
5653
+ // Categorize viem/blockchain errors
5654
+ const errorMessage = error.message || '';
5655
+ const errorName = error.name || '';
5656
+ // User rejected in wallet
5657
+ if (errorMessage.includes('User rejected') ||
5658
+ errorMessage.includes('user rejected') ||
5659
+ errorMessage.includes('User denied') ||
5660
+ errorName === 'UserRejectedRequestError') {
5661
+ throw new client.UserRejectedError('base');
5662
+ }
5663
+ // Gas estimation failed
5664
+ if (errorMessage.includes('gas') &&
5665
+ (errorMessage.includes('estimation') || errorMessage.includes('estimate'))) {
5666
+ throw new client.GasEstimationError('base', errorMessage);
5667
+ }
5668
+ // RPC/network errors
5669
+ if (errorMessage.includes('fetch failed') ||
5670
+ errorMessage.includes('network') ||
5671
+ errorMessage.includes('timeout') ||
5672
+ errorMessage.includes('ECONNREFUSED') ||
5673
+ errorMessage.includes('ETIMEDOUT') ||
5674
+ errorName === 'FetchError') {
5675
+ throw new client.RpcError('base', undefined, error);
5676
+ }
5677
+ // Fallback to generic network error with original error attached
5678
+ throw new client.PaymentNetworkError('base', errorMessage || 'Unknown error', error);
854
5679
  }
855
5680
  }
856
5681
  }