ayush-opencode 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,15 @@
1
1
  // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true,
8
+ configurable: true,
9
+ set: (newValue) => all[name] = () => newValue
10
+ });
11
+ };
12
+
2
13
  // src/agents/explorer.ts
3
14
  var EXPLORER_PROMPT = `You are a codebase search specialist. Your job: find files and code, return actionable results.
4
15
 
@@ -529,74 +540,4183 @@ var ORCHESTRATION_PROMPT = `
529
540
 
530
541
  ---
531
542
 
532
- ## Sub-Agent Orchestration
543
+ ## Sub-Agent Delegation
544
+
545
+ You have specialized subagents. Use the **Task tool** to delegate work proactively.
533
546
 
534
- You have specialized agents available. **Proactively delegate** to maximize efficiency.
547
+ ### Available Agents
535
548
 
536
- ### Trigger Patterns (Fire Immediately)
549
+ | Agent | Use For | subagent_type |
550
+ |-------|---------|---------------|
551
+ | **Explorer** | Codebase search, "Where is X?", file discovery, pattern matching | \`explorer\` |
552
+ | **Librarian** | External docs, library research, OSS examples, GitHub permalinks | \`librarian\` |
553
+ | **Oracle** | Architecture decisions, debugging strategy, trade-offs, code review | \`oracle\` |
554
+ | **UI Planner** | Visual design, CSS, animations, UI/UX, beautiful interfaces | \`ui-planner\` |
537
555
 
538
- | When You See... | Fire Agent | Why |
539
- |-----------------|------------|-----|
540
- | "Where is X?", "Find Y", locate code | \`@explorer\` | Codebase search specialist |
541
- | External library, unfamiliar API, "how does X work?" | \`@librarian\` | Searches docs, GitHub, OSS examples |
542
- | 2+ modules involved, cross-cutting concerns | \`@explorer\` | Multi-file pattern discovery |
543
- | Architecture decision, trade-offs, "should I use X or Y?" | \`@oracle\` | Deep reasoning advisor |
544
- | Visual/styling work, UI/UX, CSS, animations | \`@ui-planner\` | Designer-developer hybrid |
545
- | After 2+ failed fix attempts | \`@oracle\` | Debugging escalation |
556
+ ### When to Delegate (Fire Immediately)
546
557
 
547
- ### Parallel Execution (Default Behavior)
558
+ | Trigger | subagent_type | Why |
559
+ |---------|---------------|-----|
560
+ | "Where is X?", "Find Y", locate code | \`explorer\` | Fast codebase search |
561
+ | External library, "how does X library work?" | \`librarian\` | Searches docs, GitHub, OSS |
562
+ | 2+ modules involved, cross-cutting concerns | \`explorer\` | Multi-file pattern discovery |
563
+ | Architecture decision, "should I use X or Y?" | \`oracle\` | Deep reasoning advisor |
564
+ | Visual/styling, CSS, animations, UI/UX | \`ui-planner\` | Designer-developer hybrid |
565
+ | After 2+ failed fix attempts | \`oracle\` | Debugging escalation |
548
566
 
549
- Fire multiple agents simultaneously for broad tasks. Don't wait sequentially.
567
+ ### How to Delegate
550
568
 
569
+ Use the Task tool with these parameters:
570
+
571
+ \`\`\`
572
+ Task(
573
+ subagent_type: "explorer" | "librarian" | "oracle" | "ui-planner",
574
+ description: "Short 3-5 word task description",
575
+ prompt: "Detailed instructions for the agent"
576
+ )
577
+ \`\`\`
578
+
579
+ **Example delegations:**
580
+
581
+ \`\`\`
582
+ // Find code in codebase
583
+ Task(
584
+ subagent_type: "explorer",
585
+ description: "Find auth middleware",
586
+ prompt: "Find all authentication middleware implementations in this codebase. Return file paths and explain the auth flow."
587
+ )
588
+
589
+ // Research external library
590
+ Task(
591
+ subagent_type: "librarian",
592
+ description: "React Query caching docs",
593
+ prompt: "How does React Query handle caching? Find official documentation and real-world examples with GitHub permalinks."
594
+ )
595
+
596
+ // Architecture decision
597
+ Task(
598
+ subagent_type: "oracle",
599
+ description: "Redux vs Zustand analysis",
600
+ prompt: "Analyze trade-offs between Redux and Zustand for this project. Consider bundle size, learning curve, and our existing patterns."
601
+ )
602
+
603
+ // UI/Visual work
604
+ Task(
605
+ subagent_type: "ui-planner",
606
+ description: "Redesign dashboard cards",
607
+ prompt: "Redesign the dashboard stat cards to be more visually appealing. Use modern aesthetics, subtle animations, and ensure responsive design."
608
+ )
551
609
  \`\`\`
552
- // CORRECT: Parallel background execution
553
- @explorer \u2192 "Find auth implementations in codebase"
554
- @librarian \u2192 "Find JWT best practices in official docs"
555
- // Continue working immediately while they search
556
610
 
557
- // WRONG: Sequential blocking
558
- Wait for @explorer... then @librarian... (wastes time)
611
+ ### Parallel Execution
612
+
613
+ To run multiple agents in parallel, call multiple Task tools in the **same response message**:
614
+
615
+ \`\`\`
616
+ // CORRECT: Multiple Task calls in ONE message = parallel execution
617
+ Task(subagent_type: "explorer", description: "Find auth code", prompt: "...")
618
+ Task(subagent_type: "librarian", description: "JWT best practices", prompt: "...")
619
+ // Both run simultaneously
620
+
621
+ // WRONG: One Task per message = sequential (slow)
622
+ Message 1: Task(...) \u2192 wait for result
623
+ Message 2: Task(...) \u2192 wait for result
559
624
  \`\`\`
560
625
 
561
626
  ### Delegation Priority
562
627
 
563
- 1. **@explorer FIRST** \u2014 Always locate code before modifying unfamiliar areas
564
- 2. **@librarian** \u2014 When dealing with external libraries, APIs, or frameworks you don't fully understand
565
- 3. **@oracle** \u2014 For complex decisions, code review, or after repeated failures
566
- 4. **@ui-planner** \u2014 For ANY visual/styling work (never touch CSS/UI yourself)
628
+ 1. **Explorer FIRST** \u2014 Always locate code before modifying unfamiliar areas
629
+ 2. **Librarian** \u2014 When dealing with external libraries/APIs you don't fully understand
630
+ 3. **Oracle** \u2014 For complex decisions or after 2+ failed fix attempts
631
+ 4. **UI Planner** \u2014 For ANY visual/styling work (never edit CSS/UI yourself)
567
632
 
568
- ### Agent Capabilities
633
+ ### Critical Rules
569
634
 
570
- | Agent | Strength | Cost |
571
- |-------|----------|------|
572
- | \`@explorer\` | Fast codebase grep, file discovery, pattern matching | Cheap |
573
- | \`@librarian\` | External docs, GitHub search, OSS examples, permalinks | Cheap |
574
- | \`@oracle\` | Architecture, debugging, trade-offs, code review | Expensive |
575
- | \`@ui-planner\` | Visual design, animations, beautiful interfaces | Medium |
635
+ 1. **Never touch frontend visual/styling code yourself** \u2014 Always delegate to \`ui-planner\`
636
+ 2. **Fire librarian proactively** when unfamiliar libraries are involved
637
+ 3. **Consult oracle BEFORE major architectural decisions**, not after
638
+ 4. **Verify delegated work** before marking task complete
576
639
 
577
- ### When to Handle Directly
640
+ ### When to Handle Directly (Don't Delegate)
578
641
 
579
642
  - Single file edits with known location
580
643
  - Questions answerable from code already in context
581
644
  - Trivial changes requiring no specialist knowledge
645
+ - Tasks you can complete faster than explaining to an agent
646
+ `;
582
647
 
583
- ### Critical Rules
648
+ // node_modules/zod/v3/external.js
649
+ var exports_external = {};
650
+ __export(exports_external, {
651
+ void: () => voidType,
652
+ util: () => util,
653
+ unknown: () => unknownType,
654
+ union: () => unionType,
655
+ undefined: () => undefinedType,
656
+ tuple: () => tupleType,
657
+ transformer: () => effectsType,
658
+ symbol: () => symbolType,
659
+ string: () => stringType,
660
+ strictObject: () => strictObjectType,
661
+ setErrorMap: () => setErrorMap,
662
+ set: () => setType,
663
+ record: () => recordType,
664
+ quotelessJson: () => quotelessJson,
665
+ promise: () => promiseType,
666
+ preprocess: () => preprocessType,
667
+ pipeline: () => pipelineType,
668
+ ostring: () => ostring,
669
+ optional: () => optionalType,
670
+ onumber: () => onumber,
671
+ oboolean: () => oboolean,
672
+ objectUtil: () => objectUtil,
673
+ object: () => objectType,
674
+ number: () => numberType,
675
+ nullable: () => nullableType,
676
+ null: () => nullType,
677
+ never: () => neverType,
678
+ nativeEnum: () => nativeEnumType,
679
+ nan: () => nanType,
680
+ map: () => mapType,
681
+ makeIssue: () => makeIssue,
682
+ literal: () => literalType,
683
+ lazy: () => lazyType,
684
+ late: () => late,
685
+ isValid: () => isValid,
686
+ isDirty: () => isDirty,
687
+ isAsync: () => isAsync,
688
+ isAborted: () => isAborted,
689
+ intersection: () => intersectionType,
690
+ instanceof: () => instanceOfType,
691
+ getParsedType: () => getParsedType,
692
+ getErrorMap: () => getErrorMap,
693
+ function: () => functionType,
694
+ enum: () => enumType,
695
+ effect: () => effectsType,
696
+ discriminatedUnion: () => discriminatedUnionType,
697
+ defaultErrorMap: () => en_default,
698
+ datetimeRegex: () => datetimeRegex,
699
+ date: () => dateType,
700
+ custom: () => custom,
701
+ coerce: () => coerce,
702
+ boolean: () => booleanType,
703
+ bigint: () => bigIntType,
704
+ array: () => arrayType,
705
+ any: () => anyType,
706
+ addIssueToContext: () => addIssueToContext,
707
+ ZodVoid: () => ZodVoid,
708
+ ZodUnknown: () => ZodUnknown,
709
+ ZodUnion: () => ZodUnion,
710
+ ZodUndefined: () => ZodUndefined,
711
+ ZodType: () => ZodType,
712
+ ZodTuple: () => ZodTuple,
713
+ ZodTransformer: () => ZodEffects,
714
+ ZodSymbol: () => ZodSymbol,
715
+ ZodString: () => ZodString,
716
+ ZodSet: () => ZodSet,
717
+ ZodSchema: () => ZodType,
718
+ ZodRecord: () => ZodRecord,
719
+ ZodReadonly: () => ZodReadonly,
720
+ ZodPromise: () => ZodPromise,
721
+ ZodPipeline: () => ZodPipeline,
722
+ ZodParsedType: () => ZodParsedType,
723
+ ZodOptional: () => ZodOptional,
724
+ ZodObject: () => ZodObject,
725
+ ZodNumber: () => ZodNumber,
726
+ ZodNullable: () => ZodNullable,
727
+ ZodNull: () => ZodNull,
728
+ ZodNever: () => ZodNever,
729
+ ZodNativeEnum: () => ZodNativeEnum,
730
+ ZodNaN: () => ZodNaN,
731
+ ZodMap: () => ZodMap,
732
+ ZodLiteral: () => ZodLiteral,
733
+ ZodLazy: () => ZodLazy,
734
+ ZodIssueCode: () => ZodIssueCode,
735
+ ZodIntersection: () => ZodIntersection,
736
+ ZodFunction: () => ZodFunction,
737
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
738
+ ZodError: () => ZodError,
739
+ ZodEnum: () => ZodEnum,
740
+ ZodEffects: () => ZodEffects,
741
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
742
+ ZodDefault: () => ZodDefault,
743
+ ZodDate: () => ZodDate,
744
+ ZodCatch: () => ZodCatch,
745
+ ZodBranded: () => ZodBranded,
746
+ ZodBoolean: () => ZodBoolean,
747
+ ZodBigInt: () => ZodBigInt,
748
+ ZodArray: () => ZodArray,
749
+ ZodAny: () => ZodAny,
750
+ Schema: () => ZodType,
751
+ ParseStatus: () => ParseStatus,
752
+ OK: () => OK,
753
+ NEVER: () => NEVER,
754
+ INVALID: () => INVALID,
755
+ EMPTY_PATH: () => EMPTY_PATH,
756
+ DIRTY: () => DIRTY,
757
+ BRAND: () => BRAND
758
+ });
759
+
760
+ // node_modules/zod/v3/helpers/util.js
761
+ var util;
762
+ (function(util2) {
763
+ util2.assertEqual = (_) => {};
764
+ function assertIs(_arg) {}
765
+ util2.assertIs = assertIs;
766
+ function assertNever(_x) {
767
+ throw new Error;
768
+ }
769
+ util2.assertNever = assertNever;
770
+ util2.arrayToEnum = (items) => {
771
+ const obj = {};
772
+ for (const item of items) {
773
+ obj[item] = item;
774
+ }
775
+ return obj;
776
+ };
777
+ util2.getValidEnumValues = (obj) => {
778
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
779
+ const filtered = {};
780
+ for (const k of validKeys) {
781
+ filtered[k] = obj[k];
782
+ }
783
+ return util2.objectValues(filtered);
784
+ };
785
+ util2.objectValues = (obj) => {
786
+ return util2.objectKeys(obj).map(function(e) {
787
+ return obj[e];
788
+ });
789
+ };
790
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
791
+ const keys = [];
792
+ for (const key in object) {
793
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
794
+ keys.push(key);
795
+ }
796
+ }
797
+ return keys;
798
+ };
799
+ util2.find = (arr, checker) => {
800
+ for (const item of arr) {
801
+ if (checker(item))
802
+ return item;
803
+ }
804
+ return;
805
+ };
806
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
807
+ function joinValues(array, separator = " | ") {
808
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
809
+ }
810
+ util2.joinValues = joinValues;
811
+ util2.jsonStringifyReplacer = (_, value) => {
812
+ if (typeof value === "bigint") {
813
+ return value.toString();
814
+ }
815
+ return value;
816
+ };
817
+ })(util || (util = {}));
818
+ var objectUtil;
819
+ (function(objectUtil2) {
820
+ objectUtil2.mergeShapes = (first, second) => {
821
+ return {
822
+ ...first,
823
+ ...second
824
+ };
825
+ };
826
+ })(objectUtil || (objectUtil = {}));
827
+ var ZodParsedType = util.arrayToEnum([
828
+ "string",
829
+ "nan",
830
+ "number",
831
+ "integer",
832
+ "float",
833
+ "boolean",
834
+ "date",
835
+ "bigint",
836
+ "symbol",
837
+ "function",
838
+ "undefined",
839
+ "null",
840
+ "array",
841
+ "object",
842
+ "unknown",
843
+ "promise",
844
+ "void",
845
+ "never",
846
+ "map",
847
+ "set"
848
+ ]);
849
+ var getParsedType = (data) => {
850
+ const t = typeof data;
851
+ switch (t) {
852
+ case "undefined":
853
+ return ZodParsedType.undefined;
854
+ case "string":
855
+ return ZodParsedType.string;
856
+ case "number":
857
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
858
+ case "boolean":
859
+ return ZodParsedType.boolean;
860
+ case "function":
861
+ return ZodParsedType.function;
862
+ case "bigint":
863
+ return ZodParsedType.bigint;
864
+ case "symbol":
865
+ return ZodParsedType.symbol;
866
+ case "object":
867
+ if (Array.isArray(data)) {
868
+ return ZodParsedType.array;
869
+ }
870
+ if (data === null) {
871
+ return ZodParsedType.null;
872
+ }
873
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
874
+ return ZodParsedType.promise;
875
+ }
876
+ if (typeof Map !== "undefined" && data instanceof Map) {
877
+ return ZodParsedType.map;
878
+ }
879
+ if (typeof Set !== "undefined" && data instanceof Set) {
880
+ return ZodParsedType.set;
881
+ }
882
+ if (typeof Date !== "undefined" && data instanceof Date) {
883
+ return ZodParsedType.date;
884
+ }
885
+ return ZodParsedType.object;
886
+ default:
887
+ return ZodParsedType.unknown;
888
+ }
889
+ };
584
890
 
