@atxp/base 0.9.0 → 0.9.1

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