585
- 1. **Never touch frontend visual/styling code yourself** \u2014 Always delegate to \`@ui-planner\`
586
- 2. **Fire @librarian proactively** when unfamiliar libraries are involved
587
- 3. **Consult @oracle before major architectural decisions**, not after
588
- 4. **Verify delegated work** before marking complete
589
- `;
891
+ // node_modules/zod/v3/ZodError.js
892
+ var ZodIssueCode = util.arrayToEnum([
893
+ "invalid_type",
894
+ "invalid_literal",
895
+ "custom",
896
+ "invalid_union",
897
+ "invalid_union_discriminator",
898
+ "invalid_enum_value",
899
+ "unrecognized_keys",
900
+ "invalid_arguments",
901
+ "invalid_return_type",
902
+ "invalid_date",
903
+ "invalid_string",
904
+ "too_small",
905
+ "too_big",
906
+ "invalid_intersection_types",
907
+ "not_multiple_of",
908
+ "not_finite"
909
+ ]);
910
+ var quotelessJson = (obj) => {
911
+ const json = JSON.stringify(obj, null, 2);
912
+ return json.replace(/"([^"]+)":/g, "$1:");
913
+ };
914
+
915
+ class ZodError extends Error {
916
+ get errors() {
917
+ return this.issues;
918
+ }
919
+ constructor(issues) {
920
+ super();
921
+ this.issues = [];
922
+ this.addIssue = (sub) => {
923
+ this.issues = [...this.issues, sub];
924
+ };
925
+ this.addIssues = (subs = []) => {
926
+ this.issues = [...this.issues, ...subs];
927
+ };
928
+ const actualProto = new.target.prototype;
929
+ if (Object.setPrototypeOf) {
930
+ Object.setPrototypeOf(this, actualProto);
931
+ } else {
932
+ this.__proto__ = actualProto;
933
+ }
934
+ this.name = "ZodError";
935
+ this.issues = issues;
936
+ }
937
+ format(_mapper) {
938
+ const mapper = _mapper || function(issue) {
939
+ return issue.message;
940
+ };
941
+ const fieldErrors = { _errors: [] };
942
+ const processError = (error) => {
943
+ for (const issue of error.issues) {
944
+ if (issue.code === "invalid_union") {
945
+ issue.unionErrors.map(processError);
946
+ } else if (issue.code === "invalid_return_type") {
947
+ processError(issue.returnTypeError);
948
+ } else if (issue.code === "invalid_arguments") {
949
+ processError(issue.argumentsError);
950
+ } else if (issue.path.length === 0) {
951
+ fieldErrors._errors.push(mapper(issue));
952
+ } else {
953
+ let curr = fieldErrors;
954
+ let i = 0;
955
+ while (i < issue.path.length) {
956
+ const el = issue.path[i];
957
+ const terminal = i === issue.path.length - 1;
958
+ if (!terminal) {
959
+ curr[el] = curr[el] || { _errors: [] };
960
+ } else {
961
+ curr[el] = curr[el] || { _errors: [] };
962
+ curr[el]._errors.push(mapper(issue));
963
+ }
964
+ curr = curr[el];
965
+ i++;
966
+ }
967
+ }
968
+ }
969
+ };
970
+ processError(this);
971
+ return fieldErrors;
972
+ }
973
+ static assert(value) {
974
+ if (!(value instanceof ZodError)) {
975
+ throw new Error(`Not a ZodError: ${value}`);
976
+ }
977
+ }
978
+ toString() {
979
+ return this.message;
980
+ }
981
+ get message() {
982
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
983
+ }
984
+ get isEmpty() {
985
+ return this.issues.length === 0;
986
+ }
987
+ flatten(mapper = (issue) => issue.message) {
988
+ const fieldErrors = {};
989
+ const formErrors = [];
990
+ for (const sub of this.issues) {
991
+ if (sub.path.length > 0) {
992
+ const firstEl = sub.path[0];
993
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
994
+ fieldErrors[firstEl].push(mapper(sub));
995
+ } else {
996
+ formErrors.push(mapper(sub));
997
+ }
998
+ }
999
+ return { formErrors, fieldErrors };
1000
+ }
1001
+ get formErrors() {
1002
+ return this.flatten();
1003
+ }
1004
+ }
1005
+ ZodError.create = (issues) => {
1006
+ const error = new ZodError(issues);
1007
+ return error;
1008
+ };
1009
+
1010
+ // node_modules/zod/v3/locales/en.js
1011
+ var errorMap = (issue, _ctx) => {
1012
+ let message;
1013
+ switch (issue.code) {
1014
+ case ZodIssueCode.invalid_type:
1015
+ if (issue.received === ZodParsedType.undefined) {
1016
+ message = "Required";
1017
+ } else {
1018
+ message = `Expected ${issue.expected}, received ${issue.received}`;
1019
+ }
1020
+ break;
1021
+ case ZodIssueCode.invalid_literal:
1022
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
1023
+ break;
1024
+ case ZodIssueCode.unrecognized_keys:
1025
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
1026
+ break;
1027
+ case ZodIssueCode.invalid_union:
1028
+ message = `Invalid input`;
1029
+ break;
1030
+ case ZodIssueCode.invalid_union_discriminator:
1031
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
1032
+ break;
1033
+ case ZodIssueCode.invalid_enum_value:
1034
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
1035
+ break;
1036
+ case ZodIssueCode.invalid_arguments:
1037
+ message = `Invalid function arguments`;
1038
+ break;
1039
+ case ZodIssueCode.invalid_return_type:
1040
+ message = `Invalid function return type`;
1041
+ break;
1042
+ case ZodIssueCode.invalid_date:
1043
+ message = `Invalid date`;
1044
+ break;
1045
+ case ZodIssueCode.invalid_string:
1046
+ if (typeof issue.validation === "object") {
1047
+ if ("includes" in issue.validation) {
1048
+ message = `Invalid input: must include "${issue.validation.includes}"`;
1049
+ if (typeof issue.validation.position === "number") {
1050
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
1051
+ }
1052
+ } else if ("startsWith" in issue.validation) {
1053
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
1054
+ } else if ("endsWith" in issue.validation) {
1055
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
1056
+ } else {
1057
+ util.assertNever(issue.validation);
1058
+ }
1059
+ } else if (issue.validation !== "regex") {
1060
+ message = `Invalid ${issue.validation}`;
1061
+ } else {
1062
+ message = "Invalid";
1063
+ }
1064
+ break;
1065
+ case ZodIssueCode.too_small:
1066
+ if (issue.type === "array")
1067
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
1068
+ else if (issue.type === "string")
1069
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
1070
+ else if (issue.type === "number")
1071
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1072
+ else if (issue.type === "bigint")
1073
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
1074
+ else if (issue.type === "date")
1075
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
1076
+ else
1077
+ message = "Invalid input";
1078
+ break;
1079
+ case ZodIssueCode.too_big:
1080
+ if (issue.type === "array")
1081
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
1082
+ else if (issue.type === "string")
1083
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
1084
+ else if (issue.type === "number")
1085
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1086
+ else if (issue.type === "bigint")
1087
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
1088
+ else if (issue.type === "date")
1089
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
1090
+ else
1091
+ message = "Invalid input";
1092
+ break;
1093
+ case ZodIssueCode.custom:
1094
+ message = `Invalid input`;
1095
+ break;
1096
+ case ZodIssueCode.invalid_intersection_types:
1097
+ message = `Intersection results could not be merged`;
1098
+ break;
1099
+ case ZodIssueCode.not_multiple_of:
1100
+ message = `Number must be a multiple of ${issue.multipleOf}`;
1101
+ break;
1102
+ case ZodIssueCode.not_finite:
1103
+ message = "Number must be finite";
1104
+ break;
1105
+ default:
1106
+ message = _ctx.defaultError;
1107
+ util.assertNever(issue);
1108
+ }
1109
+ return { message };
1110
+ };
1111
+ var en_default = errorMap;
1112
+
1113
+ // node_modules/zod/v3/errors.js
1114
+ var overrideErrorMap = en_default;
1115
+ function setErrorMap(map) {
1116
+ overrideErrorMap = map;
1117
+ }
1118
+ function getErrorMap() {
1119
+ return overrideErrorMap;
1120
+ }
1121
+ // node_modules/zod/v3/helpers/parseUtil.js
1122
+ var makeIssue = (params) => {
1123
+ const { data, path, errorMaps, issueData } = params;
1124
+ const fullPath = [...path, ...issueData.path || []];
1125
+ const fullIssue = {
1126
+ ...issueData,
1127
+ path: fullPath
1128
+ };
1129
+ if (issueData.message !== undefined) {
1130
+ return {
1131
+ ...issueData,
1132
+ path: fullPath,
1133
+ message: issueData.message
1134
+ };
1135
+ }
1136
+ let errorMessage = "";
1137
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
1138
+ for (const map of maps) {
1139
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
1140
+ }
1141
+ return {
1142
+ ...issueData,
1143
+ path: fullPath,
1144
+ message: errorMessage
1145
+ };
1146
+ };
1147
+ var EMPTY_PATH = [];
1148
+ function addIssueToContext(ctx, issueData) {
1149
+ const overrideMap = getErrorMap();
1150
+ const issue = makeIssue({
1151
+ issueData,
1152
+ data: ctx.data,
1153
+ path: ctx.path,
1154
+ errorMaps: [
1155
+ ctx.common.contextualErrorMap,
1156
+ ctx.schemaErrorMap,
1157
+ overrideMap,
1158
+ overrideMap === en_default ? undefined : en_default
1159
+ ].filter((x) => !!x)
1160
+ });
1161
+ ctx.common.issues.push(issue);
1162
+ }
1163
+
1164
+ class ParseStatus {
1165
+ constructor() {
1166
+ this.value = "valid";
1167
+ }
1168
+ dirty() {
1169
+ if (this.value === "valid")
1170
+ this.value = "dirty";
1171
+ }
1172
+ abort() {
1173
+ if (this.value !== "aborted")
1174
+ this.value = "aborted";
1175
+ }
1176
+ static mergeArray(status, results) {
1177
+ const arrayValue = [];
1178
+ for (const s of results) {
1179
+ if (s.status === "aborted")
1180
+ return INVALID;
1181
+ if (s.status === "dirty")
1182
+ status.dirty();
1183
+ arrayValue.push(s.value);
1184
+ }
1185
+ return { status: status.value, value: arrayValue };
1186
+ }
1187
+ static async mergeObjectAsync(status, pairs) {
1188
+ const syncPairs = [];
1189
+ for (const pair of pairs) {
1190
+ const key = await pair.key;
1191
+ const value = await pair.value;
1192
+ syncPairs.push({
1193
+ key,
1194
+ value
1195
+ });
1196
+ }
1197
+ return ParseStatus.mergeObjectSync(status, syncPairs);
1198
+ }
1199
+ static mergeObjectSync(status, pairs) {
1200
+ const finalObject = {};
1201
+ for (const pair of pairs) {
1202
+ const { key, value } = pair;
1203
+ if (key.status === "aborted")
1204
+ return INVALID;
1205
+ if (value.status === "aborted")
1206
+ return INVALID;
1207
+ if (key.status === "dirty")
1208
+ status.dirty();
1209
+ if (value.status === "dirty")
1210
+ status.dirty();
1211
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
1212
+ finalObject[key.value] = value.value;
1213
+ }
1214
+ }
1215
+ return { status: status.value, value: finalObject };
1216
+ }
1217
+ }
1218
+ var INVALID = Object.freeze({
1219
+ status: "aborted"
1220
+ });
1221
+ var DIRTY = (value) => ({ status: "dirty", value });
1222
+ var OK = (value) => ({ status: "valid", value });
1223
+ var isAborted = (x) => x.status === "aborted";
1224
+ var isDirty = (x) => x.status === "dirty";
1225
+ var isValid = (x) => x.status === "valid";
1226
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
1227
+ // node_modules/zod/v3/helpers/errorUtil.js
1228
+ var errorUtil;
1229
+ (function(errorUtil2) {
1230
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
1231
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
1232
+ })(errorUtil || (errorUtil = {}));
1233
+
1234
+ // node_modules/zod/v3/types.js
1235
+ class ParseInputLazyPath {
1236
+ constructor(parent, value, path, key) {
1237
+ this._cachedPath = [];
1238
+ this.parent = parent;
1239
+ this.data = value;
1240
+ this._path = path;
1241
+ this._key = key;
1242
+ }
1243
+ get path() {
1244
+ if (!this._cachedPath.length) {
1245
+ if (Array.isArray(this._key)) {
1246
+ this._cachedPath.push(...this._path, ...this._key);
1247
+ } else {
1248
+ this._cachedPath.push(...this._path, this._key);
1249
+ }
1250
+ }
1251
+ return this._cachedPath;
1252
+ }
1253
+ }
1254
+ var handleResult = (ctx, result) => {
1255
+ if (isValid(result)) {
1256
+ return { success: true, data: result.value };
1257
+ } else {
1258
+ if (!ctx.common.issues.length) {
1259
+ throw new Error("Validation failed but no issues detected.");
1260
+ }
1261
+ return {
1262
+ success: false,
1263
+ get error() {
1264
+ if (this._error)
1265
+ return this._error;
1266
+ const error = new ZodError(ctx.common.issues);
1267
+ this._error = error;
1268
+ return this._error;
1269
+ }
1270
+ };
1271
+ }
1272
+ };
1273
+ function processCreateParams(params) {
1274
+ if (!params)
1275
+ return {};
1276
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
1277
+ if (errorMap2 && (invalid_type_error || required_error)) {
1278
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
1279
+ }
1280
+ if (errorMap2)
1281
+ return { errorMap: errorMap2, description };
1282
+ const customMap = (iss, ctx) => {
1283
+ const { message } = params;
1284
+ if (iss.code === "invalid_enum_value") {
1285
+ return { message: message ?? ctx.defaultError };
1286
+ }
1287
+ if (typeof ctx.data === "undefined") {
1288
+ return { message: message ?? required_error ?? ctx.defaultError };
1289
+ }
1290
+ if (iss.code !== "invalid_type")
1291
+ return { message: ctx.defaultError };
1292
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
1293
+ };
1294
+ return { errorMap: customMap, description };
1295
+ }
1296
+
1297
+ class ZodType {
1298
+ get description() {
1299
+ return this._def.description;
1300
+ }
1301
+ _getType(input) {
1302
+ return getParsedType(input.data);
1303
+ }
1304
+ _getOrReturnCtx(input, ctx) {
1305
+ return ctx || {
1306
+ common: input.parent.common,
1307
+ data: input.data,
1308
+ parsedType: getParsedType(input.data),
1309
+ schemaErrorMap: this._def.errorMap,
1310
+ path: input.path,
1311
+ parent: input.parent
1312
+ };
1313
+ }
1314
+ _processInputParams(input) {
1315
+ return {
1316
+ status: new ParseStatus,
1317
+ ctx: {
1318
+ common: input.parent.common,
1319
+ data: input.data,
1320
+ parsedType: getParsedType(input.data),
1321
+ schemaErrorMap: this._def.errorMap,
1322
+ path: input.path,
1323
+ parent: input.parent
1324
+ }
1325
+ };
1326
+ }
1327
+ _parseSync(input) {
1328
+ const result = this._parse(input);
1329
+ if (isAsync(result)) {
1330
+ throw new Error("Synchronous parse encountered promise.");
1331
+ }
1332
+ return result;
1333
+ }
1334
+ _parseAsync(input) {
1335
+ const result = this._parse(input);
1336
+ return Promise.resolve(result);
1337
+ }
1338
+ parse(data, params) {
1339
+ const result = this.safeParse(data, params);
1340
+ if (result.success)
1341
+ return result.data;
1342
+ throw result.error;
1343
+ }
1344
+ safeParse(data, params) {
1345
+ const ctx = {
1346
+ common: {
1347
+ issues: [],
1348
+ async: params?.async ?? false,
1349
+ contextualErrorMap: params?.errorMap
1350
+ },
1351
+ path: params?.path || [],
1352
+ schemaErrorMap: this._def.errorMap,
1353
+ parent: null,
1354
+ data,
1355
+ parsedType: getParsedType(data)
1356
+ };
1357
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1358
+ return handleResult(ctx, result);
1359
+ }
1360
+ "~validate"(data) {
1361
+ const ctx = {
1362
+ common: {
1363
+ issues: [],
1364
+ async: !!this["~standard"].async
1365
+ },
1366
+ path: [],
1367
+ schemaErrorMap: this._def.errorMap,
1368
+ parent: null,
1369
+ data,
1370
+ parsedType: getParsedType(data)
1371
+ };
1372
+ if (!this["~standard"].async) {
1373
+ try {
1374
+ const result = this._parseSync({ data, path: [], parent: ctx });
1375
+ return isValid(result) ? {
1376
+ value: result.value
1377
+ } : {
1378
+ issues: ctx.common.issues
1379
+ };
1380
+ } catch (err) {
1381
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
1382
+ this["~standard"].async = true;
1383
+ }
1384
+ ctx.common = {
1385
+ issues: [],
1386
+ async: true
1387
+ };
1388
+ }
1389
+ }
1390
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
1391
+ value: result.value
1392
+ } : {
1393
+ issues: ctx.common.issues
1394
+ });
1395
+ }
1396
+ async parseAsync(data, params) {
1397
+ const result = await this.safeParseAsync(data, params);
1398
+ if (result.success)
1399
+ return result.data;
1400
+ throw result.error;
1401
+ }
1402
+ async safeParseAsync(data, params) {
1403
+ const ctx = {
1404
+ common: {
1405
+ issues: [],
1406
+ contextualErrorMap: params?.errorMap,
1407
+ async: true
1408
+ },
1409
+ path: params?.path || [],
1410
+ schemaErrorMap: this._def.errorMap,
1411
+ parent: null,
1412
+ data,
1413
+ parsedType: getParsedType(data)
1414
+ };
1415
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1416
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1417
+ return handleResult(ctx, result);
1418
+ }
1419
+ refine(check, message) {
1420
+ const getIssueProperties = (val) => {
1421
+ if (typeof message === "string" || typeof message === "undefined") {
1422
+ return { message };
1423
+ } else if (typeof message === "function") {
1424
+ return message(val);
1425
+ } else {
1426
+ return message;
1427
+ }
1428
+ };
1429
+ return this._refinement((val, ctx) => {
1430
+ const result = check(val);
1431
+ const setError = () => ctx.addIssue({
1432
+ code: ZodIssueCode.custom,
1433
+ ...getIssueProperties(val)
1434
+ });
1435
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
1436
+ return result.then((data) => {
1437
+ if (!data) {
1438
+ setError();
1439
+ return false;
1440
+ } else {
1441
+ return true;
1442
+ }
1443
+ });
1444
+ }
1445
+ if (!result) {
1446
+ setError();
1447
+ return false;
1448
+ } else {
1449
+ return true;
1450
+ }
1451
+ });
1452
+ }
1453
+ refinement(check, refinementData) {
1454
+ return this._refinement((val, ctx) => {
1455
+ if (!check(val)) {
1456
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
1457
+ return false;
1458
+ } else {
1459
+ return true;
1460
+ }
1461
+ });
1462
+ }
1463
+ _refinement(refinement) {
1464
+ return new ZodEffects({
1465
+ schema: this,
1466
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1467
+ effect: { type: "refinement", refinement }
1468
+ });
1469
+ }
1470
+ superRefine(refinement) {
1471
+ return this._refinement(refinement);
1472
+ }
1473
+ constructor(def) {
1474
+ this.spa = this.safeParseAsync;
1475
+ this._def = def;
1476
+ this.parse = this.parse.bind(this);
1477
+ this.safeParse = this.safeParse.bind(this);
1478
+ this.parseAsync = this.parseAsync.bind(this);
1479
+ this.safeParseAsync = this.safeParseAsync.bind(this);
1480
+ this.spa = this.spa.bind(this);
1481
+ this.refine = this.refine.bind(this);
1482
+ this.refinement = this.refinement.bind(this);
1483
+ this.superRefine = this.superRefine.bind(this);
1484
+ this.optional = this.optional.bind(this);
1485
+ this.nullable = this.nullable.bind(this);
1486
+ this.nullish = this.nullish.bind(this);
1487
+ this.array = this.array.bind(this);
1488
+ this.promise = this.promise.bind(this);
1489
+ this.or = this.or.bind(this);
1490
+ this.and = this.and.bind(this);
1491
+ this.transform = this.transform.bind(this);
1492
+ this.brand = this.brand.bind(this);
1493
+ this.default = this.default.bind(this);
1494
+ this.catch = this.catch.bind(this);
1495
+ this.describe = this.describe.bind(this);
1496
+ this.pipe = this.pipe.bind(this);
1497
+ this.readonly = this.readonly.bind(this);
1498
+ this.isNullable = this.isNullable.bind(this);
1499
+ this.isOptional = this.isOptional.bind(this);
1500
+ this["~standard"] = {
1501
+ version: 1,
1502
+ vendor: "zod",
1503
+ validate: (data) => this["~validate"](data)
1504
+ };
1505
+ }
1506
+ optional() {
1507
+ return ZodOptional.create(this, this._def);
1508
+ }
1509
+ nullable() {
1510
+ return ZodNullable.create(this, this._def);
1511
+ }
1512
+ nullish() {
1513
+ return this.nullable().optional();
1514
+ }
1515
+ array() {
1516
+ return ZodArray.create(this);
1517
+ }
1518
+ promise() {
1519
+ return ZodPromise.create(this, this._def);
1520
+ }
1521
+ or(option) {
1522
+ return ZodUnion.create([this, option], this._def);
1523
+ }
1524
+ and(incoming) {
1525
+ return ZodIntersection.create(this, incoming, this._def);
1526
+ }
1527
+ transform(transform) {
1528
+ return new ZodEffects({
1529
+ ...processCreateParams(this._def),
1530
+ schema: this,
1531
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
1532
+ effect: { type: "transform", transform }
1533
+ });
1534
+ }
1535
+ default(def) {
1536
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
1537
+ return new ZodDefault({
1538
+ ...processCreateParams(this._def),
1539
+ innerType: this,
1540
+ defaultValue: defaultValueFunc,
1541
+ typeName: ZodFirstPartyTypeKind.ZodDefault
1542
+ });
1543
+ }
1544
+ brand() {
1545
+ return new ZodBranded({
1546
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
1547
+ type: this,
1548
+ ...processCreateParams(this._def)
1549
+ });
1550
+ }
1551
+ catch(def) {
1552
+ const catchValueFunc = typeof def === "function" ? def : () => def;
1553
+ return new ZodCatch({
1554
+ ...processCreateParams(this._def),
1555
+ innerType: this,
1556
+ catchValue: catchValueFunc,
1557
+ typeName: ZodFirstPartyTypeKind.ZodCatch
1558
+ });
1559
+ }
1560
+ describe(description) {
1561
+ const This = this.constructor;
1562
+ return new This({
1563
+ ...this._def,
1564
+ description
1565
+ });
1566
+ }
1567
+ pipe(target) {
1568
+ return ZodPipeline.create(this, target);
1569
+ }
1570
+ readonly() {
1571
+ return ZodReadonly.create(this);
1572
+ }
1573
+ isOptional() {
1574
+ return this.safeParse(undefined).success;
1575
+ }
1576
+ isNullable() {
1577
+ return this.safeParse(null).success;
1578
+ }
1579
+ }
1580
+ var cuidRegex = /^c[^\s-]{8,}$/i;
1581
+ var cuid2Regex = /^[0-9a-z]+$/;
1582
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
1583
+ var 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;
1584
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
1585
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
1586
+ var 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)?)??$/;
1587
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1588
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1589
+ var emojiRegex;
1590
+ var 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])$/;
1591
+ var 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])$/;
1592
+ var 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]))$/;
1593
+ var 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])$/;
1594
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1595
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
1596
+ var 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])))`;
1597
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
1598
+ function timeRegexSource(args) {
1599
+ let secondsRegexSource = `[0-5]\\d`;
1600
+ if (args.precision) {
1601
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
1602
+ } else if (args.precision == null) {
1603
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
1604
+ }
1605
+ const secondsQuantifier = args.precision ? "+" : "?";
1606
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
1607
+ }
1608
+ function timeRegex(args) {
1609
+ return new RegExp(`^${timeRegexSource(args)}$`);
1610
+ }
1611
+ function datetimeRegex(args) {
1612
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1613
+ const opts = [];
1614
+ opts.push(args.local ? `Z?` : `Z`);
1615
+ if (args.offset)
1616
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1617
+ regex = `${regex}(${opts.join("|")})`;
1618
+ return new RegExp(`^${regex}$`);
1619
+ }
1620
+ function isValidIP(ip, version) {
1621
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1622
+ return true;
1623
+ }
1624
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1625
+ return true;
1626
+ }
1627
+ return false;
1628
+ }
1629
+ function isValidJWT(jwt, alg) {
1630
+ if (!jwtRegex.test(jwt))
1631
+ return false;
1632
+ try {
1633
+ const [header] = jwt.split(".");
1634
+ if (!header)
1635
+ return false;
1636
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
1637
+ const decoded = JSON.parse(atob(base64));
1638
+ if (typeof decoded !== "object" || decoded === null)
1639
+ return false;
1640
+ if ("typ" in decoded && decoded?.typ !== "JWT")
1641
+ return false;
1642
+ if (!decoded.alg)
1643
+ return false;
1644
+ if (alg && decoded.alg !== alg)
1645
+ return false;
1646
+ return true;
1647
+ } catch {
1648
+ return false;
1649
+ }
1650
+ }
1651
+ function isValidCidr(ip, version) {
1652
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
1653
+ return true;
1654
+ }
1655
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
1656
+ return true;
1657
+ }
1658
+ return false;
1659
+ }
1660
+
1661
+ class ZodString extends ZodType {
1662
+ _parse(input) {
1663
+ if (this._def.coerce) {
1664
+ input.data = String(input.data);
1665
+ }
1666
+ const parsedType = this._getType(input);
1667
+ if (parsedType !== ZodParsedType.string) {
1668
+ const ctx2 = this._getOrReturnCtx(input);
1669
+ addIssueToContext(ctx2, {
1670
+ code: ZodIssueCode.invalid_type,
1671
+ expected: ZodParsedType.string,
1672
+ received: ctx2.parsedType
1673
+ });
1674
+ return INVALID;
1675
+ }
1676
+ const status = new ParseStatus;
1677
+ let ctx = undefined;
1678
+ for (const check of this._def.checks) {
1679
+ if (check.kind === "min") {
1680
+ if (input.data.length < check.value) {
1681
+ ctx = this._getOrReturnCtx(input, ctx);
1682
+ addIssueToContext(ctx, {
1683
+ code: ZodIssueCode.too_small,
1684
+ minimum: check.value,
1685
+ type: "string",
1686
+ inclusive: true,
1687
+ exact: false,
1688
+ message: check.message
1689
+ });
1690
+ status.dirty();
1691
+ }
1692
+ } else if (check.kind === "max") {
1693
+ if (input.data.length > check.value) {
1694
+ ctx = this._getOrReturnCtx(input, ctx);
1695
+ addIssueToContext(ctx, {
1696
+ code: ZodIssueCode.too_big,
1697
+ maximum: check.value,
1698
+ type: "string",
1699
+ inclusive: true,
1700
+ exact: false,
1701
+ message: check.message
1702
+ });
1703
+ status.dirty();
1704
+ }
1705
+ } else if (check.kind === "length") {
1706
+ const tooBig = input.data.length > check.value;
1707
+ const tooSmall = input.data.length < check.value;
1708
+ if (tooBig || tooSmall) {
1709
+ ctx = this._getOrReturnCtx(input, ctx);
1710
+ if (tooBig) {
1711
+ addIssueToContext(ctx, {
1712
+ code: ZodIssueCode.too_big,
1713
+ maximum: check.value,
1714
+ type: "string",
1715
+ inclusive: true,
1716
+ exact: true,
1717
+ message: check.message
1718
+ });
1719
+ } else if (tooSmall) {
1720
+ addIssueToContext(ctx, {
1721
+ code: ZodIssueCode.too_small,
1722
+ minimum: check.value,
1723
+ type: "string",
1724
+ inclusive: true,
1725
+ exact: true,
1726
+ message: check.message
1727
+ });
1728
+ }
1729
+ status.dirty();
1730
+ }
1731
+ } else if (check.kind === "email") {
1732
+ if (!emailRegex.test(input.data)) {
1733
+ ctx = this._getOrReturnCtx(input, ctx);
1734
+ addIssueToContext(ctx, {
1735
+ validation: "email",
1736
+ code: ZodIssueCode.invalid_string,
1737
+ message: check.message
1738
+ });
1739
+ status.dirty();
1740
+ }
1741
+ } else if (check.kind === "emoji") {
1742
+ if (!emojiRegex) {
1743
+ emojiRegex = new RegExp(_emojiRegex, "u");
1744
+ }
1745
+ if (!emojiRegex.test(input.data)) {
1746
+ ctx = this._getOrReturnCtx(input, ctx);
1747
+ addIssueToContext(ctx, {
1748
+ validation: "emoji",
1749
+ code: ZodIssueCode.invalid_string,
1750
+ message: check.message
1751
+ });
1752
+ status.dirty();
1753
+ }
1754
+ } else if (check.kind === "uuid") {
1755
+ if (!uuidRegex.test(input.data)) {
1756
+ ctx = this._getOrReturnCtx(input, ctx);
1757
+ addIssueToContext(ctx, {
1758
+ validation: "uuid",
1759
+ code: ZodIssueCode.invalid_string,
1760
+ message: check.message
1761
+ });
1762
+ status.dirty();
1763
+ }
1764
+ } else if (check.kind === "nanoid") {
1765
+ if (!nanoidRegex.test(input.data)) {
1766
+ ctx = this._getOrReturnCtx(input, ctx);
1767
+ addIssueToContext(ctx, {
1768
+ validation: "nanoid",
1769
+ code: ZodIssueCode.invalid_string,
1770
+ message: check.message
1771
+ });
1772
+ status.dirty();
1773
+ }
1774
+ } else if (check.kind === "cuid") {
1775
+ if (!cuidRegex.test(input.data)) {
1776
+ ctx = this._getOrReturnCtx(input, ctx);
1777
+ addIssueToContext(ctx, {
1778
+ validation: "cuid",
1779
+ code: ZodIssueCode.invalid_string,
1780
+ message: check.message
1781
+ });
1782
+ status.dirty();
1783
+ }
1784
+ } else if (check.kind === "cuid2") {
1785
+ if (!cuid2Regex.test(input.data)) {
1786
+ ctx = this._getOrReturnCtx(input, ctx);
1787
+ addIssueToContext(ctx, {
1788
+ validation: "cuid2",
1789
+ code: ZodIssueCode.invalid_string,
1790
+ message: check.message
1791
+ });
1792
+ status.dirty();
1793
+ }
1794
+ } else if (check.kind === "ulid") {
1795
+ if (!ulidRegex.test(input.data)) {
1796
+ ctx = this._getOrReturnCtx(input, ctx);
1797
+ addIssueToContext(ctx, {
1798
+ validation: "ulid",
1799
+ code: ZodIssueCode.invalid_string,
1800
+ message: check.message
1801
+ });
1802
+ status.dirty();
1803
+ }
1804
+ } else if (check.kind === "url") {
1805
+ try {
1806
+ new URL(input.data);
1807
+ } catch {
1808
+ ctx = this._getOrReturnCtx(input, ctx);
1809
+ addIssueToContext(ctx, {
1810
+ validation: "url",
1811
+ code: ZodIssueCode.invalid_string,
1812
+ message: check.message
1813
+ });
1814
+ status.dirty();
1815
+ }
1816
+ } else if (check.kind === "regex") {
1817
+ check.regex.lastIndex = 0;
1818
+ const testResult = check.regex.test(input.data);
1819
+ if (!testResult) {
1820
+ ctx = this._getOrReturnCtx(input, ctx);
1821
+ addIssueToContext(ctx, {
1822
+ validation: "regex",
1823
+ code: ZodIssueCode.invalid_string,
1824
+ message: check.message
1825
+ });
1826
+ status.dirty();
1827
+ }
1828
+ } else if (check.kind === "trim") {
1829
+ input.data = input.data.trim();
1830
+ } else if (check.kind === "includes") {
1831
+ if (!input.data.includes(check.value, check.position)) {
1832
+ ctx = this._getOrReturnCtx(input, ctx);
1833
+ addIssueToContext(ctx, {
1834
+ code: ZodIssueCode.invalid_string,
1835
+ validation: { includes: check.value, position: check.position },
1836
+ message: check.message
1837
+ });
1838
+ status.dirty();
1839
+ }
1840
+ } else if (check.kind === "toLowerCase") {
1841
+ input.data = input.data.toLowerCase();
1842
+ } else if (check.kind === "toUpperCase") {
1843
+ input.data = input.data.toUpperCase();
1844
+ } else if (check.kind === "startsWith") {
1845
+ if (!input.data.startsWith(check.value)) {
1846
+ ctx = this._getOrReturnCtx(input, ctx);
1847
+ addIssueToContext(ctx, {
1848
+ code: ZodIssueCode.invalid_string,
1849
+ validation: { startsWith: check.value },
1850
+ message: check.message
1851
+ });
1852
+ status.dirty();
1853
+ }
1854
+ } else if (check.kind === "endsWith") {
1855
+ if (!input.data.endsWith(check.value)) {
1856
+ ctx = this._getOrReturnCtx(input, ctx);
1857
+ addIssueToContext(ctx, {
1858
+ code: ZodIssueCode.invalid_string,
1859
+ validation: { endsWith: check.value },
1860
+ message: check.message
1861
+ });
1862
+ status.dirty();
1863
+ }
1864
+ } else if (check.kind === "datetime") {
1865
+ const regex = datetimeRegex(check);
1866
+ if (!regex.test(input.data)) {
1867
+ ctx = this._getOrReturnCtx(input, ctx);
1868
+ addIssueToContext(ctx, {
1869
+ code: ZodIssueCode.invalid_string,
1870
+ validation: "datetime",
1871
+ message: check.message
1872
+ });
1873
+ status.dirty();
1874
+ }
1875
+ } else if (check.kind === "date") {
1876
+ const regex = dateRegex;
1877
+ if (!regex.test(input.data)) {
1878
+ ctx = this._getOrReturnCtx(input, ctx);
1879
+ addIssueToContext(ctx, {
1880
+ code: ZodIssueCode.invalid_string,
1881
+ validation: "date",
1882
+ message: check.message
1883
+ });
1884
+ status.dirty();
1885
+ }
1886
+ } else if (check.kind === "time") {
1887
+ const regex = timeRegex(check);
1888
+ if (!regex.test(input.data)) {
1889
+ ctx = this._getOrReturnCtx(input, ctx);
1890
+ addIssueToContext(ctx, {
1891
+ code: ZodIssueCode.invalid_string,
1892
+ validation: "time",
1893
+ message: check.message
1894
+ });
1895
+ status.dirty();
1896
+ }
1897
+ } else if (check.kind === "duration") {
1898
+ if (!durationRegex.test(input.data)) {
1899
+ ctx = this._getOrReturnCtx(input, ctx);
1900
+ addIssueToContext(ctx, {
1901
+ validation: "duration",
1902
+ code: ZodIssueCode.invalid_string,
1903
+ message: check.message
1904
+ });
1905
+ status.dirty();
1906
+ }
1907
+ } else if (check.kind === "ip") {
1908
+ if (!isValidIP(input.data, check.version)) {
1909
+ ctx = this._getOrReturnCtx(input, ctx);
1910
+ addIssueToContext(ctx, {
1911
+ validation: "ip",
1912
+ code: ZodIssueCode.invalid_string,
1913
+ message: check.message
1914
+ });
1915
+ status.dirty();
1916
+ }
1917
+ } else if (check.kind === "jwt") {
1918
+ if (!isValidJWT(input.data, check.alg)) {
1919
+ ctx = this._getOrReturnCtx(input, ctx);
1920
+ addIssueToContext(ctx, {
1921
+ validation: "jwt",
1922
+ code: ZodIssueCode.invalid_string,
1923
+ message: check.message
1924
+ });
1925
+ status.dirty();
1926
+ }
1927
+ } else if (check.kind === "cidr") {
1928
+ if (!isValidCidr(input.data, check.version)) {
1929
+ ctx = this._getOrReturnCtx(input, ctx);
1930
+ addIssueToContext(ctx, {
1931
+ validation: "cidr",
1932
+ code: ZodIssueCode.invalid_string,
1933
+ message: check.message
1934
+ });
1935
+ status.dirty();
1936
+ }
1937
+ } else if (check.kind === "base64") {
1938
+ if (!base64Regex.test(input.data)) {
1939
+ ctx = this._getOrReturnCtx(input, ctx);
1940
+ addIssueToContext(ctx, {
1941
+ validation: "base64",
1942
+ code: ZodIssueCode.invalid_string,
1943
+ message: check.message
1944
+ });
1945
+ status.dirty();
1946
+ }
1947
+ } else if (check.kind === "base64url") {
1948
+ if (!base64urlRegex.test(input.data)) {
1949
+ ctx = this._getOrReturnCtx(input, ctx);
1950
+ addIssueToContext(ctx, {
1951
+ validation: "base64url",
1952
+ code: ZodIssueCode.invalid_string,
1953
+ message: check.message
1954
+ });
1955
+ status.dirty();
1956
+ }
1957
+ } else {
1958
+ util.assertNever(check);
1959
+ }
1960
+ }
1961
+ return { status: status.value, value: input.data };
1962
+ }
1963
+ _regex(regex, validation, message) {
1964
+ return this.refinement((data) => regex.test(data), {
1965
+ validation,
1966
+ code: ZodIssueCode.invalid_string,
1967
+ ...errorUtil.errToObj(message)
1968
+ });
1969
+ }
1970
+ _addCheck(check) {
1971
+ return new ZodString({
1972
+ ...this._def,
1973
+ checks: [...this._def.checks, check]
1974
+ });
1975
+ }
1976
+ email(message) {
1977
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
1978
+ }
1979
+ url(message) {
1980
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
1981
+ }
1982
+ emoji(message) {
1983
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
1984
+ }
1985
+ uuid(message) {
1986
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1987
+ }
1988
+ nanoid(message) {
1989
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1990
+ }
1991
+ cuid(message) {
1992
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1993
+ }
1994
+ cuid2(message) {
1995
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
1996
+ }
1997
+ ulid(message) {
1998
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1999
+ }
2000
+ base64(message) {
2001
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
2002
+ }
2003
+ base64url(message) {
2004
+ return this._addCheck({
2005
+ kind: "base64url",
2006
+ ...errorUtil.errToObj(message)
2007
+ });
2008
+ }
2009
+ jwt(options) {
2010
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
2011
+ }
2012
+ ip(options) {
2013
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
2014
+ }
2015
+ cidr(options) {
2016
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
2017
+ }
2018
+ datetime(options) {
2019
+ if (typeof options === "string") {
2020
+ return this._addCheck({
2021
+ kind: "datetime",
2022
+ precision: null,
2023
+ offset: false,
2024
+ local: false,
2025
+ message: options
2026
+ });
2027
+ }
2028
+ return this._addCheck({
2029
+ kind: "datetime",
2030
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
2031
+ offset: options?.offset ?? false,
2032
+ local: options?.local ?? false,
2033
+ ...errorUtil.errToObj(options?.message)
2034
+ });
2035
+ }
2036
+ date(message) {
2037
+ return this._addCheck({ kind: "date", message });
2038
+ }
2039
+ time(options) {
2040
+ if (typeof options === "string") {
2041
+ return this._addCheck({
2042
+ kind: "time",
2043
+ precision: null,
2044
+ message: options
2045
+ });
2046
+ }
2047
+ return this._addCheck({
2048
+ kind: "time",
2049
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
2050
+ ...errorUtil.errToObj(options?.message)
2051
+ });
2052
+ }
2053
+ duration(message) {
2054
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
2055
+ }
2056
+ regex(regex, message) {
2057
+ return this._addCheck({
2058
+ kind: "regex",
2059
+ regex,
2060
+ ...errorUtil.errToObj(message)
2061
+ });
2062
+ }
2063
+ includes(value, options) {
2064
+ return this._addCheck({
2065
+ kind: "includes",
2066
+ value,
2067
+ position: options?.position,
2068
+ ...errorUtil.errToObj(options?.message)
2069
+ });
2070
+ }
2071
+ startsWith(value, message) {
2072
+ return this._addCheck({
2073
+ kind: "startsWith",
2074
+ value,
2075
+ ...errorUtil.errToObj(message)
2076
+ });
2077
+ }
2078
+ endsWith(value, message) {
2079
+ return this._addCheck({
2080
+ kind: "endsWith",
2081
+ value,
2082
+ ...errorUtil.errToObj(message)
2083
+ });
2084
+ }
2085
+ min(minLength, message) {
2086
+ return this._addCheck({
2087
+ kind: "min",
2088
+ value: minLength,
2089
+ ...errorUtil.errToObj(message)
2090
+ });
2091
+ }
2092
+ max(maxLength, message) {
2093
+ return this._addCheck({
2094
+ kind: "max",
2095
+ value: maxLength,
2096
+ ...errorUtil.errToObj(message)
2097
+ });
2098
+ }
2099
+ length(len, message) {
2100
+ return this._addCheck({
2101
+ kind: "length",
2102
+ value: len,
2103
+ ...errorUtil.errToObj(message)
2104
+ });
2105
+ }
2106
+ nonempty(message) {
2107
+ return this.min(1, errorUtil.errToObj(message));
2108
+ }
2109
+ trim() {
2110
+ return new ZodString({
2111
+ ...this._def,
2112
+ checks: [...this._def.checks, { kind: "trim" }]
2113
+ });
2114
+ }
2115
+ toLowerCase() {
2116
+ return new ZodString({
2117
+ ...this._def,
2118
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
2119
+ });
2120
+ }
2121
+ toUpperCase() {
2122
+ return new ZodString({
2123
+ ...this._def,
2124
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
2125
+ });
2126
+ }
2127
+ get isDatetime() {
2128
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
2129
+ }
2130
+ get isDate() {
2131
+ return !!this._def.checks.find((ch) => ch.kind === "date");
2132
+ }
2133
+ get isTime() {
2134
+ return !!this._def.checks.find((ch) => ch.kind === "time");
2135
+ }
2136
+ get isDuration() {
2137
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
2138
+ }
2139
+ get isEmail() {
2140
+ return !!this._def.checks.find((ch) => ch.kind === "email");
2141
+ }
2142
+ get isURL() {
2143
+ return !!this._def.checks.find((ch) => ch.kind === "url");
2144
+ }
2145
+ get isEmoji() {
2146
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
2147
+ }
2148
+ get isUUID() {
2149
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
2150
+ }
2151
+ get isNANOID() {
2152
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
2153
+ }
2154
+ get isCUID() {
2155
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
2156
+ }
2157
+ get isCUID2() {
2158
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
2159
+ }
2160
+ get isULID() {
2161
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
2162
+ }
2163
+ get isIP() {
2164
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
2165
+ }
2166
+ get isCIDR() {
2167
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
2168
+ }
2169
+ get isBase64() {
2170
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
2171
+ }
2172
+ get isBase64url() {
2173
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
2174
+ }
2175
+ get minLength() {
2176
+ let min = null;
2177
+ for (const ch of this._def.checks) {
2178
+ if (ch.kind === "min") {
2179
+ if (min === null || ch.value > min)
2180
+ min = ch.value;
2181
+ }
2182
+ }
2183
+ return min;
2184
+ }
2185
+ get maxLength() {
2186
+ let max = null;
2187
+ for (const ch of this._def.checks) {
2188
+ if (ch.kind === "max") {
2189
+ if (max === null || ch.value < max)
2190
+ max = ch.value;
2191
+ }
2192
+ }
2193
+ return max;
2194
+ }
2195
+ }
2196
+ ZodString.create = (params) => {
2197
+ return new ZodString({
2198
+ checks: [],
2199
+ typeName: ZodFirstPartyTypeKind.ZodString,
2200
+ coerce: params?.coerce ?? false,
2201
+ ...processCreateParams(params)
2202
+ });
2203
+ };
2204
+ function floatSafeRemainder(val, step) {
2205
+ const valDecCount = (val.toString().split(".")[1] || "").length;
2206
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
2207
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
2208
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
2209
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
2210
+ return valInt % stepInt / 10 ** decCount;
2211
+ }
2212
+
2213
+ class ZodNumber extends ZodType {
2214
+ constructor() {
2215
+ super(...arguments);
2216
+ this.min = this.gte;
2217
+ this.max = this.lte;
2218
+ this.step = this.multipleOf;
2219
+ }
2220
+ _parse(input) {
2221
+ if (this._def.coerce) {
2222
+ input.data = Number(input.data);
2223
+ }
2224
+ const parsedType = this._getType(input);
2225
+ if (parsedType !== ZodParsedType.number) {
2226
+ const ctx2 = this._getOrReturnCtx(input);
2227
+ addIssueToContext(ctx2, {
2228
+ code: ZodIssueCode.invalid_type,
2229
+ expected: ZodParsedType.number,
2230
+ received: ctx2.parsedType
2231
+ });
2232
+ return INVALID;
2233
+ }
2234
+ let ctx = undefined;
2235
+ const status = new ParseStatus;
2236
+ for (const check of this._def.checks) {
2237
+ if (check.kind === "int") {
2238
+ if (!util.isInteger(input.data)) {
2239
+ ctx = this._getOrReturnCtx(input, ctx);
2240
+ addIssueToContext(ctx, {
2241
+ code: ZodIssueCode.invalid_type,
2242
+ expected: "integer",
2243
+ received: "float",
2244
+ message: check.message
2245
+ });
2246
+ status.dirty();
2247
+ }
2248
+ } else if (check.kind === "min") {
2249
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2250
+ if (tooSmall) {
2251
+ ctx = this._getOrReturnCtx(input, ctx);
2252
+ addIssueToContext(ctx, {
2253
+ code: ZodIssueCode.too_small,
2254
+ minimum: check.value,
2255
+ type: "number",
2256
+ inclusive: check.inclusive,
2257
+ exact: false,
2258
+ message: check.message
2259
+ });
2260
+ status.dirty();
2261
+ }
2262
+ } else if (check.kind === "max") {
2263
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2264
+ if (tooBig) {
2265
+ ctx = this._getOrReturnCtx(input, ctx);
2266
+ addIssueToContext(ctx, {
2267
+ code: ZodIssueCode.too_big,
2268
+ maximum: check.value,
2269
+ type: "number",
2270
+ inclusive: check.inclusive,
2271
+ exact: false,
2272
+ message: check.message
2273
+ });
2274
+ status.dirty();
2275
+ }
2276
+ } else if (check.kind === "multipleOf") {
2277
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
2278
+ ctx = this._getOrReturnCtx(input, ctx);
2279
+ addIssueToContext(ctx, {
2280
+ code: ZodIssueCode.not_multiple_of,
2281
+ multipleOf: check.value,
2282
+ message: check.message
2283
+ });
2284
+ status.dirty();
2285
+ }
2286
+ } else if (check.kind === "finite") {
2287
+ if (!Number.isFinite(input.data)) {
2288
+ ctx = this._getOrReturnCtx(input, ctx);
2289
+ addIssueToContext(ctx, {
2290
+ code: ZodIssueCode.not_finite,
2291
+ message: check.message
2292
+ });
2293
+ status.dirty();
2294
+ }
2295
+ } else {
2296
+ util.assertNever(check);
2297
+ }
2298
+ }
2299
+ return { status: status.value, value: input.data };
2300
+ }
2301
+ gte(value, message) {
2302
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2303
+ }
2304
+ gt(value, message) {
2305
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2306
+ }
2307
+ lte(value, message) {
2308
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2309
+ }
2310
+ lt(value, message) {
2311
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2312
+ }
2313
+ setLimit(kind, value, inclusive, message) {
2314
+ return new ZodNumber({
2315
+ ...this._def,
2316
+ checks: [
2317
+ ...this._def.checks,
2318
+ {
2319
+ kind,
2320
+ value,
2321
+ inclusive,
2322
+ message: errorUtil.toString(message)
2323
+ }
2324
+ ]
2325
+ });
2326
+ }
2327
+ _addCheck(check) {
2328
+ return new ZodNumber({
2329
+ ...this._def,
2330
+ checks: [...this._def.checks, check]
2331
+ });
2332
+ }
2333
+ int(message) {
2334
+ return this._addCheck({
2335
+ kind: "int",
2336
+ message: errorUtil.toString(message)
2337
+ });
2338
+ }
2339
+ positive(message) {
2340
+ return this._addCheck({
2341
+ kind: "min",
2342
+ value: 0,
2343
+ inclusive: false,
2344
+ message: errorUtil.toString(message)
2345
+ });
2346
+ }
2347
+ negative(message) {
2348
+ return this._addCheck({
2349
+ kind: "max",
2350
+ value: 0,
2351
+ inclusive: false,
2352
+ message: errorUtil.toString(message)
2353
+ });
2354
+ }
2355
+ nonpositive(message) {
2356
+ return this._addCheck({
2357
+ kind: "max",
2358
+ value: 0,
2359
+ inclusive: true,
2360
+ message: errorUtil.toString(message)
2361
+ });
2362
+ }
2363
+ nonnegative(message) {
2364
+ return this._addCheck({
2365
+ kind: "min",
2366
+ value: 0,
2367
+ inclusive: true,
2368
+ message: errorUtil.toString(message)
2369
+ });
2370
+ }
2371
+ multipleOf(value, message) {
2372
+ return this._addCheck({
2373
+ kind: "multipleOf",
2374
+ value,
2375
+ message: errorUtil.toString(message)
2376
+ });
2377
+ }
2378
+ finite(message) {
2379
+ return this._addCheck({
2380
+ kind: "finite",
2381
+ message: errorUtil.toString(message)
2382
+ });
2383
+ }
2384
+ safe(message) {
2385
+ return this._addCheck({
2386
+ kind: "min",
2387
+ inclusive: true,
2388
+ value: Number.MIN_SAFE_INTEGER,
2389
+ message: errorUtil.toString(message)
2390
+ })._addCheck({
2391
+ kind: "max",
2392
+ inclusive: true,
2393
+ value: Number.MAX_SAFE_INTEGER,
2394
+ message: errorUtil.toString(message)
2395
+ });
2396
+ }
2397
+ get minValue() {
2398
+ let min = null;
2399
+ for (const ch of this._def.checks) {
2400
+ if (ch.kind === "min") {
2401
+ if (min === null || ch.value > min)
2402
+ min = ch.value;
2403
+ }
2404
+ }
2405
+ return min;
2406
+ }
2407
+ get maxValue() {
2408
+ let max = null;
2409
+ for (const ch of this._def.checks) {
2410
+ if (ch.kind === "max") {
2411
+ if (max === null || ch.value < max)
2412
+ max = ch.value;
2413
+ }
2414
+ }
2415
+ return max;
2416
+ }
2417
+ get isInt() {
2418
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
2419
+ }
2420
+ get isFinite() {
2421
+ let max = null;
2422
+ let min = null;
2423
+ for (const ch of this._def.checks) {
2424
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
2425
+ return true;
2426
+ } else if (ch.kind === "min") {
2427
+ if (min === null || ch.value > min)
2428
+ min = ch.value;
2429
+ } else if (ch.kind === "max") {
2430
+ if (max === null || ch.value < max)
2431
+ max = ch.value;
2432
+ }
2433
+ }
2434
+ return Number.isFinite(min) && Number.isFinite(max);
2435
+ }
2436
+ }
2437
+ ZodNumber.create = (params) => {
2438
+ return new ZodNumber({
2439
+ checks: [],
2440
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
2441
+ coerce: params?.coerce || false,
2442
+ ...processCreateParams(params)
2443
+ });
2444
+ };
2445
+
2446
+ class ZodBigInt extends ZodType {
2447
+ constructor() {
2448
+ super(...arguments);
2449
+ this.min = this.gte;
2450
+ this.max = this.lte;
2451
+ }
2452
+ _parse(input) {
2453
+ if (this._def.coerce) {
2454
+ try {
2455
+ input.data = BigInt(input.data);
2456
+ } catch {
2457
+ return this._getInvalidInput(input);
2458
+ }
2459
+ }
2460
+ const parsedType = this._getType(input);
2461
+ if (parsedType !== ZodParsedType.bigint) {
2462
+ return this._getInvalidInput(input);
2463
+ }
2464
+ let ctx = undefined;
2465
+ const status = new ParseStatus;
2466
+ for (const check of this._def.checks) {
2467
+ if (check.kind === "min") {
2468
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
2469
+ if (tooSmall) {
2470
+ ctx = this._getOrReturnCtx(input, ctx);
2471
+ addIssueToContext(ctx, {
2472
+ code: ZodIssueCode.too_small,
2473
+ type: "bigint",
2474
+ minimum: check.value,
2475
+ inclusive: check.inclusive,
2476
+ message: check.message
2477
+ });
2478
+ status.dirty();
2479
+ }
2480
+ } else if (check.kind === "max") {
2481
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
2482
+ if (tooBig) {
2483
+ ctx = this._getOrReturnCtx(input, ctx);
2484
+ addIssueToContext(ctx, {
2485
+ code: ZodIssueCode.too_big,
2486
+ type: "bigint",
2487
+ maximum: check.value,
2488
+ inclusive: check.inclusive,
2489
+ message: check.message
2490
+ });
2491
+ status.dirty();
2492
+ }
2493
+ } else if (check.kind === "multipleOf") {
2494
+ if (input.data % check.value !== BigInt(0)) {
2495
+ ctx = this._getOrReturnCtx(input, ctx);
2496
+ addIssueToContext(ctx, {
2497
+ code: ZodIssueCode.not_multiple_of,
2498
+ multipleOf: check.value,
2499
+ message: check.message
2500
+ });
2501
+ status.dirty();
2502
+ }
2503
+ } else {
2504
+ util.assertNever(check);
2505
+ }
2506
+ }
2507
+ return { status: status.value, value: input.data };
2508
+ }
2509
+ _getInvalidInput(input) {
2510
+ const ctx = this._getOrReturnCtx(input);
2511
+ addIssueToContext(ctx, {
2512
+ code: ZodIssueCode.invalid_type,
2513
+ expected: ZodParsedType.bigint,
2514
+ received: ctx.parsedType
2515
+ });
2516
+ return INVALID;
2517
+ }
2518
+ gte(value, message) {
2519
+ return this.setLimit("min", value, true, errorUtil.toString(message));
2520
+ }
2521
+ gt(value, message) {
2522
+ return this.setLimit("min", value, false, errorUtil.toString(message));
2523
+ }
2524
+ lte(value, message) {
2525
+ return this.setLimit("max", value, true, errorUtil.toString(message));
2526
+ }
2527
+ lt(value, message) {
2528
+ return this.setLimit("max", value, false, errorUtil.toString(message));
2529
+ }
2530
+ setLimit(kind, value, inclusive, message) {
2531
+ return new ZodBigInt({
2532
+ ...this._def,
2533
+ checks: [
2534
+ ...this._def.checks,
2535
+ {
2536
+ kind,
2537
+ value,
2538
+ inclusive,
2539
+ message: errorUtil.toString(message)
2540
+ }
2541
+ ]
2542
+ });
2543
+ }
2544
+ _addCheck(check) {
2545
+ return new ZodBigInt({
2546
+ ...this._def,
2547
+ checks: [...this._def.checks, check]
2548
+ });
2549
+ }
2550
+ positive(message) {
2551
+ return this._addCheck({
2552
+ kind: "min",
2553
+ value: BigInt(0),
2554
+ inclusive: false,
2555
+ message: errorUtil.toString(message)
2556
+ });
2557
+ }
2558
+ negative(message) {
2559
+ return this._addCheck({
2560
+ kind: "max",
2561
+ value: BigInt(0),
2562
+ inclusive: false,
2563
+ message: errorUtil.toString(message)
2564
+ });
2565
+ }
2566
+ nonpositive(message) {
2567
+ return this._addCheck({
2568
+ kind: "max",
2569
+ value: BigInt(0),
2570
+ inclusive: true,
2571
+ message: errorUtil.toString(message)
2572
+ });
2573
+ }
2574
+ nonnegative(message) {
2575
+ return this._addCheck({
2576
+ kind: "min",
2577
+ value: BigInt(0),
2578
+ inclusive: true,
2579
+ message: errorUtil.toString(message)
2580
+ });
2581
+ }
2582
+ multipleOf(value, message) {
2583
+ return this._addCheck({
2584
+ kind: "multipleOf",
2585
+ value,
2586
+ message: errorUtil.toString(message)
2587
+ });
2588
+ }
2589
+ get minValue() {
2590
+ let min = null;
2591
+ for (const ch of this._def.checks) {
2592
+ if (ch.kind === "min") {
2593
+ if (min === null || ch.value > min)
2594
+ min = ch.value;
2595
+ }
2596
+ }
2597
+ return min;
2598
+ }
2599
+ get maxValue() {
2600
+ let max = null;
2601
+ for (const ch of this._def.checks) {
2602
+ if (ch.kind === "max") {
2603
+ if (max === null || ch.value < max)
2604
+ max = ch.value;
2605
+ }
2606
+ }
2607
+ return max;
2608
+ }
2609
+ }
2610
+ ZodBigInt.create = (params) => {
2611
+ return new ZodBigInt({
2612
+ checks: [],
2613
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
2614
+ coerce: params?.coerce ?? false,
2615
+ ...processCreateParams(params)
2616
+ });
2617
+ };
2618
+
2619
+ class ZodBoolean extends ZodType {
2620
+ _parse(input) {
2621
+ if (this._def.coerce) {
2622
+ input.data = Boolean(input.data);
2623
+ }
2624
+ const parsedType = this._getType(input);
2625
+ if (parsedType !== ZodParsedType.boolean) {
2626
+ const ctx = this._getOrReturnCtx(input);
2627
+ addIssueToContext(ctx, {
2628
+ code: ZodIssueCode.invalid_type,
2629
+ expected: ZodParsedType.boolean,
2630
+ received: ctx.parsedType
2631
+ });
2632
+ return INVALID;
2633
+ }
2634
+ return OK(input.data);
2635
+ }
2636
+ }
2637
+ ZodBoolean.create = (params) => {
2638
+ return new ZodBoolean({
2639
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
2640
+ coerce: params?.coerce || false,
2641
+ ...processCreateParams(params)
2642
+ });
2643
+ };
2644
+
2645
+ class ZodDate extends ZodType {
2646
+ _parse(input) {
2647
+ if (this._def.coerce) {
2648
+ input.data = new Date(input.data);
2649
+ }
2650
+ const parsedType = this._getType(input);
2651
+ if (parsedType !== ZodParsedType.date) {
2652
+ const ctx2 = this._getOrReturnCtx(input);
2653
+ addIssueToContext(ctx2, {
2654
+ code: ZodIssueCode.invalid_type,
2655
+ expected: ZodParsedType.date,
2656
+ received: ctx2.parsedType
2657
+ });
2658
+ return INVALID;
2659
+ }
2660
+ if (Number.isNaN(input.data.getTime())) {
2661
+ const ctx2 = this._getOrReturnCtx(input);
2662
+ addIssueToContext(ctx2, {
2663
+ code: ZodIssueCode.invalid_date
2664
+ });
2665
+ return INVALID;
2666
+ }
2667
+ const status = new ParseStatus;
2668
+ let ctx = undefined;
2669
+ for (const check of this._def.checks) {
2670
+ if (check.kind === "min") {
2671
+ if (input.data.getTime() < check.value) {
2672
+ ctx = this._getOrReturnCtx(input, ctx);
2673
+ addIssueToContext(ctx, {
2674
+ code: ZodIssueCode.too_small,
2675
+ message: check.message,
2676
+ inclusive: true,
2677
+ exact: false,
2678
+ minimum: check.value,
2679
+ type: "date"
2680
+ });
2681
+ status.dirty();
2682
+ }
2683
+ } else if (check.kind === "max") {
2684
+ if (input.data.getTime() > check.value) {
2685
+ ctx = this._getOrReturnCtx(input, ctx);
2686
+ addIssueToContext(ctx, {
2687
+ code: ZodIssueCode.too_big,
2688
+ message: check.message,
2689
+ inclusive: true,
2690
+ exact: false,
2691
+ maximum: check.value,
2692
+ type: "date"
2693
+ });
2694
+ status.dirty();
2695
+ }
2696
+ } else {
2697
+ util.assertNever(check);
2698
+ }
2699
+ }
2700
+ return {
2701
+ status: status.value,
2702
+ value: new Date(input.data.getTime())
2703
+ };
2704
+ }
2705
+ _addCheck(check) {
2706
+ return new ZodDate({
2707
+ ...this._def,
2708
+ checks: [...this._def.checks, check]
2709
+ });
2710
+ }
2711
+ min(minDate, message) {
2712
+ return this._addCheck({
2713
+ kind: "min",
2714
+ value: minDate.getTime(),
2715
+ message: errorUtil.toString(message)
2716
+ });
2717
+ }
2718
+ max(maxDate, message) {
2719
+ return this._addCheck({
2720
+ kind: "max",
2721
+ value: maxDate.getTime(),
2722
+ message: errorUtil.toString(message)
2723
+ });
2724
+ }
2725
+ get minDate() {
2726
+ let min = null;
2727
+ for (const ch of this._def.checks) {
2728
+ if (ch.kind === "min") {
2729
+ if (min === null || ch.value > min)
2730
+ min = ch.value;
2731
+ }
2732
+ }
2733
+ return min != null ? new Date(min) : null;
2734
+ }
2735
+ get maxDate() {
2736
+ let max = null;
2737
+ for (const ch of this._def.checks) {
2738
+ if (ch.kind === "max") {
2739
+ if (max === null || ch.value < max)
2740
+ max = ch.value;
2741
+ }
2742
+ }
2743
+ return max != null ? new Date(max) : null;
2744
+ }
2745
+ }
2746
+ ZodDate.create = (params) => {
2747
+ return new ZodDate({
2748
+ checks: [],
2749
+ coerce: params?.coerce || false,
2750
+ typeName: ZodFirstPartyTypeKind.ZodDate,
2751
+ ...processCreateParams(params)
2752
+ });
2753
+ };
2754
+
2755
+ class ZodSymbol extends ZodType {
2756
+ _parse(input) {
2757
+ const parsedType = this._getType(input);
2758
+ if (parsedType !== ZodParsedType.symbol) {
2759
+ const ctx = this._getOrReturnCtx(input);
2760
+ addIssueToContext(ctx, {
2761
+ code: ZodIssueCode.invalid_type,
2762
+ expected: ZodParsedType.symbol,
2763
+ received: ctx.parsedType
2764
+ });
2765
+ return INVALID;
2766
+ }
2767
+ return OK(input.data);
2768
+ }
2769
+ }
2770
+ ZodSymbol.create = (params) => {
2771
+ return new ZodSymbol({
2772
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
2773
+ ...processCreateParams(params)
2774
+ });
2775
+ };
2776
+
2777
+ class ZodUndefined extends ZodType {
2778
+ _parse(input) {
2779
+ const parsedType = this._getType(input);
2780
+ if (parsedType !== ZodParsedType.undefined) {
2781
+ const ctx = this._getOrReturnCtx(input);
2782
+ addIssueToContext(ctx, {
2783
+ code: ZodIssueCode.invalid_type,
2784
+ expected: ZodParsedType.undefined,
2785
+ received: ctx.parsedType
2786
+ });
2787
+ return INVALID;
2788
+ }
2789
+ return OK(input.data);
2790
+ }
2791
+ }
2792
+ ZodUndefined.create = (params) => {
2793
+ return new ZodUndefined({
2794
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
2795
+ ...processCreateParams(params)
2796
+ });
2797
+ };
2798
+
2799
+ class ZodNull extends ZodType {
2800
+ _parse(input) {
2801
+ const parsedType = this._getType(input);
2802
+ if (parsedType !== ZodParsedType.null) {
2803
+ const ctx = this._getOrReturnCtx(input);
2804
+ addIssueToContext(ctx, {
2805
+ code: ZodIssueCode.invalid_type,
2806
+ expected: ZodParsedType.null,
2807
+ received: ctx.parsedType
2808
+ });
2809
+ return INVALID;
2810
+ }
2811
+ return OK(input.data);
2812
+ }
2813
+ }
2814
+ ZodNull.create = (params) => {
2815
+ return new ZodNull({
2816
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2817
+ ...processCreateParams(params)
2818
+ });
2819
+ };
2820
+
2821
+ class ZodAny extends ZodType {
2822
+ constructor() {
2823
+ super(...arguments);
2824
+ this._any = true;
2825
+ }
2826
+ _parse(input) {
2827
+ return OK(input.data);
2828
+ }
2829
+ }
2830
+ ZodAny.create = (params) => {
2831
+ return new ZodAny({
2832
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2833
+ ...processCreateParams(params)
2834
+ });
2835
+ };
2836
+
2837
+ class ZodUnknown extends ZodType {
2838
+ constructor() {
2839
+ super(...arguments);
2840
+ this._unknown = true;
2841
+ }
2842
+ _parse(input) {
2843
+ return OK(input.data);
2844
+ }
2845
+ }
2846
+ ZodUnknown.create = (params) => {
2847
+ return new ZodUnknown({
2848
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2849
+ ...processCreateParams(params)
2850
+ });
2851
+ };
2852
+
2853
+ class ZodNever extends ZodType {
2854
+ _parse(input) {
2855
+ const ctx = this._getOrReturnCtx(input);
2856
+ addIssueToContext(ctx, {
2857
+ code: ZodIssueCode.invalid_type,
2858
+ expected: ZodParsedType.never,
2859
+ received: ctx.parsedType
2860
+ });
2861
+ return INVALID;
2862
+ }
2863
+ }
2864
+ ZodNever.create = (params) => {
2865
+ return new ZodNever({
2866
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2867
+ ...processCreateParams(params)
2868
+ });
2869
+ };
2870
+
2871
+ class ZodVoid extends ZodType {
2872
+ _parse(input) {
2873
+ const parsedType = this._getType(input);
2874
+ if (parsedType !== ZodParsedType.undefined) {
2875
+ const ctx = this._getOrReturnCtx(input);
2876
+ addIssueToContext(ctx, {
2877
+ code: ZodIssueCode.invalid_type,
2878
+ expected: ZodParsedType.void,
2879
+ received: ctx.parsedType
2880
+ });
2881
+ return INVALID;
2882
+ }
2883
+ return OK(input.data);
2884
+ }
2885
+ }
2886
+ ZodVoid.create = (params) => {
2887
+ return new ZodVoid({
2888
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2889
+ ...processCreateParams(params)
2890
+ });
2891
+ };
2892
+
2893
+ class ZodArray extends ZodType {
2894
+ _parse(input) {
2895
+ const { ctx, status } = this._processInputParams(input);
2896
+ const def = this._def;
2897
+ if (ctx.parsedType !== ZodParsedType.array) {
2898
+ addIssueToContext(ctx, {
2899
+ code: ZodIssueCode.invalid_type,
2900
+ expected: ZodParsedType.array,
2901
+ received: ctx.parsedType
2902
+ });
2903
+ return INVALID;
2904
+ }
2905
+ if (def.exactLength !== null) {
2906
+ const tooBig = ctx.data.length > def.exactLength.value;
2907
+ const tooSmall = ctx.data.length < def.exactLength.value;
2908
+ if (tooBig || tooSmall) {
2909
+ addIssueToContext(ctx, {
2910
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2911
+ minimum: tooSmall ? def.exactLength.value : undefined,
2912
+ maximum: tooBig ? def.exactLength.value : undefined,
2913
+ type: "array",
2914
+ inclusive: true,
2915
+ exact: true,
2916
+ message: def.exactLength.message
2917
+ });
2918
+ status.dirty();
2919
+ }
2920
+ }
2921
+ if (def.minLength !== null) {
2922
+ if (ctx.data.length < def.minLength.value) {
2923
+ addIssueToContext(ctx, {
2924
+ code: ZodIssueCode.too_small,
2925
+ minimum: def.minLength.value,
2926
+ type: "array",
2927
+ inclusive: true,
2928
+ exact: false,
2929
+ message: def.minLength.message
2930
+ });
2931
+ status.dirty();
2932
+ }
2933
+ }
2934
+ if (def.maxLength !== null) {
2935
+ if (ctx.data.length > def.maxLength.value) {
2936
+ addIssueToContext(ctx, {
2937
+ code: ZodIssueCode.too_big,
2938
+ maximum: def.maxLength.value,
2939
+ type: "array",
2940
+ inclusive: true,
2941
+ exact: false,
2942
+ message: def.maxLength.message
2943
+ });
2944
+ status.dirty();
2945
+ }
2946
+ }
2947
+ if (ctx.common.async) {
2948
+ return Promise.all([...ctx.data].map((item, i) => {
2949
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2950
+ })).then((result2) => {
2951
+ return ParseStatus.mergeArray(status, result2);
2952
+ });
2953
+ }
2954
+ const result = [...ctx.data].map((item, i) => {
2955
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2956
+ });
2957
+ return ParseStatus.mergeArray(status, result);
2958
+ }
2959
+ get element() {
2960
+ return this._def.type;
2961
+ }
2962
+ min(minLength, message) {
2963
+ return new ZodArray({
2964
+ ...this._def,
2965
+ minLength: { value: minLength, message: errorUtil.toString(message) }
2966
+ });
2967
+ }
2968
+ max(maxLength, message) {
2969
+ return new ZodArray({
2970
+ ...this._def,
2971
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
2972
+ });
2973
+ }
2974
+ length(len, message) {
2975
+ return new ZodArray({
2976
+ ...this._def,
2977
+ exactLength: { value: len, message: errorUtil.toString(message) }
2978
+ });
2979
+ }
2980
+ nonempty(message) {
2981
+ return this.min(1, message);
2982
+ }
2983
+ }
2984
+ ZodArray.create = (schema, params) => {
2985
+ return new ZodArray({
2986
+ type: schema,
2987
+ minLength: null,
2988
+ maxLength: null,
2989
+ exactLength: null,
2990
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2991
+ ...processCreateParams(params)
2992
+ });
2993
+ };
2994
+ function deepPartialify(schema) {
2995
+ if (schema instanceof ZodObject) {
2996
+ const newShape = {};
2997
+ for (const key in schema.shape) {
2998
+ const fieldSchema = schema.shape[key];
2999
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
3000
+ }
3001
+ return new ZodObject({
3002
+ ...schema._def,
3003
+ shape: () => newShape
3004
+ });
3005
+ } else if (schema instanceof ZodArray) {
3006
+ return new ZodArray({
3007
+ ...schema._def,
3008
+ type: deepPartialify(schema.element)
3009
+ });
3010
+ } else if (schema instanceof ZodOptional) {
3011
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
3012
+ } else if (schema instanceof ZodNullable) {
3013
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
3014
+ } else if (schema instanceof ZodTuple) {
3015
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
3016
+ } else {
3017
+ return schema;
3018
+ }
3019
+ }
3020
+
3021
+ class ZodObject extends ZodType {
3022
+ constructor() {
3023
+ super(...arguments);
3024
+ this._cached = null;
3025
+ this.nonstrict = this.passthrough;
3026
+ this.augment = this.extend;
3027
+ }
3028
+ _getCached() {
3029
+ if (this._cached !== null)
3030
+ return this._cached;
3031
+ const shape = this._def.shape();
3032
+ const keys = util.objectKeys(shape);
3033
+ this._cached = { shape, keys };
3034
+ return this._cached;
3035
+ }
3036
+ _parse(input) {
3037
+ const parsedType = this._getType(input);
3038
+ if (parsedType !== ZodParsedType.object) {
3039
+ const ctx2 = this._getOrReturnCtx(input);
3040
+ addIssueToContext(ctx2, {
3041
+ code: ZodIssueCode.invalid_type,
3042
+ expected: ZodParsedType.object,
3043
+ received: ctx2.parsedType
3044
+ });
3045
+ return INVALID;
3046
+ }
3047
+ const { status, ctx } = this._processInputParams(input);
3048
+ const { shape, keys: shapeKeys } = this._getCached();
3049
+ const extraKeys = [];
3050
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
3051
+ for (const key in ctx.data) {
3052
+ if (!shapeKeys.includes(key)) {
3053
+ extraKeys.push(key);
3054
+ }
3055
+ }
3056
+ }
3057
+ const pairs = [];
3058
+ for (const key of shapeKeys) {
3059
+ const keyValidator = shape[key];
3060
+ const value = ctx.data[key];
3061
+ pairs.push({
3062
+ key: { status: "valid", value: key },
3063
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
3064
+ alwaysSet: key in ctx.data
3065
+ });
3066
+ }
3067
+ if (this._def.catchall instanceof ZodNever) {
3068
+ const unknownKeys = this._def.unknownKeys;
3069
+ if (unknownKeys === "passthrough") {
3070
+ for (const key of extraKeys) {
3071
+ pairs.push({
3072
+ key: { status: "valid", value: key },
3073
+ value: { status: "valid", value: ctx.data[key] }
3074
+ });
3075
+ }
3076
+ } else if (unknownKeys === "strict") {
3077
+ if (extraKeys.length > 0) {
3078
+ addIssueToContext(ctx, {
3079
+ code: ZodIssueCode.unrecognized_keys,
3080
+ keys: extraKeys
3081
+ });
3082
+ status.dirty();
3083
+ }
3084
+ } else if (unknownKeys === "strip") {} else {
3085
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
3086
+ }
3087
+ } else {
3088
+ const catchall = this._def.catchall;
3089
+ for (const key of extraKeys) {
3090
+ const value = ctx.data[key];
3091
+ pairs.push({
3092
+ key: { status: "valid", value: key },
3093
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
3094
+ alwaysSet: key in ctx.data
3095
+ });
3096
+ }
3097
+ }
3098
+ if (ctx.common.async) {
3099
+ return Promise.resolve().then(async () => {
3100
+ const syncPairs = [];
3101
+ for (const pair of pairs) {
3102
+ const key = await pair.key;
3103
+ const value = await pair.value;
3104
+ syncPairs.push({
3105
+ key,
3106
+ value,
3107
+ alwaysSet: pair.alwaysSet
3108
+ });
3109
+ }
3110
+ return syncPairs;
3111
+ }).then((syncPairs) => {
3112
+ return ParseStatus.mergeObjectSync(status, syncPairs);
3113
+ });
3114
+ } else {
3115
+ return ParseStatus.mergeObjectSync(status, pairs);
3116
+ }
3117
+ }
3118
+ get shape() {
3119
+ return this._def.shape();
3120
+ }
3121
+ strict(message) {
3122
+ errorUtil.errToObj;
3123
+ return new ZodObject({
3124
+ ...this._def,
3125
+ unknownKeys: "strict",
3126
+ ...message !== undefined ? {
3127
+ errorMap: (issue, ctx) => {
3128
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
3129
+ if (issue.code === "unrecognized_keys")
3130
+ return {
3131
+ message: errorUtil.errToObj(message).message ?? defaultError
3132
+ };
3133
+ return {
3134
+ message: defaultError
3135
+ };
3136
+ }
3137
+ } : {}
3138
+ });
3139
+ }
3140
+ strip() {
3141
+ return new ZodObject({
3142
+ ...this._def,
3143
+ unknownKeys: "strip"
3144
+ });
3145
+ }
3146
+ passthrough() {
3147
+ return new ZodObject({
3148
+ ...this._def,
3149
+ unknownKeys: "passthrough"
3150
+ });
3151
+ }
3152
+ extend(augmentation) {
3153
+ return new ZodObject({
3154
+ ...this._def,
3155
+ shape: () => ({
3156
+ ...this._def.shape(),
3157
+ ...augmentation
3158
+ })
3159
+ });
3160
+ }
3161
+ merge(merging) {
3162
+ const merged = new ZodObject({
3163
+ unknownKeys: merging._def.unknownKeys,
3164
+ catchall: merging._def.catchall,
3165
+ shape: () => ({
3166
+ ...this._def.shape(),
3167
+ ...merging._def.shape()
3168
+ }),
3169
+ typeName: ZodFirstPartyTypeKind.ZodObject
3170
+ });
3171
+ return merged;
3172
+ }
3173
+ setKey(key, schema) {
3174
+ return this.augment({ [key]: schema });
3175
+ }
3176
+ catchall(index) {
3177
+ return new ZodObject({
3178
+ ...this._def,
3179
+ catchall: index
3180
+ });
3181
+ }
3182
+ pick(mask) {
3183
+ const shape = {};
3184
+ for (const key of util.objectKeys(mask)) {
3185
+ if (mask[key] && this.shape[key]) {
3186
+ shape[key] = this.shape[key];
3187
+ }
3188
+ }
3189
+ return new ZodObject({
3190
+ ...this._def,
3191
+ shape: () => shape
3192
+ });
3193
+ }
3194
+ omit(mask) {
3195
+ const shape = {};
3196
+ for (const key of util.objectKeys(this.shape)) {
3197
+ if (!mask[key]) {
3198
+ shape[key] = this.shape[key];
3199
+ }
3200
+ }
3201
+ return new ZodObject({
3202
+ ...this._def,
3203
+ shape: () => shape
3204
+ });
3205
+ }
3206
+ deepPartial() {
3207
+ return deepPartialify(this);
3208
+ }
3209
+ partial(mask) {
3210
+ const newShape = {};
3211
+ for (const key of util.objectKeys(this.shape)) {
3212
+ const fieldSchema = this.shape[key];
3213
+ if (mask && !mask[key]) {
3214
+ newShape[key] = fieldSchema;
3215
+ } else {
3216
+ newShape[key] = fieldSchema.optional();
3217
+ }
3218
+ }
3219
+ return new ZodObject({
3220
+ ...this._def,
3221
+ shape: () => newShape
3222
+ });
3223
+ }
3224
+ required(mask) {
3225
+ const newShape = {};
3226
+ for (const key of util.objectKeys(this.shape)) {
3227
+ if (mask && !mask[key]) {
3228
+ newShape[key] = this.shape[key];
3229
+ } else {
3230
+ const fieldSchema = this.shape[key];
3231
+ let newField = fieldSchema;
3232
+ while (newField instanceof ZodOptional) {
3233
+ newField = newField._def.innerType;
3234
+ }
3235
+ newShape[key] = newField;
3236
+ }
3237
+ }
3238
+ return new ZodObject({
3239
+ ...this._def,
3240
+ shape: () => newShape
3241
+ });
3242
+ }
3243
+ keyof() {
3244
+ return createZodEnum(util.objectKeys(this.shape));
3245
+ }
3246
+ }
3247
+ ZodObject.create = (shape, params) => {
3248
+ return new ZodObject({
3249
+ shape: () => shape,
3250
+ unknownKeys: "strip",
3251
+ catchall: ZodNever.create(),
3252
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3253
+ ...processCreateParams(params)
3254
+ });
3255
+ };
3256
+ ZodObject.strictCreate = (shape, params) => {
3257
+ return new ZodObject({
3258
+ shape: () => shape,
3259
+ unknownKeys: "strict",
3260
+ catchall: ZodNever.create(),
3261
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3262
+ ...processCreateParams(params)
3263
+ });
3264
+ };
3265
+ ZodObject.lazycreate = (shape, params) => {
3266
+ return new ZodObject({
3267
+ shape,
3268
+ unknownKeys: "strip",
3269
+ catchall: ZodNever.create(),
3270
+ typeName: ZodFirstPartyTypeKind.ZodObject,
3271
+ ...processCreateParams(params)
3272
+ });
3273
+ };
3274
+
3275
+ class ZodUnion extends ZodType {
3276
+ _parse(input) {
3277
+ const { ctx } = this._processInputParams(input);
3278
+ const options = this._def.options;
3279
+ function handleResults(results) {
3280
+ for (const result of results) {
3281
+ if (result.result.status === "valid") {
3282
+ return result.result;
3283
+ }
3284
+ }
3285
+ for (const result of results) {
3286
+ if (result.result.status === "dirty") {
3287
+ ctx.common.issues.push(...result.ctx.common.issues);
3288
+ return result.result;
3289
+ }
3290
+ }
3291
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
3292
+ addIssueToContext(ctx, {
3293
+ code: ZodIssueCode.invalid_union,
3294
+ unionErrors
3295
+ });
3296
+ return INVALID;
3297
+ }
3298
+ if (ctx.common.async) {
3299
+ return Promise.all(options.map(async (option) => {
3300
+ const childCtx = {
3301
+ ...ctx,
3302
+ common: {
3303
+ ...ctx.common,
3304
+ issues: []
3305
+ },
3306
+ parent: null
3307
+ };
3308
+ return {
3309
+ result: await option._parseAsync({
3310
+ data: ctx.data,
3311
+ path: ctx.path,
3312
+ parent: childCtx
3313
+ }),
3314
+ ctx: childCtx
3315
+ };
3316
+ })).then(handleResults);
3317
+ } else {
3318
+ let dirty = undefined;
3319
+ const issues = [];
3320
+ for (const option of options) {
3321
+ const childCtx = {
3322
+ ...ctx,
3323
+ common: {
3324
+ ...ctx.common,
3325
+ issues: []
3326
+ },
3327
+ parent: null
3328
+ };
3329
+ const result = option._parseSync({
3330
+ data: ctx.data,
3331
+ path: ctx.path,
3332
+ parent: childCtx
3333
+ });
3334
+ if (result.status === "valid") {
3335
+ return result;
3336
+ } else if (result.status === "dirty" && !dirty) {
3337
+ dirty = { result, ctx: childCtx };
3338
+ }
3339
+ if (childCtx.common.issues.length) {
3340
+ issues.push(childCtx.common.issues);
3341
+ }
3342
+ }
3343
+ if (dirty) {
3344
+ ctx.common.issues.push(...dirty.ctx.common.issues);
3345
+ return dirty.result;
3346
+ }
3347
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
3348
+ addIssueToContext(ctx, {
3349
+ code: ZodIssueCode.invalid_union,
3350
+ unionErrors
3351
+ });
3352
+ return INVALID;
3353
+ }
3354
+ }
3355
+ get options() {
3356
+ return this._def.options;
3357
+ }
3358
+ }
3359
+ ZodUnion.create = (types, params) => {
3360
+ return new ZodUnion({
3361
+ options: types,
3362
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
3363
+ ...processCreateParams(params)
3364
+ });
3365
+ };
3366
+ var getDiscriminator = (type) => {
3367
+ if (type instanceof ZodLazy) {
3368
+ return getDiscriminator(type.schema);
3369
+ } else if (type instanceof ZodEffects) {
3370
+ return getDiscriminator(type.innerType());
3371
+ } else if (type instanceof ZodLiteral) {
3372
+ return [type.value];
3373
+ } else if (type instanceof ZodEnum) {
3374
+ return type.options;
3375
+ } else if (type instanceof ZodNativeEnum) {
3376
+ return util.objectValues(type.enum);
3377
+ } else if (type instanceof ZodDefault) {
3378
+ return getDiscriminator(type._def.innerType);
3379
+ } else if (type instanceof ZodUndefined) {
3380
+ return [undefined];
3381
+ } else if (type instanceof ZodNull) {
3382
+ return [null];
3383
+ } else if (type instanceof ZodOptional) {
3384
+ return [undefined, ...getDiscriminator(type.unwrap())];
3385
+ } else if (type instanceof ZodNullable) {
3386
+ return [null, ...getDiscriminator(type.unwrap())];
3387
+ } else if (type instanceof ZodBranded) {
3388
+ return getDiscriminator(type.unwrap());
3389
+ } else if (type instanceof ZodReadonly) {
3390
+ return getDiscriminator(type.unwrap());
3391
+ } else if (type instanceof ZodCatch) {
3392
+ return getDiscriminator(type._def.innerType);
3393
+ } else {
3394
+ return [];
3395
+ }
3396
+ };
3397
+
3398
+ class ZodDiscriminatedUnion extends ZodType {
3399
+ _parse(input) {
3400
+ const { ctx } = this._processInputParams(input);
3401
+ if (ctx.parsedType !== ZodParsedType.object) {
3402
+ addIssueToContext(ctx, {
3403
+ code: ZodIssueCode.invalid_type,
3404
+ expected: ZodParsedType.object,
3405
+ received: ctx.parsedType
3406
+ });
3407
+ return INVALID;
3408
+ }
3409
+ const discriminator = this.discriminator;
3410
+ const discriminatorValue = ctx.data[discriminator];
3411
+ const option = this.optionsMap.get(discriminatorValue);
3412
+ if (!option) {
3413
+ addIssueToContext(ctx, {
3414
+ code: ZodIssueCode.invalid_union_discriminator,
3415
+ options: Array.from(this.optionsMap.keys()),
3416
+ path: [discriminator]
3417
+ });
3418
+ return INVALID;
3419
+ }
3420
+ if (ctx.common.async) {
3421
+ return option._parseAsync({
3422
+ data: ctx.data,
3423
+ path: ctx.path,
3424
+ parent: ctx
3425
+ });
3426
+ } else {
3427
+ return option._parseSync({
3428
+ data: ctx.data,
3429
+ path: ctx.path,
3430
+ parent: ctx
3431
+ });
3432
+ }
3433
+ }
3434
+ get discriminator() {
3435
+ return this._def.discriminator;
3436
+ }
3437
+ get options() {
3438
+ return this._def.options;
3439
+ }
3440
+ get optionsMap() {
3441
+ return this._def.optionsMap;
3442
+ }
3443
+ static create(discriminator, options, params) {
3444
+ const optionsMap = new Map;
3445
+ for (const type of options) {
3446
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3447
+ if (!discriminatorValues.length) {
3448
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3449
+ }
3450
+ for (const value of discriminatorValues) {
3451
+ if (optionsMap.has(value)) {
3452
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
3453
+ }
3454
+ optionsMap.set(value, type);
3455
+ }
3456
+ }
3457
+ return new ZodDiscriminatedUnion({
3458
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
3459
+ discriminator,
3460
+ options,
3461
+ optionsMap,
3462
+ ...processCreateParams(params)
3463
+ });
3464
+ }
3465
+ }
3466
+ function mergeValues(a, b) {
3467
+ const aType = getParsedType(a);
3468
+ const bType = getParsedType(b);
3469
+ if (a === b) {
3470
+ return { valid: true, data: a };
3471
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
3472
+ const bKeys = util.objectKeys(b);
3473
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
3474
+ const newObj = { ...a, ...b };
3475
+ for (const key of sharedKeys) {
3476
+ const sharedValue = mergeValues(a[key], b[key]);
3477
+ if (!sharedValue.valid) {
3478
+ return { valid: false };
3479
+ }
3480
+ newObj[key] = sharedValue.data;
3481
+ }
3482
+ return { valid: true, data: newObj };
3483
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
3484
+ if (a.length !== b.length) {
3485
+ return { valid: false };
3486
+ }
3487
+ const newArray = [];
3488
+ for (let index = 0;index < a.length; index++) {
3489
+ const itemA = a[index];
3490
+ const itemB = b[index];
3491
+ const sharedValue = mergeValues(itemA, itemB);
3492
+ if (!sharedValue.valid) {
3493
+ return { valid: false };
3494
+ }
3495
+ newArray.push(sharedValue.data);
3496
+ }
3497
+ return { valid: true, data: newArray };
3498
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
3499
+ return { valid: true, data: a };
3500
+ } else {
3501
+ return { valid: false };
3502
+ }
3503
+ }
3504
+
3505
+ class ZodIntersection extends ZodType {
3506
+ _parse(input) {
3507
+ const { status, ctx } = this._processInputParams(input);
3508
+ const handleParsed = (parsedLeft, parsedRight) => {
3509
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
3510
+ return INVALID;
3511
+ }
3512
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
3513
+ if (!merged.valid) {
3514
+ addIssueToContext(ctx, {
3515
+ code: ZodIssueCode.invalid_intersection_types
3516
+ });
3517
+ return INVALID;
3518
+ }
3519
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
3520
+ status.dirty();
3521
+ }
3522
+ return { status: status.value, value: merged.data };
3523
+ };
3524
+ if (ctx.common.async) {
3525
+ return Promise.all([
3526
+ this._def.left._parseAsync({
3527
+ data: ctx.data,
3528
+ path: ctx.path,
3529
+ parent: ctx
3530
+ }),
3531
+ this._def.right._parseAsync({
3532
+ data: ctx.data,
3533
+ path: ctx.path,
3534
+ parent: ctx
3535
+ })
3536
+ ]).then(([left, right]) => handleParsed(left, right));
3537
+ } else {
3538
+ return handleParsed(this._def.left._parseSync({
3539
+ data: ctx.data,
3540
+ path: ctx.path,
3541
+ parent: ctx
3542
+ }), this._def.right._parseSync({
3543
+ data: ctx.data,
3544
+ path: ctx.path,
3545
+ parent: ctx
3546
+ }));
3547
+ }
3548
+ }
3549
+ }
3550
+ ZodIntersection.create = (left, right, params) => {
3551
+ return new ZodIntersection({
3552
+ left,
3553
+ right,
3554
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
3555
+ ...processCreateParams(params)
3556
+ });
3557
+ };
3558
+
3559
+ class ZodTuple extends ZodType {
3560
+ _parse(input) {
3561
+ const { status, ctx } = this._processInputParams(input);
3562
+ if (ctx.parsedType !== ZodParsedType.array) {
3563
+ addIssueToContext(ctx, {
3564
+ code: ZodIssueCode.invalid_type,
3565
+ expected: ZodParsedType.array,
3566
+ received: ctx.parsedType
3567
+ });
3568
+ return INVALID;
3569
+ }
3570
+ if (ctx.data.length < this._def.items.length) {
3571
+ addIssueToContext(ctx, {
3572
+ code: ZodIssueCode.too_small,
3573
+ minimum: this._def.items.length,
3574
+ inclusive: true,
3575
+ exact: false,
3576
+ type: "array"
3577
+ });
3578
+ return INVALID;
3579
+ }
3580
+ const rest = this._def.rest;
3581
+ if (!rest && ctx.data.length > this._def.items.length) {
3582
+ addIssueToContext(ctx, {
3583
+ code: ZodIssueCode.too_big,
3584
+ maximum: this._def.items.length,
3585
+ inclusive: true,
3586
+ exact: false,
3587
+ type: "array"
3588
+ });
3589
+ status.dirty();
3590
+ }
3591
+ const items = [...ctx.data].map((item, itemIndex) => {
3592
+ const schema = this._def.items[itemIndex] || this._def.rest;
3593
+ if (!schema)
3594
+ return null;
3595
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
3596
+ }).filter((x) => !!x);
3597
+ if (ctx.common.async) {
3598
+ return Promise.all(items).then((results) => {
3599
+ return ParseStatus.mergeArray(status, results);
3600
+ });
3601
+ } else {
3602
+ return ParseStatus.mergeArray(status, items);
3603
+ }
3604
+ }
3605
+ get items() {
3606
+ return this._def.items;
3607
+ }
3608
+ rest(rest) {
3609
+ return new ZodTuple({
3610
+ ...this._def,
3611
+ rest
3612
+ });
3613
+ }
3614
+ }
3615
+ ZodTuple.create = (schemas, params) => {
3616
+ if (!Array.isArray(schemas)) {
3617
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
3618
+ }
3619
+ return new ZodTuple({
3620
+ items: schemas,
3621
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
3622
+ rest: null,
3623
+ ...processCreateParams(params)
3624
+ });
3625
+ };
3626
+
3627
+ class ZodRecord extends ZodType {
3628
+ get keySchema() {
3629
+ return this._def.keyType;
3630
+ }
3631
+ get valueSchema() {
3632
+ return this._def.valueType;
3633
+ }
3634
+ _parse(input) {
3635
+ const { status, ctx } = this._processInputParams(input);
3636
+ if (ctx.parsedType !== ZodParsedType.object) {
3637
+ addIssueToContext(ctx, {
3638
+ code: ZodIssueCode.invalid_type,
3639
+ expected: ZodParsedType.object,
3640
+ received: ctx.parsedType
3641
+ });
3642
+ return INVALID;
3643
+ }
3644
+ const pairs = [];
3645
+ const keyType = this._def.keyType;
3646
+ const valueType = this._def.valueType;
3647
+ for (const key in ctx.data) {
3648
+ pairs.push({
3649
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3650
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3651
+ alwaysSet: key in ctx.data
3652
+ });
3653
+ }
3654
+ if (ctx.common.async) {
3655
+ return ParseStatus.mergeObjectAsync(status, pairs);
3656
+ } else {
3657
+ return ParseStatus.mergeObjectSync(status, pairs);
3658
+ }
3659
+ }
3660
+ get element() {
3661
+ return this._def.valueType;
3662
+ }
3663
+ static create(first, second, third) {
3664
+ if (second instanceof ZodType) {
3665
+ return new ZodRecord({
3666
+ keyType: first,
3667
+ valueType: second,
3668
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3669
+ ...processCreateParams(third)
3670
+ });
3671
+ }
3672
+ return new ZodRecord({
3673
+ keyType: ZodString.create(),
3674
+ valueType: first,
3675
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
3676
+ ...processCreateParams(second)
3677
+ });
3678
+ }
3679
+ }
3680
+
3681
+ class ZodMap extends ZodType {
3682
+ get keySchema() {
3683
+ return this._def.keyType;
3684
+ }
3685
+ get valueSchema() {
3686
+ return this._def.valueType;
3687
+ }
3688
+ _parse(input) {
3689
+ const { status, ctx } = this._processInputParams(input);
3690
+ if (ctx.parsedType !== ZodParsedType.map) {
3691
+ addIssueToContext(ctx, {
3692
+ code: ZodIssueCode.invalid_type,
3693
+ expected: ZodParsedType.map,
3694
+ received: ctx.parsedType
3695
+ });
3696
+ return INVALID;
3697
+ }
3698
+ const keyType = this._def.keyType;
3699
+ const valueType = this._def.valueType;
3700
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
3701
+ return {
3702
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
3703
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
3704
+ };
3705
+ });
3706
+ if (ctx.common.async) {
3707
+ const finalMap = new Map;
3708
+ return Promise.resolve().then(async () => {
3709
+ for (const pair of pairs) {
3710
+ const key = await pair.key;
3711
+ const value = await pair.value;
3712
+ if (key.status === "aborted" || value.status === "aborted") {
3713
+ return INVALID;
3714
+ }
3715
+ if (key.status === "dirty" || value.status === "dirty") {
3716
+ status.dirty();
3717
+ }
3718
+ finalMap.set(key.value, value.value);
3719
+ }
3720
+ return { status: status.value, value: finalMap };
3721
+ });
3722
+ } else {
3723
+ const finalMap = new Map;
3724
+ for (const pair of pairs) {
3725
+ const key = pair.key;
3726
+ const value = pair.value;
3727
+ if (key.status === "aborted" || value.status === "aborted") {
3728
+ return INVALID;
3729
+ }
3730
+ if (key.status === "dirty" || value.status === "dirty") {
3731
+ status.dirty();
3732
+ }
3733
+ finalMap.set(key.value, value.value);
3734
+ }
3735
+ return { status: status.value, value: finalMap };
3736
+ }
3737
+ }
3738
+ }
3739
+ ZodMap.create = (keyType, valueType, params) => {
3740
+ return new ZodMap({
3741
+ valueType,
3742
+ keyType,
3743
+ typeName: ZodFirstPartyTypeKind.ZodMap,
3744
+ ...processCreateParams(params)
3745
+ });
3746
+ };
3747
+
3748
+ class ZodSet extends ZodType {
3749
+ _parse(input) {
3750
+ const { status, ctx } = this._processInputParams(input);
3751
+ if (ctx.parsedType !== ZodParsedType.set) {
3752
+ addIssueToContext(ctx, {
3753
+ code: ZodIssueCode.invalid_type,
3754
+ expected: ZodParsedType.set,
3755
+ received: ctx.parsedType
3756
+ });
3757
+ return INVALID;
3758
+ }
3759
+ const def = this._def;
3760
+ if (def.minSize !== null) {
3761
+ if (ctx.data.size < def.minSize.value) {
3762
+ addIssueToContext(ctx, {
3763
+ code: ZodIssueCode.too_small,
3764
+ minimum: def.minSize.value,
3765
+ type: "set",
3766
+ inclusive: true,
3767
+ exact: false,
3768
+ message: def.minSize.message
3769
+ });
3770
+ status.dirty();
3771
+ }
3772
+ }
3773
+ if (def.maxSize !== null) {
3774
+ if (ctx.data.size > def.maxSize.value) {
3775
+ addIssueToContext(ctx, {
3776
+ code: ZodIssueCode.too_big,
3777
+ maximum: def.maxSize.value,
3778
+ type: "set",
3779
+ inclusive: true,
3780
+ exact: false,
3781
+ message: def.maxSize.message
3782
+ });
3783
+ status.dirty();
3784
+ }
3785
+ }
3786
+ const valueType = this._def.valueType;
3787
+ function finalizeSet(elements2) {
3788
+ const parsedSet = new Set;
3789
+ for (const element of elements2) {
3790
+ if (element.status === "aborted")
3791
+ return INVALID;
3792
+ if (element.status === "dirty")
3793
+ status.dirty();
3794
+ parsedSet.add(element.value);
3795
+ }
3796
+ return { status: status.value, value: parsedSet };
3797
+ }
3798
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
3799
+ if (ctx.common.async) {
3800
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
3801
+ } else {
3802
+ return finalizeSet(elements);
3803
+ }
3804
+ }
3805
+ min(minSize, message) {
3806
+ return new ZodSet({
3807
+ ...this._def,
3808
+ minSize: { value: minSize, message: errorUtil.toString(message) }
3809
+ });
3810
+ }
3811
+ max(maxSize, message) {
3812
+ return new ZodSet({
3813
+ ...this._def,
3814
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
3815
+ });
3816
+ }
3817
+ size(size, message) {
3818
+ return this.min(size, message).max(size, message);
3819
+ }
3820
+ nonempty(message) {
3821
+ return this.min(1, message);
3822
+ }
3823
+ }
3824
+ ZodSet.create = (valueType, params) => {
3825
+ return new ZodSet({
3826
+ valueType,
3827
+ minSize: null,
3828
+ maxSize: null,
3829
+ typeName: ZodFirstPartyTypeKind.ZodSet,
3830
+ ...processCreateParams(params)
3831
+ });
3832
+ };
3833
+
3834
+ class ZodFunction extends ZodType {
3835
+ constructor() {
3836
+ super(...arguments);
3837
+ this.validate = this.implement;
3838
+ }
3839
+ _parse(input) {
3840
+ const { ctx } = this._processInputParams(input);
3841
+ if (ctx.parsedType !== ZodParsedType.function) {
3842
+ addIssueToContext(ctx, {
3843
+ code: ZodIssueCode.invalid_type,
3844
+ expected: ZodParsedType.function,
3845
+ received: ctx.parsedType
3846
+ });
3847
+ return INVALID;
3848
+ }
3849
+ function makeArgsIssue(args, error) {
3850
+ return makeIssue({
3851
+ data: args,
3852
+ path: ctx.path,
3853
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3854
+ issueData: {
3855
+ code: ZodIssueCode.invalid_arguments,
3856
+ argumentsError: error
3857
+ }
3858
+ });
3859
+ }
3860
+ function makeReturnsIssue(returns, error) {
3861
+ return makeIssue({
3862
+ data: returns,
3863
+ path: ctx.path,
3864
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
3865
+ issueData: {
3866
+ code: ZodIssueCode.invalid_return_type,
3867
+ returnTypeError: error
3868
+ }
3869
+ });
3870
+ }
3871
+ const params = { errorMap: ctx.common.contextualErrorMap };
3872
+ const fn = ctx.data;
3873
+ if (this._def.returns instanceof ZodPromise) {
3874
+ const me = this;
3875
+ return OK(async function(...args) {
3876
+ const error = new ZodError([]);
3877
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3878
+ error.addIssue(makeArgsIssue(args, e));
3879
+ throw error;
3880
+ });
3881
+ const result = await Reflect.apply(fn, this, parsedArgs);
3882
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3883
+ error.addIssue(makeReturnsIssue(result, e));
3884
+ throw error;
3885
+ });
3886
+ return parsedReturns;
3887
+ });
3888
+ } else {
3889
+ const me = this;
3890
+ return OK(function(...args) {
3891
+ const parsedArgs = me._def.args.safeParse(args, params);
3892
+ if (!parsedArgs.success) {
3893
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3894
+ }
3895
+ const result = Reflect.apply(fn, this, parsedArgs.data);
3896
+ const parsedReturns = me._def.returns.safeParse(result, params);
3897
+ if (!parsedReturns.success) {
3898
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3899
+ }
3900
+ return parsedReturns.data;
3901
+ });
3902
+ }
3903
+ }
3904
+ parameters() {
3905
+ return this._def.args;
3906
+ }
3907
+ returnType() {
3908
+ return this._def.returns;
3909
+ }
3910
+ args(...items) {
3911
+ return new ZodFunction({
3912
+ ...this._def,
3913
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
3914
+ });
3915
+ }
3916
+ returns(returnType) {
3917
+ return new ZodFunction({
3918
+ ...this._def,
3919
+ returns: returnType
3920
+ });
3921
+ }
3922
+ implement(func) {
3923
+ const validatedFunc = this.parse(func);
3924
+ return validatedFunc;
3925
+ }
3926
+ strictImplement(func) {
3927
+ const validatedFunc = this.parse(func);
3928
+ return validatedFunc;
3929
+ }
3930
+ static create(args, returns, params) {
3931
+ return new ZodFunction({
3932
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3933
+ returns: returns || ZodUnknown.create(),
3934
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
3935
+ ...processCreateParams(params)
3936
+ });
3937
+ }
3938
+ }
3939
+
3940
+ class ZodLazy extends ZodType {
3941
+ get schema() {
3942
+ return this._def.getter();
3943
+ }
3944
+ _parse(input) {
3945
+ const { ctx } = this._processInputParams(input);
3946
+ const lazySchema = this._def.getter();
3947
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3948
+ }
3949
+ }
3950
+ ZodLazy.create = (getter, params) => {
3951
+ return new ZodLazy({
3952
+ getter,
3953
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3954
+ ...processCreateParams(params)
3955
+ });
3956
+ };
3957
+
3958
+ class ZodLiteral extends ZodType {
3959
+ _parse(input) {
3960
+ if (input.data !== this._def.value) {
3961
+ const ctx = this._getOrReturnCtx(input);
3962
+ addIssueToContext(ctx, {
3963
+ received: ctx.data,
3964
+ code: ZodIssueCode.invalid_literal,
3965
+ expected: this._def.value
3966
+ });
3967
+ return INVALID;
3968
+ }
3969
+ return { status: "valid", value: input.data };
3970
+ }
3971
+ get value() {
3972
+ return this._def.value;
3973
+ }
3974
+ }
3975
+ ZodLiteral.create = (value, params) => {
3976
+ return new ZodLiteral({
3977
+ value,
3978
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3979
+ ...processCreateParams(params)
3980
+ });
3981
+ };
3982
+ function createZodEnum(values, params) {
3983
+ return new ZodEnum({
3984
+ values,
3985
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3986
+ ...processCreateParams(params)
3987
+ });
3988
+ }
3989
+
3990
+ class ZodEnum extends ZodType {
3991
+ _parse(input) {
3992
+ if (typeof input.data !== "string") {
3993
+ const ctx = this._getOrReturnCtx(input);
3994
+ const expectedValues = this._def.values;
3995
+ addIssueToContext(ctx, {
3996
+ expected: util.joinValues(expectedValues),
3997
+ received: ctx.parsedType,
3998
+ code: ZodIssueCode.invalid_type
3999
+ });
4000
+ return INVALID;
4001
+ }
4002
+ if (!this._cache) {
4003
+ this._cache = new Set(this._def.values);
4004
+ }
4005
+ if (!this._cache.has(input.data)) {
4006
+ const ctx = this._getOrReturnCtx(input);
4007
+ const expectedValues = this._def.values;
4008
+ addIssueToContext(ctx, {
4009
+ received: ctx.data,
4010
+ code: ZodIssueCode.invalid_enum_value,
4011
+ options: expectedValues
4012
+ });
4013
+ return INVALID;
4014
+ }
4015
+ return OK(input.data);
4016
+ }
4017
+ get options() {
4018
+ return this._def.values;
4019
+ }
4020
+ get enum() {
4021
+ const enumValues = {};
4022
+ for (const val of this._def.values) {
4023
+ enumValues[val] = val;
4024
+ }
4025
+ return enumValues;
4026
+ }
4027
+ get Values() {
4028
+ const enumValues = {};
4029
+ for (const val of this._def.values) {
4030
+ enumValues[val] = val;
4031
+ }
4032
+ return enumValues;
4033
+ }
4034
+ get Enum() {
4035
+ const enumValues = {};
4036
+ for (const val of this._def.values) {
4037
+ enumValues[val] = val;
4038
+ }
4039
+ return enumValues;
4040
+ }
4041
+ extract(values, newDef = this._def) {
4042
+ return ZodEnum.create(values, {
4043
+ ...this._def,
4044
+ ...newDef
4045
+ });
4046
+ }
4047
+ exclude(values, newDef = this._def) {
4048
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
4049
+ ...this._def,
4050
+ ...newDef
4051
+ });
4052
+ }
4053
+ }
4054
+ ZodEnum.create = createZodEnum;
4055
+
4056
+ class ZodNativeEnum extends ZodType {
4057
+ _parse(input) {
4058
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
4059
+ const ctx = this._getOrReturnCtx(input);
4060
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
4061
+ const expectedValues = util.objectValues(nativeEnumValues);
4062
+ addIssueToContext(ctx, {
4063
+ expected: util.joinValues(expectedValues),
4064
+ received: ctx.parsedType,
4065
+ code: ZodIssueCode.invalid_type
4066
+ });
4067
+ return INVALID;
4068
+ }
4069
+ if (!this._cache) {
4070
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
4071
+ }
4072
+ if (!this._cache.has(input.data)) {
4073
+ const expectedValues = util.objectValues(nativeEnumValues);
4074
+ addIssueToContext(ctx, {
4075
+ received: ctx.data,
4076
+ code: ZodIssueCode.invalid_enum_value,
4077
+ options: expectedValues
4078
+ });
4079
+ return INVALID;
4080
+ }
4081
+ return OK(input.data);
4082
+ }
4083
+ get enum() {
4084
+ return this._def.values;
4085
+ }
4086
+ }
4087
+ ZodNativeEnum.create = (values, params) => {
4088
+ return new ZodNativeEnum({
4089
+ values,
4090
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
4091
+ ...processCreateParams(params)
4092
+ });
4093
+ };
4094
+
4095
+ class ZodPromise extends ZodType {
4096
+ unwrap() {
4097
+ return this._def.type;
4098
+ }
4099
+ _parse(input) {
4100
+ const { ctx } = this._processInputParams(input);
4101
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
4102
+ addIssueToContext(ctx, {
4103
+ code: ZodIssueCode.invalid_type,
4104
+ expected: ZodParsedType.promise,
4105
+ received: ctx.parsedType
4106
+ });
4107
+ return INVALID;
4108
+ }
4109
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
4110
+ return OK(promisified.then((data) => {
4111
+ return this._def.type.parseAsync(data, {
4112
+ path: ctx.path,
4113
+ errorMap: ctx.common.contextualErrorMap
4114
+ });
4115
+ }));
4116
+ }
4117
+ }
4118
+ ZodPromise.create = (schema, params) => {
4119
+ return new ZodPromise({
4120
+ type: schema,
4121
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
4122
+ ...processCreateParams(params)
4123
+ });
4124
+ };
590
4125
 
4126
+ class ZodEffects extends ZodType {
4127
+ innerType() {
4128
+ return this._def.schema;
4129
+ }
4130
+ sourceType() {
4131
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
4132
+ }
4133
+ _parse(input) {
4134
+ const { status, ctx } = this._processInputParams(input);
4135
+ const effect = this._def.effect || null;
4136
+ const checkCtx = {
4137
+ addIssue: (arg) => {
4138
+ addIssueToContext(ctx, arg);
4139
+ if (arg.fatal) {
4140
+ status.abort();
4141
+ } else {
4142
+ status.dirty();
4143
+ }
4144
+ },
4145
+ get path() {
4146
+ return ctx.path;
4147
+ }
4148
+ };
4149
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
4150
+ if (effect.type === "preprocess") {
4151
+ const processed = effect.transform(ctx.data, checkCtx);
4152
+ if (ctx.common.async) {
4153
+ return Promise.resolve(processed).then(async (processed2) => {
4154
+ if (status.value === "aborted")
4155
+ return INVALID;
4156
+ const result = await this._def.schema._parseAsync({
4157
+ data: processed2,
4158
+ path: ctx.path,
4159
+ parent: ctx
4160
+ });
4161
+ if (result.status === "aborted")
4162
+ return INVALID;
4163
+ if (result.status === "dirty")
4164
+ return DIRTY(result.value);
4165
+ if (status.value === "dirty")
4166
+ return DIRTY(result.value);
4167
+ return result;
4168
+ });
4169
+ } else {
4170
+ if (status.value === "aborted")
4171
+ return INVALID;
4172
+ const result = this._def.schema._parseSync({
4173
+ data: processed,
4174
+ path: ctx.path,
4175
+ parent: ctx
4176
+ });
4177
+ if (result.status === "aborted")
4178
+ return INVALID;
4179
+ if (result.status === "dirty")
4180
+ return DIRTY(result.value);
4181
+ if (status.value === "dirty")
4182
+ return DIRTY(result.value);
4183
+ return result;
4184
+ }
4185
+ }
4186
+ if (effect.type === "refinement") {
4187
+ const executeRefinement = (acc) => {
4188
+ const result = effect.refinement(acc, checkCtx);
4189
+ if (ctx.common.async) {
4190
+ return Promise.resolve(result);
4191
+ }
4192
+ if (result instanceof Promise) {
4193
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
4194
+ }
4195
+ return acc;
4196
+ };
4197
+ if (ctx.common.async === false) {
4198
+ const inner = this._def.schema._parseSync({
4199
+ data: ctx.data,
4200
+ path: ctx.path,
4201
+ parent: ctx
4202
+ });
4203
+ if (inner.status === "aborted")
4204
+ return INVALID;
4205
+ if (inner.status === "dirty")
4206
+ status.dirty();
4207
+ executeRefinement(inner.value);
4208
+ return { status: status.value, value: inner.value };
4209
+ } else {
4210
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
4211
+ if (inner.status === "aborted")
4212
+ return INVALID;
4213
+ if (inner.status === "dirty")
4214
+ status.dirty();
4215
+ return executeRefinement(inner.value).then(() => {
4216
+ return { status: status.value, value: inner.value };
4217
+ });
4218
+ });
4219
+ }
4220
+ }
4221
+ if (effect.type === "transform") {
4222
+ if (ctx.common.async === false) {
4223
+ const base = this._def.schema._parseSync({
4224
+ data: ctx.data,
4225
+ path: ctx.path,
4226
+ parent: ctx
4227
+ });
4228
+ if (!isValid(base))
4229
+ return INVALID;
4230
+ const result = effect.transform(base.value, checkCtx);
4231
+ if (result instanceof Promise) {
4232
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
4233
+ }
4234
+ return { status: status.value, value: result };
4235
+ } else {
4236
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
4237
+ if (!isValid(base))
4238
+ return INVALID;
4239
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
4240
+ status: status.value,
4241
+ value: result
4242
+ }));
4243
+ });
4244
+ }
4245
+ }
4246
+ util.assertNever(effect);
4247
+ }
4248
+ }
4249
+ ZodEffects.create = (schema, effect, params) => {
4250
+ return new ZodEffects({
4251
+ schema,
4252
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4253
+ effect,
4254
+ ...processCreateParams(params)
4255
+ });
4256
+ };
4257
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
4258
+ return new ZodEffects({
4259
+ schema,
4260
+ effect: { type: "preprocess", transform: preprocess },
4261
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
4262
+ ...processCreateParams(params)
4263
+ });
4264
+ };
4265
+ class ZodOptional extends ZodType {
4266
+ _parse(input) {
4267
+ const parsedType = this._getType(input);
4268
+ if (parsedType === ZodParsedType.undefined) {
4269
+ return OK(undefined);
4270
+ }
4271
+ return this._def.innerType._parse(input);
4272
+ }
4273
+ unwrap() {
4274
+ return this._def.innerType;
4275
+ }
4276
+ }
4277
+ ZodOptional.create = (type, params) => {
4278
+ return new ZodOptional({
4279
+ innerType: type,
4280
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
4281
+ ...processCreateParams(params)
4282
+ });
4283
+ };
4284
+
4285
+ class ZodNullable extends ZodType {
4286
+ _parse(input) {
4287
+ const parsedType = this._getType(input);
4288
+ if (parsedType === ZodParsedType.null) {
4289
+ return OK(null);
4290
+ }
4291
+ return this._def.innerType._parse(input);
4292
+ }
4293
+ unwrap() {
4294
+ return this._def.innerType;
4295
+ }
4296
+ }
4297
+ ZodNullable.create = (type, params) => {
4298
+ return new ZodNullable({
4299
+ innerType: type,
4300
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
4301
+ ...processCreateParams(params)
4302
+ });
4303
+ };
4304
+
4305
+ class ZodDefault extends ZodType {
4306
+ _parse(input) {
4307
+ const { ctx } = this._processInputParams(input);
4308
+ let data = ctx.data;
4309
+ if (ctx.parsedType === ZodParsedType.undefined) {
4310
+ data = this._def.defaultValue();
4311
+ }
4312
+ return this._def.innerType._parse({
4313
+ data,
4314
+ path: ctx.path,
4315
+ parent: ctx
4316
+ });
4317
+ }
4318
+ removeDefault() {
4319
+ return this._def.innerType;
4320
+ }
4321
+ }
4322
+ ZodDefault.create = (type, params) => {
4323
+ return new ZodDefault({
4324
+ innerType: type,
4325
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
4326
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
4327
+ ...processCreateParams(params)
4328
+ });
4329
+ };
4330
+
4331
+ class ZodCatch extends ZodType {
4332
+ _parse(input) {
4333
+ const { ctx } = this._processInputParams(input);
4334
+ const newCtx = {
4335
+ ...ctx,
4336
+ common: {
4337
+ ...ctx.common,
4338
+ issues: []
4339
+ }
4340
+ };
4341
+ const result = this._def.innerType._parse({
4342
+ data: newCtx.data,
4343
+ path: newCtx.path,
4344
+ parent: {
4345
+ ...newCtx
4346
+ }
4347
+ });
4348
+ if (isAsync(result)) {
4349
+ return result.then((result2) => {
4350
+ return {
4351
+ status: "valid",
4352
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
4353
+ get error() {
4354
+ return new ZodError(newCtx.common.issues);
4355
+ },
4356
+ input: newCtx.data
4357
+ })
4358
+ };
4359
+ });
4360
+ } else {
4361
+ return {
4362
+ status: "valid",
4363
+ value: result.status === "valid" ? result.value : this._def.catchValue({
4364
+ get error() {
4365
+ return new ZodError(newCtx.common.issues);
4366
+ },
4367
+ input: newCtx.data
4368
+ })
4369
+ };
4370
+ }
4371
+ }
4372
+ removeCatch() {
4373
+ return this._def.innerType;
4374
+ }
4375
+ }
4376
+ ZodCatch.create = (type, params) => {
4377
+ return new ZodCatch({
4378
+ innerType: type,
4379
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
4380
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
4381
+ ...processCreateParams(params)
4382
+ });
4383
+ };
4384
+
4385
+ class ZodNaN extends ZodType {
4386
+ _parse(input) {
4387
+ const parsedType = this._getType(input);
4388
+ if (parsedType !== ZodParsedType.nan) {
4389
+ const ctx = this._getOrReturnCtx(input);
4390
+ addIssueToContext(ctx, {
4391
+ code: ZodIssueCode.invalid_type,
4392
+ expected: ZodParsedType.nan,
4393
+ received: ctx.parsedType
4394
+ });
4395
+ return INVALID;
4396
+ }
4397
+ return { status: "valid", value: input.data };
4398
+ }
4399
+ }
4400
+ ZodNaN.create = (params) => {
4401
+ return new ZodNaN({
4402
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
4403
+ ...processCreateParams(params)
4404
+ });
4405
+ };
4406
+ var BRAND = Symbol("zod_brand");
4407
+
4408
+ class ZodBranded extends ZodType {
4409
+ _parse(input) {
4410
+ const { ctx } = this._processInputParams(input);
4411
+ const data = ctx.data;
4412
+ return this._def.type._parse({
4413
+ data,
4414
+ path: ctx.path,
4415
+ parent: ctx
4416
+ });
4417
+ }
4418
+ unwrap() {
4419
+ return this._def.type;
4420
+ }
4421
+ }
4422
+
4423
+ class ZodPipeline extends ZodType {
4424
+ _parse(input) {
4425
+ const { status, ctx } = this._processInputParams(input);
4426
+ if (ctx.common.async) {
4427
+ const handleAsync = async () => {
4428
+ const inResult = await this._def.in._parseAsync({
4429
+ data: ctx.data,
4430
+ path: ctx.path,
4431
+ parent: ctx
4432
+ });
4433
+ if (inResult.status === "aborted")
4434
+ return INVALID;
4435
+ if (inResult.status === "dirty") {
4436
+ status.dirty();
4437
+ return DIRTY(inResult.value);
4438
+ } else {
4439
+ return this._def.out._parseAsync({
4440
+ data: inResult.value,
4441
+ path: ctx.path,
4442
+ parent: ctx
4443
+ });
4444
+ }
4445
+ };
4446
+ return handleAsync();
4447
+ } else {
4448
+ const inResult = this._def.in._parseSync({
4449
+ data: ctx.data,
4450
+ path: ctx.path,
4451
+ parent: ctx
4452
+ });
4453
+ if (inResult.status === "aborted")
4454
+ return INVALID;
4455
+ if (inResult.status === "dirty") {
4456
+ status.dirty();
4457
+ return {
4458
+ status: "dirty",
4459
+ value: inResult.value
4460
+ };
4461
+ } else {
4462
+ return this._def.out._parseSync({
4463
+ data: inResult.value,
4464
+ path: ctx.path,
4465
+ parent: ctx
4466
+ });
4467
+ }
4468
+ }
4469
+ }
4470
+ static create(a, b) {
4471
+ return new ZodPipeline({
4472
+ in: a,
4473
+ out: b,
4474
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
4475
+ });
4476
+ }
4477
+ }
4478
+
4479
+ class ZodReadonly extends ZodType {
4480
+ _parse(input) {
4481
+ const result = this._def.innerType._parse(input);
4482
+ const freeze = (data) => {
4483
+ if (isValid(data)) {
4484
+ data.value = Object.freeze(data.value);
4485
+ }
4486
+ return data;
4487
+ };
4488
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
4489
+ }
4490
+ unwrap() {
4491
+ return this._def.innerType;
4492
+ }
4493
+ }
4494
+ ZodReadonly.create = (type, params) => {
4495
+ return new ZodReadonly({
4496
+ innerType: type,
4497
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
4498
+ ...processCreateParams(params)
4499
+ });
4500
+ };
4501
+ function cleanParams(params, data) {
4502
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
4503
+ const p2 = typeof p === "string" ? { message: p } : p;
4504
+ return p2;
4505
+ }
4506
+ function custom(check, _params = {}, fatal) {
4507
+ if (check)
4508
+ return ZodAny.create().superRefine((data, ctx) => {
4509
+ const r = check(data);
4510
+ if (r instanceof Promise) {
4511
+ return r.then((r2) => {
4512
+ if (!r2) {
4513
+ const params = cleanParams(_params, data);
4514
+ const _fatal = params.fatal ?? fatal ?? true;
4515
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4516
+ }
4517
+ });
4518
+ }
4519
+ if (!r) {
4520
+ const params = cleanParams(_params, data);
4521
+ const _fatal = params.fatal ?? fatal ?? true;
4522
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
4523
+ }
4524
+ return;
4525
+ });
4526
+ return ZodAny.create();
4527
+ }
4528
+ var late = {
4529
+ object: ZodObject.lazycreate
4530
+ };
4531
+ var ZodFirstPartyTypeKind;
4532
+ (function(ZodFirstPartyTypeKind2) {
4533
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
4534
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
4535
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
4536
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
4537
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
4538
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
4539
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
4540
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
4541
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
4542
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
4543
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
4544
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
4545
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
4546
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
4547
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
4548
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
4549
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
4550
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
4551
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
4552
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
4553
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
4554
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
4555
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
4556
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
4557
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
4558
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
4559
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
4560
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
4561
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
4562
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
4563
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
4564
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
4565
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
4566
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
4567
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
4568
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
4569
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
4570
+ var instanceOfType = (cls, params = {
4571
+ message: `Input not instance of ${cls.name}`
4572
+ }) => custom((data) => data instanceof cls, params);
4573
+ var stringType = ZodString.create;
4574
+ var numberType = ZodNumber.create;
4575
+ var nanType = ZodNaN.create;
4576
+ var bigIntType = ZodBigInt.create;
4577
+ var booleanType = ZodBoolean.create;
4578
+ var dateType = ZodDate.create;
4579
+ var symbolType = ZodSymbol.create;
4580
+ var undefinedType = ZodUndefined.create;
4581
+ var nullType = ZodNull.create;
4582
+ var anyType = ZodAny.create;
4583
+ var unknownType = ZodUnknown.create;
4584
+ var neverType = ZodNever.create;
4585
+ var voidType = ZodVoid.create;
4586
+ var arrayType = ZodArray.create;
4587
+ var objectType = ZodObject.create;
4588
+ var strictObjectType = ZodObject.strictCreate;
4589
+ var unionType = ZodUnion.create;
4590
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
4591
+ var intersectionType = ZodIntersection.create;
4592
+ var tupleType = ZodTuple.create;
4593
+ var recordType = ZodRecord.create;
4594
+ var mapType = ZodMap.create;
4595
+ var setType = ZodSet.create;
4596
+ var functionType = ZodFunction.create;
4597
+ var lazyType = ZodLazy.create;
4598
+ var literalType = ZodLiteral.create;
4599
+ var enumType = ZodEnum.create;
4600
+ var nativeEnumType = ZodNativeEnum.create;
4601
+ var promiseType = ZodPromise.create;
4602
+ var effectsType = ZodEffects.create;
4603
+ var optionalType = ZodOptional.create;
4604
+ var nullableType = ZodNullable.create;
4605
+ var preprocessType = ZodEffects.createWithPreprocess;
4606
+ var pipelineType = ZodPipeline.create;
4607
+ var ostring = () => stringType().optional();
4608
+ var onumber = () => numberType().optional();
4609
+ var oboolean = () => booleanType().optional();
4610
+ var coerce = {
4611
+ string: (arg) => ZodString.create({ ...arg, coerce: true }),
4612
+ number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
4613
+ boolean: (arg) => ZodBoolean.create({
4614
+ ...arg,
4615
+ coerce: true
4616
+ }),
4617
+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
4618
+ date: (arg) => ZodDate.create({ ...arg, coerce: true })
4619
+ };
4620
+ var NEVER = INVALID;
4621
+ // src/config/schema.ts
4622
+ var AgentNameSchema = exports_external.enum([
4623
+ "explorer",
4624
+ "librarian",
4625
+ "oracle",
4626
+ "ui-planner"
4627
+ ]);
4628
+ var AgentOverrideConfigSchema = exports_external.object({
4629
+ model: exports_external.string().optional()
4630
+ });
4631
+ var AgentOverridesSchema = exports_external.object({
4632
+ explorer: AgentOverrideConfigSchema.optional(),
4633
+ librarian: AgentOverrideConfigSchema.optional(),
4634
+ oracle: AgentOverrideConfigSchema.optional(),
4635
+ "ui-planner": AgentOverrideConfigSchema.optional()
4636
+ });
4637
+ var AyushOpenCodeConfigSchema = exports_external.object({
4638
+ $schema: exports_external.string().optional(),
4639
+ agents: AgentOverridesSchema.optional(),
4640
+ disabled_agents: exports_external.array(AgentNameSchema).optional()
4641
+ });
4642
+ // src/config/loader.ts
4643
+ import * as fs from "fs";
4644
+ import * as path from "path";
4645
+ function getUserConfigDir() {
4646
+ if (process.platform === "win32") {
4647
+ return process.env.APPDATA || path.join(process.env.USERPROFILE || "", "AppData", "Roaming");
4648
+ }
4649
+ return process.env.XDG_CONFIG_HOME || path.join(process.env.HOME || "", ".config");
4650
+ }
4651
+ function loadConfigFromPath(configPath) {
4652
+ try {
4653
+ if (fs.existsSync(configPath)) {
4654
+ const content = fs.readFileSync(configPath, "utf-8");
4655
+ const rawConfig = JSON.parse(content);
4656
+ const result = AyushOpenCodeConfigSchema.safeParse(rawConfig);
4657
+ if (!result.success) {
4658
+ console.warn(`[ayush-opencode] Config validation error in ${configPath}:`, result.error.issues);
4659
+ return null;
4660
+ }
4661
+ return result.data;
4662
+ }
4663
+ } catch (err) {
4664
+ console.warn(`[ayush-opencode] Error loading config from ${configPath}:`, err);
4665
+ }
4666
+ return null;
4667
+ }
4668
+ function mergeConfigs(base, override) {
4669
+ return {
4670
+ ...base,
4671
+ ...override,
4672
+ agents: {
4673
+ ...base.agents,
4674
+ ...override.agents
4675
+ },
4676
+ disabled_agents: [
4677
+ ...new Set([
4678
+ ...base.disabled_agents ?? [],
4679
+ ...override.disabled_agents ?? []
4680
+ ])
4681
+ ]
4682
+ };
4683
+ }
4684
+ function loadPluginConfig(projectDirectory) {
4685
+ const userConfigPath = path.join(getUserConfigDir(), "opencode", "ayush-opencode.json");
4686
+ const projectConfigPath = path.join(projectDirectory, ".opencode", "ayush-opencode.json");
4687
+ let config = loadConfigFromPath(userConfigPath) ?? {};
4688
+ const projectConfig = loadConfigFromPath(projectConfigPath);
4689
+ if (projectConfig) {
4690
+ config = mergeConfigs(config, projectConfig);
4691
+ }
4692
+ return config;
4693
+ }
591
4694
  // src/index.ts
592
4695
  var AyushOpenCodePlugin = async (ctx) => {
4696
+ const pluginConfig = loadPluginConfig(ctx.directory);
4697
+ const disabledAgents = new Set(pluginConfig.disabled_agents ?? []);
4698
+ const applyModelOverride = (agentName, baseAgent) => {
4699
+ const override = pluginConfig.agents?.[agentName];
4700
+ if (override?.model) {
4701
+ return { ...baseAgent, model: override.model };
4702
+ }
4703
+ return baseAgent;
4704
+ };
593
4705
  return {
594
- async config(config) {
4706
+ config: async (config) => {
595
4707
  config.agent = config.agent ?? {};
596
- config.agent.explorer = explorerAgent;
597
- config.agent.librarian = librarianAgent;
598
- config.agent.oracle = oracleAgent;
599
- config.agent["ui-planner"] = uiPlannerAgent;
4708
+ if (!disabledAgents.has("explorer")) {
4709
+ config.agent.explorer = applyModelOverride("explorer", explorerAgent);
4710
+ }
4711
+ if (!disabledAgents.has("librarian")) {
4712
+ config.agent.librarian = applyModelOverride("librarian", librarianAgent);
4713
+ }
4714
+ if (!disabledAgents.has("oracle")) {
4715
+ config.agent.oracle = applyModelOverride("oracle", oracleAgent);
4716
+ }
4717
+ if (!disabledAgents.has("ui-planner")) {
4718
+ config.agent["ui-planner"] = applyModelOverride("ui-planner", uiPlannerAgent);
4719
+ }
600
4720
  if (config.agent.build) {
601
4721
  const existingPrompt = config.agent.build.prompt ?? "";
602
4722
  config.agent.build.prompt = existingPrompt + ORCHESTRATION_PROMPT;
@@ -610,11 +4730,5 @@ var AyushOpenCodePlugin = async (ctx) => {
610
4730
  };
611
4731
  var src_default = AyushOpenCodePlugin;
612
4732
  export {
613
- uiPlannerAgent,
614
- oracleAgent,
615
- librarianAgent,
616
- explorerAgent,
617
- src_default as default,
618
- ORCHESTRATION_PROMPT,
619
- AyushOpenCodePlugin
4733
+ src_default as default
620
4734
  };