zod 3.25.12-alpha.0 → 3.25.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/package.json +16 -17
  2. package/dist/types/index.d.ts +0 -3
  3. package/dist/types/index.js +0 -3
  4. package/dist/types/v3/ZodError.d.ts +0 -164
  5. package/dist/types/v3/ZodError.js +0 -132
  6. package/dist/types/v3/benchmarks/datetime.d.ts +0 -5
  7. package/dist/types/v3/benchmarks/datetime.js +0 -49
  8. package/dist/types/v3/benchmarks/discriminatedUnion.d.ts +0 -5
  9. package/dist/types/v3/benchmarks/discriminatedUnion.js +0 -74
  10. package/dist/types/v3/benchmarks/index.d.ts +0 -1
  11. package/dist/types/v3/benchmarks/index.js +0 -54
  12. package/dist/types/v3/benchmarks/ipv4.d.ts +0 -5
  13. package/dist/types/v3/benchmarks/ipv4.js +0 -49
  14. package/dist/types/v3/benchmarks/object.d.ts +0 -5
  15. package/dist/types/v3/benchmarks/object.js +0 -65
  16. package/dist/types/v3/benchmarks/primitives.d.ts +0 -5
  17. package/dist/types/v3/benchmarks/primitives.js +0 -154
  18. package/dist/types/v3/benchmarks/realworld.d.ts +0 -5
  19. package/dist/types/v3/benchmarks/realworld.js +0 -51
  20. package/dist/types/v3/benchmarks/string.d.ts +0 -5
  21. package/dist/types/v3/benchmarks/string.js +0 -50
  22. package/dist/types/v3/benchmarks/union.d.ts +0 -5
  23. package/dist/types/v3/benchmarks/union.js +0 -74
  24. package/dist/types/v3/errors.d.ts +0 -5
  25. package/dist/types/v3/errors.js +0 -9
  26. package/dist/types/v3/external.d.ts +0 -6
  27. package/dist/types/v3/external.js +0 -6
  28. package/dist/types/v3/helpers/enumUtil.d.ts +0 -8
  29. package/dist/types/v3/helpers/enumUtil.js +0 -1
  30. package/dist/types/v3/helpers/errorUtil.d.ts +0 -9
  31. package/dist/types/v3/helpers/errorUtil.js +0 -6
  32. package/dist/types/v3/helpers/parseUtil.d.ts +0 -78
  33. package/dist/types/v3/helpers/parseUtil.js +0 -109
  34. package/dist/types/v3/helpers/partialUtil.d.ts +0 -8
  35. package/dist/types/v3/helpers/partialUtil.js +0 -1
  36. package/dist/types/v3/helpers/typeAliases.d.ts +0 -2
  37. package/dist/types/v3/helpers/typeAliases.js +0 -1
  38. package/dist/types/v3/helpers/util.d.ts +0 -85
  39. package/dist/types/v3/helpers/util.js +0 -133
  40. package/dist/types/v3/index.d.ts +0 -4
  41. package/dist/types/v3/index.js +0 -4
  42. package/dist/types/v3/locales/en.d.ts +0 -3
  43. package/dist/types/v3/locales/en.js +0 -107
  44. package/dist/types/v3/standard-schema.d.ts +0 -102
  45. package/dist/types/v3/standard-schema.js +0 -1
  46. package/dist/types/v3/tests/Mocker.d.ts +0 -17
  47. package/dist/types/v3/tests/Mocker.js +0 -53
  48. package/dist/types/v3/tests/language-server.source.d.ts +0 -70
  49. package/dist/types/v3/tests/language-server.source.js +0 -45
  50. package/dist/types/v3/types.d.ts +0 -1031
  51. package/dist/types/v3/types.js +0 -3713
  52. package/dist/types/v4/classic/checks.d.ts +0 -1
  53. package/dist/types/v4/classic/checks.js +0 -1
  54. package/dist/types/v4/classic/coerce.d.ts +0 -17
  55. package/dist/types/v4/classic/coerce.js +0 -17
  56. package/dist/types/v4/classic/compat.d.ts +0 -48
  57. package/dist/types/v4/classic/compat.js +0 -33
  58. package/dist/types/v4/classic/errors.d.ts +0 -30
  59. package/dist/types/v4/classic/errors.js +0 -41
  60. package/dist/types/v4/classic/external.d.ts +0 -8
  61. package/dist/types/v4/classic/external.js +0 -11
  62. package/dist/types/v4/classic/index.d.ts +0 -4
  63. package/dist/types/v4/classic/index.js +0 -4
  64. package/dist/types/v4/classic/iso.d.ts +0 -22
  65. package/dist/types/v4/classic/iso.js +0 -30
  66. package/dist/types/v4/classic/parse.d.ts +0 -23
  67. package/dist/types/v4/classic/parse.js +0 -6
  68. package/dist/types/v4/classic/schemas.d.ts +0 -653
  69. package/dist/types/v4/classic/schemas.js +0 -1012
  70. package/dist/types/v4/core/api.d.ts +0 -273
  71. package/dist/types/v4/core/api.js +0 -867
  72. package/dist/types/v4/core/checks.d.ts +0 -277
  73. package/dist/types/v4/core/checks.js +0 -535
  74. package/dist/types/v4/core/config.d.ts +0 -9
  75. package/dist/types/v4/core/config.js +0 -6
  76. package/dist/types/v4/core/core.d.ts +0 -43
  77. package/dist/types/v4/core/core.js +0 -53
  78. package/dist/types/v4/core/doc.d.ts +0 -14
  79. package/dist/types/v4/core/doc.js +0 -36
  80. package/dist/types/v4/core/errors.d.ts +0 -204
  81. package/dist/types/v4/core/errors.js +0 -206
  82. package/dist/types/v4/core/function.d.ts +0 -35
  83. package/dist/types/v4/core/function.js +0 -70
  84. package/dist/types/v4/core/index.d.ts +0 -15
  85. package/dist/types/v4/core/index.js +0 -15
  86. package/dist/types/v4/core/json-schema.d.ts +0 -100
  87. package/dist/types/v4/core/json-schema.js +0 -1
  88. package/dist/types/v4/core/parse.d.ts +0 -25
  89. package/dist/types/v4/core/parse.js +0 -57
  90. package/dist/types/v4/core/regexes.d.ts +0 -62
  91. package/dist/types/v4/core/regexes.js +0 -93
  92. package/dist/types/v4/core/registries.d.ts +0 -32
  93. package/dist/types/v4/core/registries.js +0 -42
  94. package/dist/types/v4/core/schemas.d.ts +0 -975
  95. package/dist/types/v4/core/schemas.js +0 -1740
  96. package/dist/types/v4/core/standard-schema.d.ts +0 -55
  97. package/dist/types/v4/core/standard-schema.js +0 -1
  98. package/dist/types/v4/core/to-json-schema.d.ts +0 -84
  99. package/dist/types/v4/core/to-json-schema.js +0 -665
  100. package/dist/types/v4/core/util.d.ts +0 -186
  101. package/dist/types/v4/core/util.js +0 -469
  102. package/dist/types/v4/core/versions.d.ts +0 -5
  103. package/dist/types/v4/core/versions.js +0 -5
  104. package/dist/types/v4/core/zsf.d.ts +0 -91
  105. package/dist/types/v4/core/zsf.js +0 -171
  106. package/dist/types/v4/index.d.ts +0 -3
  107. package/dist/types/v4/index.js +0 -3
  108. package/dist/types/v4/locales/ar.d.ts +0 -7
  109. package/dist/types/v4/locales/ar.js +0 -115
  110. package/dist/types/v4/locales/az.d.ts +0 -7
  111. package/dist/types/v4/locales/az.js +0 -114
  112. package/dist/types/v4/locales/be.d.ts +0 -7
  113. package/dist/types/v4/locales/be.js +0 -163
  114. package/dist/types/v4/locales/ca.d.ts +0 -7
  115. package/dist/types/v4/locales/ca.js +0 -117
  116. package/dist/types/v4/locales/cs.d.ts +0 -7
  117. package/dist/types/v4/locales/cs.js +0 -134
  118. package/dist/types/v4/locales/de.d.ts +0 -7
  119. package/dist/types/v4/locales/de.js +0 -115
  120. package/dist/types/v4/locales/en.d.ts +0 -7
  121. package/dist/types/v4/locales/en.js +0 -117
  122. package/dist/types/v4/locales/es.d.ts +0 -7
  123. package/dist/types/v4/locales/es.js +0 -116
  124. package/dist/types/v4/locales/fa.d.ts +0 -7
  125. package/dist/types/v4/locales/fa.js +0 -121
  126. package/dist/types/v4/locales/fi.d.ts +0 -7
  127. package/dist/types/v4/locales/fi.js +0 -121
  128. package/dist/types/v4/locales/fr.d.ts +0 -7
  129. package/dist/types/v4/locales/fr.js +0 -115
  130. package/dist/types/v4/locales/frCA.d.ts +0 -7
  131. package/dist/types/v4/locales/frCA.js +0 -116
  132. package/dist/types/v4/locales/he.d.ts +0 -7
  133. package/dist/types/v4/locales/he.js +0 -116
  134. package/dist/types/v4/locales/hu.d.ts +0 -7
  135. package/dist/types/v4/locales/hu.js +0 -116
  136. package/dist/types/v4/locales/id.d.ts +0 -7
  137. package/dist/types/v4/locales/id.js +0 -115
  138. package/dist/types/v4/locales/index.d.ts +0 -34
  139. package/dist/types/v4/locales/index.js +0 -34
  140. package/dist/types/v4/locales/it.d.ts +0 -7
  141. package/dist/types/v4/locales/it.js +0 -116
  142. package/dist/types/v4/locales/ja.d.ts +0 -7
  143. package/dist/types/v4/locales/ja.js +0 -114
  144. package/dist/types/v4/locales/ko.d.ts +0 -7
  145. package/dist/types/v4/locales/ko.js +0 -120
  146. package/dist/types/v4/locales/mk.d.ts +0 -7
  147. package/dist/types/v4/locales/mk.js +0 -117
  148. package/dist/types/v4/locales/ms.d.ts +0 -7
  149. package/dist/types/v4/locales/ms.js +0 -115
  150. package/dist/types/v4/locales/no.d.ts +0 -7
  151. package/dist/types/v4/locales/no.js +0 -115
  152. package/dist/types/v4/locales/ota.d.ts +0 -7
  153. package/dist/types/v4/locales/ota.js +0 -116
  154. package/dist/types/v4/locales/pl.d.ts +0 -7
  155. package/dist/types/v4/locales/pl.js +0 -116
  156. package/dist/types/v4/locales/pt.d.ts +0 -7
  157. package/dist/types/v4/locales/pt.js +0 -115
  158. package/dist/types/v4/locales/ru.d.ts +0 -7
  159. package/dist/types/v4/locales/ru.js +0 -163
  160. package/dist/types/v4/locales/sl.d.ts +0 -7
  161. package/dist/types/v4/locales/sl.js +0 -116
  162. package/dist/types/v4/locales/ta.d.ts +0 -7
  163. package/dist/types/v4/locales/ta.js +0 -116
  164. package/dist/types/v4/locales/th.d.ts +0 -7
  165. package/dist/types/v4/locales/th.js +0 -116
  166. package/dist/types/v4/locales/tr.d.ts +0 -7
  167. package/dist/types/v4/locales/tr.js +0 -114
  168. package/dist/types/v4/locales/ua.d.ts +0 -7
  169. package/dist/types/v4/locales/ua.js +0 -116
  170. package/dist/types/v4/locales/ur.d.ts +0 -7
  171. package/dist/types/v4/locales/ur.js +0 -116
  172. package/dist/types/v4/locales/vi.d.ts +0 -7
  173. package/dist/types/v4/locales/vi.js +0 -115
  174. package/dist/types/v4/locales/zh-CN.d.ts +0 -7
  175. package/dist/types/v4/locales/zh-CN.js +0 -115
  176. package/dist/types/v4/locales/zh-tw.d.ts +0 -7
  177. package/dist/types/v4/locales/zh-tw.js +0 -116
  178. package/dist/types/v4/mini/checks.d.ts +0 -1
  179. package/dist/types/v4/mini/checks.js +0 -1
  180. package/dist/types/v4/mini/coerce.d.ts +0 -7
  181. package/dist/types/v4/mini/coerce.js +0 -17
  182. package/dist/types/v4/mini/external.d.ts +0 -7
  183. package/dist/types/v4/mini/external.js +0 -7
  184. package/dist/types/v4/mini/index.d.ts +0 -3
  185. package/dist/types/v4/mini/index.js +0 -3
  186. package/dist/types/v4/mini/iso.d.ts +0 -22
  187. package/dist/types/v4/mini/iso.js +0 -30
  188. package/dist/types/v4/mini/parse.d.ts +0 -1
  189. package/dist/types/v4/mini/parse.js +0 -1
  190. package/dist/types/v4/mini/schemas.d.ts +0 -405
  191. package/dist/types/v4/mini/schemas.js +0 -738
@@ -1,3713 +0,0 @@
1
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
- };
6
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
7
- if (kind === "m") throw new TypeError("Private method is not writable");
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
10
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
- };
12
- var _ZodEnum_cache, _ZodNativeEnum_cache;
13
- import { ZodError, ZodIssueCode, } from "./ZodError.js";
14
- import { defaultErrorMap, getErrorMap } from "./errors.js";
15
- import { errorUtil } from "./helpers/errorUtil.js";
16
- import { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from "./helpers/parseUtil.js";
17
- import { util, ZodParsedType, getParsedType } from "./helpers/util.js";
18
- class ParseInputLazyPath {
19
- constructor(parent, value, path, key) {
20
- this._cachedPath = [];
21
- this.parent = parent;
22
- this.data = value;
23
- this._path = path;
24
- this._key = key;
25
- }
26
- get path() {
27
- if (!this._cachedPath.length) {
28
- if (Array.isArray(this._key)) {
29
- this._cachedPath.push(...this._path, ...this._key);
30
- }
31
- else {
32
- this._cachedPath.push(...this._path, this._key);
33
- }
34
- }
35
- return this._cachedPath;
36
- }
37
- }
38
- const handleResult = (ctx, result) => {
39
- if (isValid(result)) {
40
- return { success: true, data: result.value };
41
- }
42
- else {
43
- if (!ctx.common.issues.length) {
44
- throw new Error("Validation failed but no issues detected.");
45
- }
46
- return {
47
- success: false,
48
- get error() {
49
- if (this._error)
50
- return this._error;
51
- const error = new ZodError(ctx.common.issues);
52
- this._error = error;
53
- return this._error;
54
- },
55
- };
56
- }
57
- };
58
- function processCreateParams(params) {
59
- if (!params)
60
- return {};
61
- const { errorMap, invalid_type_error, required_error, description } = params;
62
- if (errorMap && (invalid_type_error || required_error)) {
63
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
64
- }
65
- if (errorMap)
66
- return { errorMap: errorMap, description };
67
- const customMap = (iss, ctx) => {
68
- const { message } = params;
69
- if (iss.code === "invalid_enum_value") {
70
- return { message: message ?? ctx.defaultError };
71
- }
72
- if (typeof ctx.data === "undefined") {
73
- return { message: message ?? required_error ?? ctx.defaultError };
74
- }
75
- if (iss.code !== "invalid_type")
76
- return { message: ctx.defaultError };
77
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
78
- };
79
- return { errorMap: customMap, description };
80
- }
81
- export class ZodType {
82
- get description() {
83
- return this._def.description;
84
- }
85
- _getType(input) {
86
- return getParsedType(input.data);
87
- }
88
- _getOrReturnCtx(input, ctx) {
89
- return (ctx || {
90
- common: input.parent.common,
91
- data: input.data,
92
- parsedType: getParsedType(input.data),
93
- schemaErrorMap: this._def.errorMap,
94
- path: input.path,
95
- parent: input.parent,
96
- });
97
- }
98
- _processInputParams(input) {
99
- return {
100
- status: new ParseStatus(),
101
- ctx: {
102
- common: input.parent.common,
103
- data: input.data,
104
- parsedType: getParsedType(input.data),
105
- schemaErrorMap: this._def.errorMap,
106
- path: input.path,
107
- parent: input.parent,
108
- },
109
- };
110
- }
111
- _parseSync(input) {
112
- const result = this._parse(input);
113
- if (isAsync(result)) {
114
- throw new Error("Synchronous parse encountered promise.");
115
- }
116
- return result;
117
- }
118
- _parseAsync(input) {
119
- const result = this._parse(input);
120
- return Promise.resolve(result);
121
- }
122
- parse(data, params) {
123
- const result = this.safeParse(data, params);
124
- if (result.success)
125
- return result.data;
126
- throw result.error;
127
- }
128
- safeParse(data, params) {
129
- const ctx = {
130
- common: {
131
- issues: [],
132
- async: params?.async ?? false,
133
- contextualErrorMap: params?.errorMap,
134
- },
135
- path: params?.path || [],
136
- schemaErrorMap: this._def.errorMap,
137
- parent: null,
138
- data,
139
- parsedType: getParsedType(data),
140
- };
141
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
142
- return handleResult(ctx, result);
143
- }
144
- "~validate"(data) {
145
- const ctx = {
146
- common: {
147
- issues: [],
148
- async: !!this["~standard"].async,
149
- },
150
- path: [],
151
- schemaErrorMap: this._def.errorMap,
152
- parent: null,
153
- data,
154
- parsedType: getParsedType(data),
155
- };
156
- if (!this["~standard"].async) {
157
- try {
158
- const result = this._parseSync({ data, path: [], parent: ctx });
159
- return isValid(result)
160
- ? {
161
- value: result.value,
162
- }
163
- : {
164
- issues: ctx.common.issues,
165
- };
166
- }
167
- catch (err) {
168
- if (err?.message?.toLowerCase()?.includes("encountered")) {
169
- this["~standard"].async = true;
170
- }
171
- ctx.common = {
172
- issues: [],
173
- async: true,
174
- };
175
- }
176
- }
177
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)
178
- ? {
179
- value: result.value,
180
- }
181
- : {
182
- issues: ctx.common.issues,
183
- });
184
- }
185
- async parseAsync(data, params) {
186
- const result = await this.safeParseAsync(data, params);
187
- if (result.success)
188
- return result.data;
189
- throw result.error;
190
- }
191
- async safeParseAsync(data, params) {
192
- const ctx = {
193
- common: {
194
- issues: [],
195
- contextualErrorMap: params?.errorMap,
196
- async: true,
197
- },
198
- path: params?.path || [],
199
- schemaErrorMap: this._def.errorMap,
200
- parent: null,
201
- data,
202
- parsedType: getParsedType(data),
203
- };
204
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
205
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
206
- return handleResult(ctx, result);
207
- }
208
- refine(check, message) {
209
- const getIssueProperties = (val) => {
210
- if (typeof message === "string" || typeof message === "undefined") {
211
- return { message };
212
- }
213
- else if (typeof message === "function") {
214
- return message(val);
215
- }
216
- else {
217
- return message;
218
- }
219
- };
220
- return this._refinement((val, ctx) => {
221
- const result = check(val);
222
- const setError = () => ctx.addIssue({
223
- code: ZodIssueCode.custom,
224
- ...getIssueProperties(val),
225
- });
226
- if (typeof Promise !== "undefined" && result instanceof Promise) {
227
- return result.then((data) => {
228
- if (!data) {
229
- setError();
230
- return false;
231
- }
232
- else {
233
- return true;
234
- }
235
- });
236
- }
237
- if (!result) {
238
- setError();
239
- return false;
240
- }
241
- else {
242
- return true;
243
- }
244
- });
245
- }
246
- refinement(check, refinementData) {
247
- return this._refinement((val, ctx) => {
248
- if (!check(val)) {
249
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
250
- return false;
251
- }
252
- else {
253
- return true;
254
- }
255
- });
256
- }
257
- _refinement(refinement) {
258
- return new ZodEffects({
259
- schema: this,
260
- typeName: ZodFirstPartyTypeKind.ZodEffects,
261
- effect: { type: "refinement", refinement },
262
- });
263
- }
264
- superRefine(refinement) {
265
- return this._refinement(refinement);
266
- }
267
- constructor(def) {
268
- /** Alias of safeParseAsync */
269
- this.spa = this.safeParseAsync;
270
- this._def = def;
271
- this.parse = this.parse.bind(this);
272
- this.safeParse = this.safeParse.bind(this);
273
- this.parseAsync = this.parseAsync.bind(this);
274
- this.safeParseAsync = this.safeParseAsync.bind(this);
275
- this.spa = this.spa.bind(this);
276
- this.refine = this.refine.bind(this);
277
- this.refinement = this.refinement.bind(this);
278
- this.superRefine = this.superRefine.bind(this);
279
- this.optional = this.optional.bind(this);
280
- this.nullable = this.nullable.bind(this);
281
- this.nullish = this.nullish.bind(this);
282
- this.array = this.array.bind(this);
283
- this.promise = this.promise.bind(this);
284
- this.or = this.or.bind(this);
285
- this.and = this.and.bind(this);
286
- this.transform = this.transform.bind(this);
287
- this.brand = this.brand.bind(this);
288
- this.default = this.default.bind(this);
289
- this.catch = this.catch.bind(this);
290
- this.describe = this.describe.bind(this);
291
- this.pipe = this.pipe.bind(this);
292
- this.readonly = this.readonly.bind(this);
293
- this.isNullable = this.isNullable.bind(this);
294
- this.isOptional = this.isOptional.bind(this);
295
- this["~standard"] = {
296
- version: 1,
297
- vendor: "zod",
298
- validate: (data) => this["~validate"](data),
299
- };
300
- }
301
- optional() {
302
- return ZodOptional.create(this, this._def);
303
- }
304
- nullable() {
305
- return ZodNullable.create(this, this._def);
306
- }
307
- nullish() {
308
- return this.nullable().optional();
309
- }
310
- array() {
311
- return ZodArray.create(this);
312
- }
313
- promise() {
314
- return ZodPromise.create(this, this._def);
315
- }
316
- or(option) {
317
- return ZodUnion.create([this, option], this._def);
318
- }
319
- and(incoming) {
320
- return ZodIntersection.create(this, incoming, this._def);
321
- }
322
- transform(transform) {
323
- return new ZodEffects({
324
- ...processCreateParams(this._def),
325
- schema: this,
326
- typeName: ZodFirstPartyTypeKind.ZodEffects,
327
- effect: { type: "transform", transform },
328
- });
329
- }
330
- default(def) {
331
- const defaultValueFunc = typeof def === "function" ? def : () => def;
332
- return new ZodDefault({
333
- ...processCreateParams(this._def),
334
- innerType: this,
335
- defaultValue: defaultValueFunc,
336
- typeName: ZodFirstPartyTypeKind.ZodDefault,
337
- });
338
- }
339
- brand() {
340
- return new ZodBranded({
341
- typeName: ZodFirstPartyTypeKind.ZodBranded,
342
- type: this,
343
- ...processCreateParams(this._def),
344
- });
345
- }
346
- catch(def) {
347
- const catchValueFunc = typeof def === "function" ? def : () => def;
348
- return new ZodCatch({
349
- ...processCreateParams(this._def),
350
- innerType: this,
351
- catchValue: catchValueFunc,
352
- typeName: ZodFirstPartyTypeKind.ZodCatch,
353
- });
354
- }
355
- describe(description) {
356
- const This = this.constructor;
357
- return new This({
358
- ...this._def,
359
- description,
360
- });
361
- }
362
- pipe(target) {
363
- return ZodPipeline.create(this, target);
364
- }
365
- readonly() {
366
- return ZodReadonly.create(this);
367
- }
368
- isOptional() {
369
- return this.safeParse(undefined).success;
370
- }
371
- isNullable() {
372
- return this.safeParse(null).success;
373
- }
374
- }
375
- const cuidRegex = /^c[^\s-]{8,}$/i;
376
- const cuid2Regex = /^[0-9a-z]+$/;
377
- const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
378
- // const uuidRegex =
379
- // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
380
- const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
381
- const nanoidRegex = /^[a-z0-9_-]{21}$/i;
382
- const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
383
- const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
384
- // from https://stackoverflow.com/a/46181/1550155
385
- // old version: too slow, didn't support unicode
386
- // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
387
- //old email regex
388
- // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
389
- // eslint-disable-next-line
390
- // const emailRegex =
391
- // /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/;
392
- // const emailRegex =
393
- // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
394
- // const emailRegex =
395
- // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
396
- const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
397
- // const emailRegex =
398
- // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
399
- // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
400
- const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
401
- let emojiRegex;
402
- // faster, simpler, safer
403
- const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
404
- const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
405
- // const ipv6Regex =
406
- // /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
407
- const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
408
- const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
409
- // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
410
- const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
411
- // https://base64.guru/standards/base64url
412
- const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
413
- // simple
414
- // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
415
- // no leap year validation
416
- // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
417
- // with leap year validation
418
- const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
419
- const dateRegex = new RegExp(`^${dateRegexSource}$`);
420
- function timeRegexSource(args) {
421
- let secondsRegexSource = `[0-5]\\d`;
422
- if (args.precision) {
423
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
424
- }
425
- else if (args.precision == null) {
426
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
427
- }
428
- const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero
429
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
430
- }
431
- function timeRegex(args) {
432
- return new RegExp(`^${timeRegexSource(args)}$`);
433
- }
434
- // Adapted from https://stackoverflow.com/a/3143231
435
- export function datetimeRegex(args) {
436
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
437
- const opts = [];
438
- opts.push(args.local ? `Z?` : `Z`);
439
- if (args.offset)
440
- opts.push(`([+-]\\d{2}:?\\d{2})`);
441
- regex = `${regex}(${opts.join("|")})`;
442
- return new RegExp(`^${regex}$`);
443
- }
444
- function isValidIP(ip, version) {
445
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
446
- return true;
447
- }
448
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
449
- return true;
450
- }
451
- return false;
452
- }
453
- function isValidJWT(jwt, alg) {
454
- if (!jwtRegex.test(jwt))
455
- return false;
456
- try {
457
- const [header] = jwt.split(".");
458
- // Convert base64url to base64
459
- const base64 = header
460
- .replace(/-/g, "+")
461
- .replace(/_/g, "/")
462
- .padEnd(header.length + ((4 - (header.length % 4)) % 4), "=");
463
- const decoded = JSON.parse(atob(base64));
464
- if (typeof decoded !== "object" || decoded === null)
465
- return false;
466
- if ("typ" in decoded && decoded?.typ !== "JWT")
467
- return false;
468
- if (!decoded.alg)
469
- return false;
470
- if (alg && decoded.alg !== alg)
471
- return false;
472
- return true;
473
- }
474
- catch {
475
- return false;
476
- }
477
- }
478
- function isValidCidr(ip, version) {
479
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
480
- return true;
481
- }
482
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
483
- return true;
484
- }
485
- return false;
486
- }
487
- export class ZodString extends ZodType {
488
- _parse(input) {
489
- if (this._def.coerce) {
490
- input.data = String(input.data);
491
- }
492
- const parsedType = this._getType(input);
493
- if (parsedType !== ZodParsedType.string) {
494
- const ctx = this._getOrReturnCtx(input);
495
- addIssueToContext(ctx, {
496
- code: ZodIssueCode.invalid_type,
497
- expected: ZodParsedType.string,
498
- received: ctx.parsedType,
499
- });
500
- return INVALID;
501
- }
502
- const status = new ParseStatus();
503
- let ctx = undefined;
504
- for (const check of this._def.checks) {
505
- if (check.kind === "min") {
506
- if (input.data.length < check.value) {
507
- ctx = this._getOrReturnCtx(input, ctx);
508
- addIssueToContext(ctx, {
509
- code: ZodIssueCode.too_small,
510
- minimum: check.value,
511
- type: "string",
512
- inclusive: true,
513
- exact: false,
514
- message: check.message,
515
- });
516
- status.dirty();
517
- }
518
- }
519
- else if (check.kind === "max") {
520
- if (input.data.length > check.value) {
521
- ctx = this._getOrReturnCtx(input, ctx);
522
- addIssueToContext(ctx, {
523
- code: ZodIssueCode.too_big,
524
- maximum: check.value,
525
- type: "string",
526
- inclusive: true,
527
- exact: false,
528
- message: check.message,
529
- });
530
- status.dirty();
531
- }
532
- }
533
- else if (check.kind === "length") {
534
- const tooBig = input.data.length > check.value;
535
- const tooSmall = input.data.length < check.value;
536
- if (tooBig || tooSmall) {
537
- ctx = this._getOrReturnCtx(input, ctx);
538
- if (tooBig) {
539
- addIssueToContext(ctx, {
540
- code: ZodIssueCode.too_big,
541
- maximum: check.value,
542
- type: "string",
543
- inclusive: true,
544
- exact: true,
545
- message: check.message,
546
- });
547
- }
548
- else if (tooSmall) {
549
- addIssueToContext(ctx, {
550
- code: ZodIssueCode.too_small,
551
- minimum: check.value,
552
- type: "string",
553
- inclusive: true,
554
- exact: true,
555
- message: check.message,
556
- });
557
- }
558
- status.dirty();
559
- }
560
- }
561
- else if (check.kind === "email") {
562
- if (!emailRegex.test(input.data)) {
563
- ctx = this._getOrReturnCtx(input, ctx);
564
- addIssueToContext(ctx, {
565
- validation: "email",
566
- code: ZodIssueCode.invalid_string,
567
- message: check.message,
568
- });
569
- status.dirty();
570
- }
571
- }
572
- else if (check.kind === "emoji") {
573
- if (!emojiRegex) {
574
- emojiRegex = new RegExp(_emojiRegex, "u");
575
- }
576
- if (!emojiRegex.test(input.data)) {
577
- ctx = this._getOrReturnCtx(input, ctx);
578
- addIssueToContext(ctx, {
579
- validation: "emoji",
580
- code: ZodIssueCode.invalid_string,
581
- message: check.message,
582
- });
583
- status.dirty();
584
- }
585
- }
586
- else if (check.kind === "uuid") {
587
- if (!uuidRegex.test(input.data)) {
588
- ctx = this._getOrReturnCtx(input, ctx);
589
- addIssueToContext(ctx, {
590
- validation: "uuid",
591
- code: ZodIssueCode.invalid_string,
592
- message: check.message,
593
- });
594
- status.dirty();
595
- }
596
- }
597
- else if (check.kind === "nanoid") {
598
- if (!nanoidRegex.test(input.data)) {
599
- ctx = this._getOrReturnCtx(input, ctx);
600
- addIssueToContext(ctx, {
601
- validation: "nanoid",
602
- code: ZodIssueCode.invalid_string,
603
- message: check.message,
604
- });
605
- status.dirty();
606
- }
607
- }
608
- else if (check.kind === "cuid") {
609
- if (!cuidRegex.test(input.data)) {
610
- ctx = this._getOrReturnCtx(input, ctx);
611
- addIssueToContext(ctx, {
612
- validation: "cuid",
613
- code: ZodIssueCode.invalid_string,
614
- message: check.message,
615
- });
616
- status.dirty();
617
- }
618
- }
619
- else if (check.kind === "cuid2") {
620
- if (!cuid2Regex.test(input.data)) {
621
- ctx = this._getOrReturnCtx(input, ctx);
622
- addIssueToContext(ctx, {
623
- validation: "cuid2",
624
- code: ZodIssueCode.invalid_string,
625
- message: check.message,
626
- });
627
- status.dirty();
628
- }
629
- }
630
- else if (check.kind === "ulid") {
631
- if (!ulidRegex.test(input.data)) {
632
- ctx = this._getOrReturnCtx(input, ctx);
633
- addIssueToContext(ctx, {
634
- validation: "ulid",
635
- code: ZodIssueCode.invalid_string,
636
- message: check.message,
637
- });
638
- status.dirty();
639
- }
640
- }
641
- else if (check.kind === "url") {
642
- try {
643
- new URL(input.data);
644
- }
645
- catch {
646
- ctx = this._getOrReturnCtx(input, ctx);
647
- addIssueToContext(ctx, {
648
- validation: "url",
649
- code: ZodIssueCode.invalid_string,
650
- message: check.message,
651
- });
652
- status.dirty();
653
- }
654
- }
655
- else if (check.kind === "regex") {
656
- check.regex.lastIndex = 0;
657
- const testResult = check.regex.test(input.data);
658
- if (!testResult) {
659
- ctx = this._getOrReturnCtx(input, ctx);
660
- addIssueToContext(ctx, {
661
- validation: "regex",
662
- code: ZodIssueCode.invalid_string,
663
- message: check.message,
664
- });
665
- status.dirty();
666
- }
667
- }
668
- else if (check.kind === "trim") {
669
- input.data = input.data.trim();
670
- }
671
- else if (check.kind === "includes") {
672
- if (!input.data.includes(check.value, check.position)) {
673
- ctx = this._getOrReturnCtx(input, ctx);
674
- addIssueToContext(ctx, {
675
- code: ZodIssueCode.invalid_string,
676
- validation: { includes: check.value, position: check.position },
677
- message: check.message,
678
- });
679
- status.dirty();
680
- }
681
- }
682
- else if (check.kind === "toLowerCase") {
683
- input.data = input.data.toLowerCase();
684
- }
685
- else if (check.kind === "toUpperCase") {
686
- input.data = input.data.toUpperCase();
687
- }
688
- else if (check.kind === "startsWith") {
689
- if (!input.data.startsWith(check.value)) {
690
- ctx = this._getOrReturnCtx(input, ctx);
691
- addIssueToContext(ctx, {
692
- code: ZodIssueCode.invalid_string,
693
- validation: { startsWith: check.value },
694
- message: check.message,
695
- });
696
- status.dirty();
697
- }
698
- }
699
- else if (check.kind === "endsWith") {
700
- if (!input.data.endsWith(check.value)) {
701
- ctx = this._getOrReturnCtx(input, ctx);
702
- addIssueToContext(ctx, {
703
- code: ZodIssueCode.invalid_string,
704
- validation: { endsWith: check.value },
705
- message: check.message,
706
- });
707
- status.dirty();
708
- }
709
- }
710
- else if (check.kind === "datetime") {
711
- const regex = datetimeRegex(check);
712
- if (!regex.test(input.data)) {
713
- ctx = this._getOrReturnCtx(input, ctx);
714
- addIssueToContext(ctx, {
715
- code: ZodIssueCode.invalid_string,
716
- validation: "datetime",
717
- message: check.message,
718
- });
719
- status.dirty();
720
- }
721
- }
722
- else if (check.kind === "date") {
723
- const regex = dateRegex;
724
- if (!regex.test(input.data)) {
725
- ctx = this._getOrReturnCtx(input, ctx);
726
- addIssueToContext(ctx, {
727
- code: ZodIssueCode.invalid_string,
728
- validation: "date",
729
- message: check.message,
730
- });
731
- status.dirty();
732
- }
733
- }
734
- else if (check.kind === "time") {
735
- const regex = timeRegex(check);
736
- if (!regex.test(input.data)) {
737
- ctx = this._getOrReturnCtx(input, ctx);
738
- addIssueToContext(ctx, {
739
- code: ZodIssueCode.invalid_string,
740
- validation: "time",
741
- message: check.message,
742
- });
743
- status.dirty();
744
- }
745
- }
746
- else if (check.kind === "duration") {
747
- if (!durationRegex.test(input.data)) {
748
- ctx = this._getOrReturnCtx(input, ctx);
749
- addIssueToContext(ctx, {
750
- validation: "duration",
751
- code: ZodIssueCode.invalid_string,
752
- message: check.message,
753
- });
754
- status.dirty();
755
- }
756
- }
757
- else if (check.kind === "ip") {
758
- if (!isValidIP(input.data, check.version)) {
759
- ctx = this._getOrReturnCtx(input, ctx);
760
- addIssueToContext(ctx, {
761
- validation: "ip",
762
- code: ZodIssueCode.invalid_string,
763
- message: check.message,
764
- });
765
- status.dirty();
766
- }
767
- }
768
- else if (check.kind === "jwt") {
769
- if (!isValidJWT(input.data, check.alg)) {
770
- ctx = this._getOrReturnCtx(input, ctx);
771
- addIssueToContext(ctx, {
772
- validation: "jwt",
773
- code: ZodIssueCode.invalid_string,
774
- message: check.message,
775
- });
776
- status.dirty();
777
- }
778
- }
779
- else if (check.kind === "cidr") {
780
- if (!isValidCidr(input.data, check.version)) {
781
- ctx = this._getOrReturnCtx(input, ctx);
782
- addIssueToContext(ctx, {
783
- validation: "cidr",
784
- code: ZodIssueCode.invalid_string,
785
- message: check.message,
786
- });
787
- status.dirty();
788
- }
789
- }
790
- else if (check.kind === "base64") {
791
- if (!base64Regex.test(input.data)) {
792
- ctx = this._getOrReturnCtx(input, ctx);
793
- addIssueToContext(ctx, {
794
- validation: "base64",
795
- code: ZodIssueCode.invalid_string,
796
- message: check.message,
797
- });
798
- status.dirty();
799
- }
800
- }
801
- else if (check.kind === "base64url") {
802
- if (!base64urlRegex.test(input.data)) {
803
- ctx = this._getOrReturnCtx(input, ctx);
804
- addIssueToContext(ctx, {
805
- validation: "base64url",
806
- code: ZodIssueCode.invalid_string,
807
- message: check.message,
808
- });
809
- status.dirty();
810
- }
811
- }
812
- else {
813
- util.assertNever(check);
814
- }
815
- }
816
- return { status: status.value, value: input.data };
817
- }
818
- _regex(regex, validation, message) {
819
- return this.refinement((data) => regex.test(data), {
820
- validation,
821
- code: ZodIssueCode.invalid_string,
822
- ...errorUtil.errToObj(message),
823
- });
824
- }
825
- _addCheck(check) {
826
- return new ZodString({
827
- ...this._def,
828
- checks: [...this._def.checks, check],
829
- });
830
- }
831
- email(message) {
832
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
833
- }
834
- url(message) {
835
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
836
- }
837
- emoji(message) {
838
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
839
- }
840
- uuid(message) {
841
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
842
- }
843
- nanoid(message) {
844
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
845
- }
846
- cuid(message) {
847
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
848
- }
849
- cuid2(message) {
850
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
851
- }
852
- ulid(message) {
853
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
854
- }
855
- base64(message) {
856
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
857
- }
858
- base64url(message) {
859
- // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
860
- return this._addCheck({
861
- kind: "base64url",
862
- ...errorUtil.errToObj(message),
863
- });
864
- }
865
- jwt(options) {
866
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
867
- }
868
- ip(options) {
869
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
870
- }
871
- cidr(options) {
872
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
873
- }
874
- datetime(options) {
875
- if (typeof options === "string") {
876
- return this._addCheck({
877
- kind: "datetime",
878
- precision: null,
879
- offset: false,
880
- local: false,
881
- message: options,
882
- });
883
- }
884
- return this._addCheck({
885
- kind: "datetime",
886
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
887
- offset: options?.offset ?? false,
888
- local: options?.local ?? false,
889
- ...errorUtil.errToObj(options?.message),
890
- });
891
- }
892
- date(message) {
893
- return this._addCheck({ kind: "date", message });
894
- }
895
- time(options) {
896
- if (typeof options === "string") {
897
- return this._addCheck({
898
- kind: "time",
899
- precision: null,
900
- message: options,
901
- });
902
- }
903
- return this._addCheck({
904
- kind: "time",
905
- precision: typeof options?.precision === "undefined" ? null : options?.precision,
906
- ...errorUtil.errToObj(options?.message),
907
- });
908
- }
909
- duration(message) {
910
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
911
- }
912
- regex(regex, message) {
913
- return this._addCheck({
914
- kind: "regex",
915
- regex: regex,
916
- ...errorUtil.errToObj(message),
917
- });
918
- }
919
- includes(value, options) {
920
- return this._addCheck({
921
- kind: "includes",
922
- value: value,
923
- position: options?.position,
924
- ...errorUtil.errToObj(options?.message),
925
- });
926
- }
927
- startsWith(value, message) {
928
- return this._addCheck({
929
- kind: "startsWith",
930
- value: value,
931
- ...errorUtil.errToObj(message),
932
- });
933
- }
934
- endsWith(value, message) {
935
- return this._addCheck({
936
- kind: "endsWith",
937
- value: value,
938
- ...errorUtil.errToObj(message),
939
- });
940
- }
941
- min(minLength, message) {
942
- return this._addCheck({
943
- kind: "min",
944
- value: minLength,
945
- ...errorUtil.errToObj(message),
946
- });
947
- }
948
- max(maxLength, message) {
949
- return this._addCheck({
950
- kind: "max",
951
- value: maxLength,
952
- ...errorUtil.errToObj(message),
953
- });
954
- }
955
- length(len, message) {
956
- return this._addCheck({
957
- kind: "length",
958
- value: len,
959
- ...errorUtil.errToObj(message),
960
- });
961
- }
962
- /**
963
- * Equivalent to `.min(1)`
964
- */
965
- nonempty(message) {
966
- return this.min(1, errorUtil.errToObj(message));
967
- }
968
- trim() {
969
- return new ZodString({
970
- ...this._def,
971
- checks: [...this._def.checks, { kind: "trim" }],
972
- });
973
- }
974
- toLowerCase() {
975
- return new ZodString({
976
- ...this._def,
977
- checks: [...this._def.checks, { kind: "toLowerCase" }],
978
- });
979
- }
980
- toUpperCase() {
981
- return new ZodString({
982
- ...this._def,
983
- checks: [...this._def.checks, { kind: "toUpperCase" }],
984
- });
985
- }
986
- get isDatetime() {
987
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
988
- }
989
- get isDate() {
990
- return !!this._def.checks.find((ch) => ch.kind === "date");
991
- }
992
- get isTime() {
993
- return !!this._def.checks.find((ch) => ch.kind === "time");
994
- }
995
- get isDuration() {
996
- return !!this._def.checks.find((ch) => ch.kind === "duration");
997
- }
998
- get isEmail() {
999
- return !!this._def.checks.find((ch) => ch.kind === "email");
1000
- }
1001
- get isURL() {
1002
- return !!this._def.checks.find((ch) => ch.kind === "url");
1003
- }
1004
- get isEmoji() {
1005
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
1006
- }
1007
- get isUUID() {
1008
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
1009
- }
1010
- get isNANOID() {
1011
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1012
- }
1013
- get isCUID() {
1014
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
1015
- }
1016
- get isCUID2() {
1017
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1018
- }
1019
- get isULID() {
1020
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
1021
- }
1022
- get isIP() {
1023
- return !!this._def.checks.find((ch) => ch.kind === "ip");
1024
- }
1025
- get isCIDR() {
1026
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
1027
- }
1028
- get isBase64() {
1029
- return !!this._def.checks.find((ch) => ch.kind === "base64");
1030
- }
1031
- get isBase64url() {
1032
- // base64url encoding is a modification of base64 that can safely be used in URLs and filenames
1033
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
1034
- }
1035
- get minLength() {
1036
- let min = null;
1037
- for (const ch of this._def.checks) {
1038
- if (ch.kind === "min") {
1039
- if (min === null || ch.value > min)
1040
- min = ch.value;
1041
- }
1042
- }
1043
- return min;
1044
- }
1045
- get maxLength() {
1046
- let max = null;
1047
- for (const ch of this._def.checks) {
1048
- if (ch.kind === "max") {
1049
- if (max === null || ch.value < max)
1050
- max = ch.value;
1051
- }
1052
- }
1053
- return max;
1054
- }
1055
- }
1056
- ZodString.create = (params) => {
1057
- return new ZodString({
1058
- checks: [],
1059
- typeName: ZodFirstPartyTypeKind.ZodString,
1060
- coerce: params?.coerce ?? false,
1061
- ...processCreateParams(params),
1062
- });
1063
- };
1064
- // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
1065
- function floatSafeRemainder(val, step) {
1066
- const valDecCount = (val.toString().split(".")[1] || "").length;
1067
- const stepDecCount = (step.toString().split(".")[1] || "").length;
1068
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1069
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1070
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1071
- return (valInt % stepInt) / 10 ** decCount;
1072
- }
1073
- export class ZodNumber extends ZodType {
1074
- constructor() {
1075
- super(...arguments);
1076
- this.min = this.gte;
1077
- this.max = this.lte;
1078
- this.step = this.multipleOf;
1079
- }
1080
- _parse(input) {
1081
- if (this._def.coerce) {
1082
- input.data = Number(input.data);
1083
- }
1084
- const parsedType = this._getType(input);
1085
- if (parsedType !== ZodParsedType.number) {
1086
- const ctx = this._getOrReturnCtx(input);
1087
- addIssueToContext(ctx, {
1088
- code: ZodIssueCode.invalid_type,
1089
- expected: ZodParsedType.number,
1090
- received: ctx.parsedType,
1091
- });
1092
- return INVALID;
1093
- }
1094
- let ctx = undefined;
1095
- const status = new ParseStatus();
1096
- for (const check of this._def.checks) {
1097
- if (check.kind === "int") {
1098
- if (!util.isInteger(input.data)) {
1099
- ctx = this._getOrReturnCtx(input, ctx);
1100
- addIssueToContext(ctx, {
1101
- code: ZodIssueCode.invalid_type,
1102
- expected: "integer",
1103
- received: "float",
1104
- message: check.message,
1105
- });
1106
- status.dirty();
1107
- }
1108
- }
1109
- else if (check.kind === "min") {
1110
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1111
- if (tooSmall) {
1112
- ctx = this._getOrReturnCtx(input, ctx);
1113
- addIssueToContext(ctx, {
1114
- code: ZodIssueCode.too_small,
1115
- minimum: check.value,
1116
- type: "number",
1117
- inclusive: check.inclusive,
1118
- exact: false,
1119
- message: check.message,
1120
- });
1121
- status.dirty();
1122
- }
1123
- }
1124
- else if (check.kind === "max") {
1125
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1126
- if (tooBig) {
1127
- ctx = this._getOrReturnCtx(input, ctx);
1128
- addIssueToContext(ctx, {
1129
- code: ZodIssueCode.too_big,
1130
- maximum: check.value,
1131
- type: "number",
1132
- inclusive: check.inclusive,
1133
- exact: false,
1134
- message: check.message,
1135
- });
1136
- status.dirty();
1137
- }
1138
- }
1139
- else if (check.kind === "multipleOf") {
1140
- if (floatSafeRemainder(input.data, check.value) !== 0) {
1141
- ctx = this._getOrReturnCtx(input, ctx);
1142
- addIssueToContext(ctx, {
1143
- code: ZodIssueCode.not_multiple_of,
1144
- multipleOf: check.value,
1145
- message: check.message,
1146
- });
1147
- status.dirty();
1148
- }
1149
- }
1150
- else if (check.kind === "finite") {
1151
- if (!Number.isFinite(input.data)) {
1152
- ctx = this._getOrReturnCtx(input, ctx);
1153
- addIssueToContext(ctx, {
1154
- code: ZodIssueCode.not_finite,
1155
- message: check.message,
1156
- });
1157
- status.dirty();
1158
- }
1159
- }
1160
- else {
1161
- util.assertNever(check);
1162
- }
1163
- }
1164
- return { status: status.value, value: input.data };
1165
- }
1166
- gte(value, message) {
1167
- return this.setLimit("min", value, true, errorUtil.toString(message));
1168
- }
1169
- gt(value, message) {
1170
- return this.setLimit("min", value, false, errorUtil.toString(message));
1171
- }
1172
- lte(value, message) {
1173
- return this.setLimit("max", value, true, errorUtil.toString(message));
1174
- }
1175
- lt(value, message) {
1176
- return this.setLimit("max", value, false, errorUtil.toString(message));
1177
- }
1178
- setLimit(kind, value, inclusive, message) {
1179
- return new ZodNumber({
1180
- ...this._def,
1181
- checks: [
1182
- ...this._def.checks,
1183
- {
1184
- kind,
1185
- value,
1186
- inclusive,
1187
- message: errorUtil.toString(message),
1188
- },
1189
- ],
1190
- });
1191
- }
1192
- _addCheck(check) {
1193
- return new ZodNumber({
1194
- ...this._def,
1195
- checks: [...this._def.checks, check],
1196
- });
1197
- }
1198
- int(message) {
1199
- return this._addCheck({
1200
- kind: "int",
1201
- message: errorUtil.toString(message),
1202
- });
1203
- }
1204
- positive(message) {
1205
- return this._addCheck({
1206
- kind: "min",
1207
- value: 0,
1208
- inclusive: false,
1209
- message: errorUtil.toString(message),
1210
- });
1211
- }
1212
- negative(message) {
1213
- return this._addCheck({
1214
- kind: "max",
1215
- value: 0,
1216
- inclusive: false,
1217
- message: errorUtil.toString(message),
1218
- });
1219
- }
1220
- nonpositive(message) {
1221
- return this._addCheck({
1222
- kind: "max",
1223
- value: 0,
1224
- inclusive: true,
1225
- message: errorUtil.toString(message),
1226
- });
1227
- }
1228
- nonnegative(message) {
1229
- return this._addCheck({
1230
- kind: "min",
1231
- value: 0,
1232
- inclusive: true,
1233
- message: errorUtil.toString(message),
1234
- });
1235
- }
1236
- multipleOf(value, message) {
1237
- return this._addCheck({
1238
- kind: "multipleOf",
1239
- value: value,
1240
- message: errorUtil.toString(message),
1241
- });
1242
- }
1243
- finite(message) {
1244
- return this._addCheck({
1245
- kind: "finite",
1246
- message: errorUtil.toString(message),
1247
- });
1248
- }
1249
- safe(message) {
1250
- return this._addCheck({
1251
- kind: "min",
1252
- inclusive: true,
1253
- value: Number.MIN_SAFE_INTEGER,
1254
- message: errorUtil.toString(message),
1255
- })._addCheck({
1256
- kind: "max",
1257
- inclusive: true,
1258
- value: Number.MAX_SAFE_INTEGER,
1259
- message: errorUtil.toString(message),
1260
- });
1261
- }
1262
- get minValue() {
1263
- let min = null;
1264
- for (const ch of this._def.checks) {
1265
- if (ch.kind === "min") {
1266
- if (min === null || ch.value > min)
1267
- min = ch.value;
1268
- }
1269
- }
1270
- return min;
1271
- }
1272
- get maxValue() {
1273
- let max = null;
1274
- for (const ch of this._def.checks) {
1275
- if (ch.kind === "max") {
1276
- if (max === null || ch.value < max)
1277
- max = ch.value;
1278
- }
1279
- }
1280
- return max;
1281
- }
1282
- get isInt() {
1283
- return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value)));
1284
- }
1285
- get isFinite() {
1286
- let max = null;
1287
- let min = null;
1288
- for (const ch of this._def.checks) {
1289
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
1290
- return true;
1291
- }
1292
- else if (ch.kind === "min") {
1293
- if (min === null || ch.value > min)
1294
- min = ch.value;
1295
- }
1296
- else if (ch.kind === "max") {
1297
- if (max === null || ch.value < max)
1298
- max = ch.value;
1299
- }
1300
- }
1301
- return Number.isFinite(min) && Number.isFinite(max);
1302
- }
1303
- }
1304
- ZodNumber.create = (params) => {
1305
- return new ZodNumber({
1306
- checks: [],
1307
- typeName: ZodFirstPartyTypeKind.ZodNumber,
1308
- coerce: params?.coerce || false,
1309
- ...processCreateParams(params),
1310
- });
1311
- };
1312
- export class ZodBigInt extends ZodType {
1313
- constructor() {
1314
- super(...arguments);
1315
- this.min = this.gte;
1316
- this.max = this.lte;
1317
- }
1318
- _parse(input) {
1319
- if (this._def.coerce) {
1320
- try {
1321
- input.data = BigInt(input.data);
1322
- }
1323
- catch {
1324
- return this._getInvalidInput(input);
1325
- }
1326
- }
1327
- const parsedType = this._getType(input);
1328
- if (parsedType !== ZodParsedType.bigint) {
1329
- return this._getInvalidInput(input);
1330
- }
1331
- let ctx = undefined;
1332
- const status = new ParseStatus();
1333
- for (const check of this._def.checks) {
1334
- if (check.kind === "min") {
1335
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1336
- if (tooSmall) {
1337
- ctx = this._getOrReturnCtx(input, ctx);
1338
- addIssueToContext(ctx, {
1339
- code: ZodIssueCode.too_small,
1340
- type: "bigint",
1341
- minimum: check.value,
1342
- inclusive: check.inclusive,
1343
- message: check.message,
1344
- });
1345
- status.dirty();
1346
- }
1347
- }
1348
- else if (check.kind === "max") {
1349
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1350
- if (tooBig) {
1351
- ctx = this._getOrReturnCtx(input, ctx);
1352
- addIssueToContext(ctx, {
1353
- code: ZodIssueCode.too_big,
1354
- type: "bigint",
1355
- maximum: check.value,
1356
- inclusive: check.inclusive,
1357
- message: check.message,
1358
- });
1359
- status.dirty();
1360
- }
1361
- }
1362
- else if (check.kind === "multipleOf") {
1363
- if (input.data % check.value !== BigInt(0)) {
1364
- ctx = this._getOrReturnCtx(input, ctx);
1365
- addIssueToContext(ctx, {
1366
- code: ZodIssueCode.not_multiple_of,
1367
- multipleOf: check.value,
1368
- message: check.message,
1369
- });
1370
- status.dirty();
1371
- }
1372
- }
1373
- else {
1374
- util.assertNever(check);
1375
- }
1376
- }
1377
- return { status: status.value, value: input.data };
1378
- }
1379
- _getInvalidInput(input) {
1380
- const ctx = this._getOrReturnCtx(input);
1381
- addIssueToContext(ctx, {
1382
- code: ZodIssueCode.invalid_type,
1383
- expected: ZodParsedType.bigint,
1384
- received: ctx.parsedType,
1385
- });
1386
- return INVALID;
1387
- }
1388
- gte(value, message) {
1389
- return this.setLimit("min", value, true, errorUtil.toString(message));
1390
- }
1391
- gt(value, message) {
1392
- return this.setLimit("min", value, false, errorUtil.toString(message));
1393
- }
1394
- lte(value, message) {
1395
- return this.setLimit("max", value, true, errorUtil.toString(message));
1396
- }
1397
- lt(value, message) {
1398
- return this.setLimit("max", value, false, errorUtil.toString(message));
1399
- }
1400
- setLimit(kind, value, inclusive, message) {
1401
- return new ZodBigInt({
1402
- ...this._def,
1403
- checks: [
1404
- ...this._def.checks,
1405
- {
1406
- kind,
1407
- value,
1408
- inclusive,
1409
- message: errorUtil.toString(message),
1410
- },
1411
- ],
1412
- });
1413
- }
1414
- _addCheck(check) {
1415
- return new ZodBigInt({
1416
- ...this._def,
1417
- checks: [...this._def.checks, check],
1418
- });
1419
- }
1420
- positive(message) {
1421
- return this._addCheck({
1422
- kind: "min",
1423
- value: BigInt(0),
1424
- inclusive: false,
1425
- message: errorUtil.toString(message),
1426
- });
1427
- }
1428
- negative(message) {
1429
- return this._addCheck({
1430
- kind: "max",
1431
- value: BigInt(0),
1432
- inclusive: false,
1433
- message: errorUtil.toString(message),
1434
- });
1435
- }
1436
- nonpositive(message) {
1437
- return this._addCheck({
1438
- kind: "max",
1439
- value: BigInt(0),
1440
- inclusive: true,
1441
- message: errorUtil.toString(message),
1442
- });
1443
- }
1444
- nonnegative(message) {
1445
- return this._addCheck({
1446
- kind: "min",
1447
- value: BigInt(0),
1448
- inclusive: true,
1449
- message: errorUtil.toString(message),
1450
- });
1451
- }
1452
- multipleOf(value, message) {
1453
- return this._addCheck({
1454
- kind: "multipleOf",
1455
- value,
1456
- message: errorUtil.toString(message),
1457
- });
1458
- }
1459
- get minValue() {
1460
- let min = null;
1461
- for (const ch of this._def.checks) {
1462
- if (ch.kind === "min") {
1463
- if (min === null || ch.value > min)
1464
- min = ch.value;
1465
- }
1466
- }
1467
- return min;
1468
- }
1469
- get maxValue() {
1470
- let max = null;
1471
- for (const ch of this._def.checks) {
1472
- if (ch.kind === "max") {
1473
- if (max === null || ch.value < max)
1474
- max = ch.value;
1475
- }
1476
- }
1477
- return max;
1478
- }
1479
- }
1480
- ZodBigInt.create = (params) => {
1481
- return new ZodBigInt({
1482
- checks: [],
1483
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
1484
- coerce: params?.coerce ?? false,
1485
- ...processCreateParams(params),
1486
- });
1487
- };
1488
- export class ZodBoolean extends ZodType {
1489
- _parse(input) {
1490
- if (this._def.coerce) {
1491
- input.data = Boolean(input.data);
1492
- }
1493
- const parsedType = this._getType(input);
1494
- if (parsedType !== ZodParsedType.boolean) {
1495
- const ctx = this._getOrReturnCtx(input);
1496
- addIssueToContext(ctx, {
1497
- code: ZodIssueCode.invalid_type,
1498
- expected: ZodParsedType.boolean,
1499
- received: ctx.parsedType,
1500
- });
1501
- return INVALID;
1502
- }
1503
- return OK(input.data);
1504
- }
1505
- }
1506
- ZodBoolean.create = (params) => {
1507
- return new ZodBoolean({
1508
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
1509
- coerce: params?.coerce || false,
1510
- ...processCreateParams(params),
1511
- });
1512
- };
1513
- export class ZodDate extends ZodType {
1514
- _parse(input) {
1515
- if (this._def.coerce) {
1516
- input.data = new Date(input.data);
1517
- }
1518
- const parsedType = this._getType(input);
1519
- if (parsedType !== ZodParsedType.date) {
1520
- const ctx = this._getOrReturnCtx(input);
1521
- addIssueToContext(ctx, {
1522
- code: ZodIssueCode.invalid_type,
1523
- expected: ZodParsedType.date,
1524
- received: ctx.parsedType,
1525
- });
1526
- return INVALID;
1527
- }
1528
- if (Number.isNaN(input.data.getTime())) {
1529
- const ctx = this._getOrReturnCtx(input);
1530
- addIssueToContext(ctx, {
1531
- code: ZodIssueCode.invalid_date,
1532
- });
1533
- return INVALID;
1534
- }
1535
- const status = new ParseStatus();
1536
- let ctx = undefined;
1537
- for (const check of this._def.checks) {
1538
- if (check.kind === "min") {
1539
- if (input.data.getTime() < check.value) {
1540
- ctx = this._getOrReturnCtx(input, ctx);
1541
- addIssueToContext(ctx, {
1542
- code: ZodIssueCode.too_small,
1543
- message: check.message,
1544
- inclusive: true,
1545
- exact: false,
1546
- minimum: check.value,
1547
- type: "date",
1548
- });
1549
- status.dirty();
1550
- }
1551
- }
1552
- else if (check.kind === "max") {
1553
- if (input.data.getTime() > check.value) {
1554
- ctx = this._getOrReturnCtx(input, ctx);
1555
- addIssueToContext(ctx, {
1556
- code: ZodIssueCode.too_big,
1557
- message: check.message,
1558
- inclusive: true,
1559
- exact: false,
1560
- maximum: check.value,
1561
- type: "date",
1562
- });
1563
- status.dirty();
1564
- }
1565
- }
1566
- else {
1567
- util.assertNever(check);
1568
- }
1569
- }
1570
- return {
1571
- status: status.value,
1572
- value: new Date(input.data.getTime()),
1573
- };
1574
- }
1575
- _addCheck(check) {
1576
- return new ZodDate({
1577
- ...this._def,
1578
- checks: [...this._def.checks, check],
1579
- });
1580
- }
1581
- min(minDate, message) {
1582
- return this._addCheck({
1583
- kind: "min",
1584
- value: minDate.getTime(),
1585
- message: errorUtil.toString(message),
1586
- });
1587
- }
1588
- max(maxDate, message) {
1589
- return this._addCheck({
1590
- kind: "max",
1591
- value: maxDate.getTime(),
1592
- message: errorUtil.toString(message),
1593
- });
1594
- }
1595
- get minDate() {
1596
- let min = null;
1597
- for (const ch of this._def.checks) {
1598
- if (ch.kind === "min") {
1599
- if (min === null || ch.value > min)
1600
- min = ch.value;
1601
- }
1602
- }
1603
- return min != null ? new Date(min) : null;
1604
- }
1605
- get maxDate() {
1606
- let max = null;
1607
- for (const ch of this._def.checks) {
1608
- if (ch.kind === "max") {
1609
- if (max === null || ch.value < max)
1610
- max = ch.value;
1611
- }
1612
- }
1613
- return max != null ? new Date(max) : null;
1614
- }
1615
- }
1616
- ZodDate.create = (params) => {
1617
- return new ZodDate({
1618
- checks: [],
1619
- coerce: params?.coerce || false,
1620
- typeName: ZodFirstPartyTypeKind.ZodDate,
1621
- ...processCreateParams(params),
1622
- });
1623
- };
1624
- export class ZodSymbol extends ZodType {
1625
- _parse(input) {
1626
- const parsedType = this._getType(input);
1627
- if (parsedType !== ZodParsedType.symbol) {
1628
- const ctx = this._getOrReturnCtx(input);
1629
- addIssueToContext(ctx, {
1630
- code: ZodIssueCode.invalid_type,
1631
- expected: ZodParsedType.symbol,
1632
- received: ctx.parsedType,
1633
- });
1634
- return INVALID;
1635
- }
1636
- return OK(input.data);
1637
- }
1638
- }
1639
- ZodSymbol.create = (params) => {
1640
- return new ZodSymbol({
1641
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
1642
- ...processCreateParams(params),
1643
- });
1644
- };
1645
- export class ZodUndefined extends ZodType {
1646
- _parse(input) {
1647
- const parsedType = this._getType(input);
1648
- if (parsedType !== ZodParsedType.undefined) {
1649
- const ctx = this._getOrReturnCtx(input);
1650
- addIssueToContext(ctx, {
1651
- code: ZodIssueCode.invalid_type,
1652
- expected: ZodParsedType.undefined,
1653
- received: ctx.parsedType,
1654
- });
1655
- return INVALID;
1656
- }
1657
- return OK(input.data);
1658
- }
1659
- }
1660
- ZodUndefined.create = (params) => {
1661
- return new ZodUndefined({
1662
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
1663
- ...processCreateParams(params),
1664
- });
1665
- };
1666
- export class ZodNull extends ZodType {
1667
- _parse(input) {
1668
- const parsedType = this._getType(input);
1669
- if (parsedType !== ZodParsedType.null) {
1670
- const ctx = this._getOrReturnCtx(input);
1671
- addIssueToContext(ctx, {
1672
- code: ZodIssueCode.invalid_type,
1673
- expected: ZodParsedType.null,
1674
- received: ctx.parsedType,
1675
- });
1676
- return INVALID;
1677
- }
1678
- return OK(input.data);
1679
- }
1680
- }
1681
- ZodNull.create = (params) => {
1682
- return new ZodNull({
1683
- typeName: ZodFirstPartyTypeKind.ZodNull,
1684
- ...processCreateParams(params),
1685
- });
1686
- };
1687
- export class ZodAny extends ZodType {
1688
- constructor() {
1689
- super(...arguments);
1690
- // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
1691
- this._any = true;
1692
- }
1693
- _parse(input) {
1694
- return OK(input.data);
1695
- }
1696
- }
1697
- ZodAny.create = (params) => {
1698
- return new ZodAny({
1699
- typeName: ZodFirstPartyTypeKind.ZodAny,
1700
- ...processCreateParams(params),
1701
- });
1702
- };
1703
- export class ZodUnknown extends ZodType {
1704
- constructor() {
1705
- super(...arguments);
1706
- // required
1707
- this._unknown = true;
1708
- }
1709
- _parse(input) {
1710
- return OK(input.data);
1711
- }
1712
- }
1713
- ZodUnknown.create = (params) => {
1714
- return new ZodUnknown({
1715
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
1716
- ...processCreateParams(params),
1717
- });
1718
- };
1719
- export class ZodNever extends ZodType {
1720
- _parse(input) {
1721
- const ctx = this._getOrReturnCtx(input);
1722
- addIssueToContext(ctx, {
1723
- code: ZodIssueCode.invalid_type,
1724
- expected: ZodParsedType.never,
1725
- received: ctx.parsedType,
1726
- });
1727
- return INVALID;
1728
- }
1729
- }
1730
- ZodNever.create = (params) => {
1731
- return new ZodNever({
1732
- typeName: ZodFirstPartyTypeKind.ZodNever,
1733
- ...processCreateParams(params),
1734
- });
1735
- };
1736
- export class ZodVoid extends ZodType {
1737
- _parse(input) {
1738
- const parsedType = this._getType(input);
1739
- if (parsedType !== ZodParsedType.undefined) {
1740
- const ctx = this._getOrReturnCtx(input);
1741
- addIssueToContext(ctx, {
1742
- code: ZodIssueCode.invalid_type,
1743
- expected: ZodParsedType.void,
1744
- received: ctx.parsedType,
1745
- });
1746
- return INVALID;
1747
- }
1748
- return OK(input.data);
1749
- }
1750
- }
1751
- ZodVoid.create = (params) => {
1752
- return new ZodVoid({
1753
- typeName: ZodFirstPartyTypeKind.ZodVoid,
1754
- ...processCreateParams(params),
1755
- });
1756
- };
1757
- export class ZodArray extends ZodType {
1758
- _parse(input) {
1759
- const { ctx, status } = this._processInputParams(input);
1760
- const def = this._def;
1761
- if (ctx.parsedType !== ZodParsedType.array) {
1762
- addIssueToContext(ctx, {
1763
- code: ZodIssueCode.invalid_type,
1764
- expected: ZodParsedType.array,
1765
- received: ctx.parsedType,
1766
- });
1767
- return INVALID;
1768
- }
1769
- if (def.exactLength !== null) {
1770
- const tooBig = ctx.data.length > def.exactLength.value;
1771
- const tooSmall = ctx.data.length < def.exactLength.value;
1772
- if (tooBig || tooSmall) {
1773
- addIssueToContext(ctx, {
1774
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
1775
- minimum: (tooSmall ? def.exactLength.value : undefined),
1776
- maximum: (tooBig ? def.exactLength.value : undefined),
1777
- type: "array",
1778
- inclusive: true,
1779
- exact: true,
1780
- message: def.exactLength.message,
1781
- });
1782
- status.dirty();
1783
- }
1784
- }
1785
- if (def.minLength !== null) {
1786
- if (ctx.data.length < def.minLength.value) {
1787
- addIssueToContext(ctx, {
1788
- code: ZodIssueCode.too_small,
1789
- minimum: def.minLength.value,
1790
- type: "array",
1791
- inclusive: true,
1792
- exact: false,
1793
- message: def.minLength.message,
1794
- });
1795
- status.dirty();
1796
- }
1797
- }
1798
- if (def.maxLength !== null) {
1799
- if (ctx.data.length > def.maxLength.value) {
1800
- addIssueToContext(ctx, {
1801
- code: ZodIssueCode.too_big,
1802
- maximum: def.maxLength.value,
1803
- type: "array",
1804
- inclusive: true,
1805
- exact: false,
1806
- message: def.maxLength.message,
1807
- });
1808
- status.dirty();
1809
- }
1810
- }
1811
- if (ctx.common.async) {
1812
- return Promise.all([...ctx.data].map((item, i) => {
1813
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
1814
- })).then((result) => {
1815
- return ParseStatus.mergeArray(status, result);
1816
- });
1817
- }
1818
- const result = [...ctx.data].map((item, i) => {
1819
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
1820
- });
1821
- return ParseStatus.mergeArray(status, result);
1822
- }
1823
- get element() {
1824
- return this._def.type;
1825
- }
1826
- min(minLength, message) {
1827
- return new ZodArray({
1828
- ...this._def,
1829
- minLength: { value: minLength, message: errorUtil.toString(message) },
1830
- });
1831
- }
1832
- max(maxLength, message) {
1833
- return new ZodArray({
1834
- ...this._def,
1835
- maxLength: { value: maxLength, message: errorUtil.toString(message) },
1836
- });
1837
- }
1838
- length(len, message) {
1839
- return new ZodArray({
1840
- ...this._def,
1841
- exactLength: { value: len, message: errorUtil.toString(message) },
1842
- });
1843
- }
1844
- nonempty(message) {
1845
- return this.min(1, message);
1846
- }
1847
- }
1848
- ZodArray.create = (schema, params) => {
1849
- return new ZodArray({
1850
- type: schema,
1851
- minLength: null,
1852
- maxLength: null,
1853
- exactLength: null,
1854
- typeName: ZodFirstPartyTypeKind.ZodArray,
1855
- ...processCreateParams(params),
1856
- });
1857
- };
1858
- function deepPartialify(schema) {
1859
- if (schema instanceof ZodObject) {
1860
- const newShape = {};
1861
- for (const key in schema.shape) {
1862
- const fieldSchema = schema.shape[key];
1863
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
1864
- }
1865
- return new ZodObject({
1866
- ...schema._def,
1867
- shape: () => newShape,
1868
- });
1869
- }
1870
- else if (schema instanceof ZodArray) {
1871
- return new ZodArray({
1872
- ...schema._def,
1873
- type: deepPartialify(schema.element),
1874
- });
1875
- }
1876
- else if (schema instanceof ZodOptional) {
1877
- return ZodOptional.create(deepPartialify(schema.unwrap()));
1878
- }
1879
- else if (schema instanceof ZodNullable) {
1880
- return ZodNullable.create(deepPartialify(schema.unwrap()));
1881
- }
1882
- else if (schema instanceof ZodTuple) {
1883
- return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
1884
- }
1885
- else {
1886
- return schema;
1887
- }
1888
- }
1889
- export class ZodObject extends ZodType {
1890
- constructor() {
1891
- super(...arguments);
1892
- this._cached = null;
1893
- /**
1894
- * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
1895
- * If you want to pass through unknown properties, use `.passthrough()` instead.
1896
- */
1897
- this.nonstrict = this.passthrough;
1898
- // extend<
1899
- // Augmentation extends ZodRawShape,
1900
- // NewOutput extends util.flatten<{
1901
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
1902
- // ? Augmentation[k]["_output"]
1903
- // : k extends keyof Output
1904
- // ? Output[k]
1905
- // : never;
1906
- // }>,
1907
- // NewInput extends util.flatten<{
1908
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
1909
- // ? Augmentation[k]["_input"]
1910
- // : k extends keyof Input
1911
- // ? Input[k]
1912
- // : never;
1913
- // }>
1914
- // >(
1915
- // augmentation: Augmentation
1916
- // ): ZodObject<
1917
- // extendShape<T, Augmentation>,
1918
- // UnknownKeys,
1919
- // Catchall,
1920
- // NewOutput,
1921
- // NewInput
1922
- // > {
1923
- // return new ZodObject({
1924
- // ...this._def,
1925
- // shape: () => ({
1926
- // ...this._def.shape(),
1927
- // ...augmentation,
1928
- // }),
1929
- // }) as any;
1930
- // }
1931
- /**
1932
- * @deprecated Use `.extend` instead
1933
- * */
1934
- this.augment = this.extend;
1935
- }
1936
- _getCached() {
1937
- if (this._cached !== null)
1938
- return this._cached;
1939
- const shape = this._def.shape();
1940
- const keys = util.objectKeys(shape);
1941
- this._cached = { shape, keys };
1942
- return this._cached;
1943
- }
1944
- _parse(input) {
1945
- const parsedType = this._getType(input);
1946
- if (parsedType !== ZodParsedType.object) {
1947
- const ctx = this._getOrReturnCtx(input);
1948
- addIssueToContext(ctx, {
1949
- code: ZodIssueCode.invalid_type,
1950
- expected: ZodParsedType.object,
1951
- received: ctx.parsedType,
1952
- });
1953
- return INVALID;
1954
- }
1955
- const { status, ctx } = this._processInputParams(input);
1956
- const { shape, keys: shapeKeys } = this._getCached();
1957
- const extraKeys = [];
1958
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
1959
- for (const key in ctx.data) {
1960
- if (!shapeKeys.includes(key)) {
1961
- extraKeys.push(key);
1962
- }
1963
- }
1964
- }
1965
- const pairs = [];
1966
- for (const key of shapeKeys) {
1967
- const keyValidator = shape[key];
1968
- const value = ctx.data[key];
1969
- pairs.push({
1970
- key: { status: "valid", value: key },
1971
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
1972
- alwaysSet: key in ctx.data,
1973
- });
1974
- }
1975
- if (this._def.catchall instanceof ZodNever) {
1976
- const unknownKeys = this._def.unknownKeys;
1977
- if (unknownKeys === "passthrough") {
1978
- for (const key of extraKeys) {
1979
- pairs.push({
1980
- key: { status: "valid", value: key },
1981
- value: { status: "valid", value: ctx.data[key] },
1982
- });
1983
- }
1984
- }
1985
- else if (unknownKeys === "strict") {
1986
- if (extraKeys.length > 0) {
1987
- addIssueToContext(ctx, {
1988
- code: ZodIssueCode.unrecognized_keys,
1989
- keys: extraKeys,
1990
- });
1991
- status.dirty();
1992
- }
1993
- }
1994
- else if (unknownKeys === "strip") {
1995
- }
1996
- else {
1997
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
1998
- }
1999
- }
2000
- else {
2001
- // run catchall validation
2002
- const catchall = this._def.catchall;
2003
- for (const key of extraKeys) {
2004
- const value = ctx.data[key];
2005
- pairs.push({
2006
- key: { status: "valid", value: key },
2007
- value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
2008
- ),
2009
- alwaysSet: key in ctx.data,
2010
- });
2011
- }
2012
- }
2013
- if (ctx.common.async) {
2014
- return Promise.resolve()
2015
- .then(async () => {
2016
- const syncPairs = [];
2017
- for (const pair of pairs) {
2018
- const key = await pair.key;
2019
- const value = await pair.value;
2020
- syncPairs.push({
2021
- key,
2022
- value,
2023
- alwaysSet: pair.alwaysSet,
2024
- });
2025
- }
2026
- return syncPairs;
2027
- })
2028
- .then((syncPairs) => {
2029
- return ParseStatus.mergeObjectSync(status, syncPairs);
2030
- });
2031
- }
2032
- else {
2033
- return ParseStatus.mergeObjectSync(status, pairs);
2034
- }
2035
- }
2036
- get shape() {
2037
- return this._def.shape();
2038
- }
2039
- strict(message) {
2040
- errorUtil.errToObj;
2041
- return new ZodObject({
2042
- ...this._def,
2043
- unknownKeys: "strict",
2044
- ...(message !== undefined
2045
- ? {
2046
- errorMap: (issue, ctx) => {
2047
- const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2048
- if (issue.code === "unrecognized_keys")
2049
- return {
2050
- message: errorUtil.errToObj(message).message ?? defaultError,
2051
- };
2052
- return {
2053
- message: defaultError,
2054
- };
2055
- },
2056
- }
2057
- : {}),
2058
- });
2059
- }
2060
- strip() {
2061
- return new ZodObject({
2062
- ...this._def,
2063
- unknownKeys: "strip",
2064
- });
2065
- }
2066
- passthrough() {
2067
- return new ZodObject({
2068
- ...this._def,
2069
- unknownKeys: "passthrough",
2070
- });
2071
- }
2072
- // const AugmentFactory =
2073
- // <Def extends ZodObjectDef>(def: Def) =>
2074
- // <Augmentation extends ZodRawShape>(
2075
- // augmentation: Augmentation
2076
- // ): ZodObject<
2077
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
2078
- // Def["unknownKeys"],
2079
- // Def["catchall"]
2080
- // > => {
2081
- // return new ZodObject({
2082
- // ...def,
2083
- // shape: () => ({
2084
- // ...def.shape(),
2085
- // ...augmentation,
2086
- // }),
2087
- // }) as any;
2088
- // };
2089
- extend(augmentation) {
2090
- return new ZodObject({
2091
- ...this._def,
2092
- shape: () => ({
2093
- ...this._def.shape(),
2094
- ...augmentation,
2095
- }),
2096
- });
2097
- }
2098
- /**
2099
- * Prior to zod@1.0.12 there was a bug in the
2100
- * inferred type of merged objects. Please
2101
- * upgrade if you are experiencing issues.
2102
- */
2103
- merge(merging) {
2104
- const merged = new ZodObject({
2105
- unknownKeys: merging._def.unknownKeys,
2106
- catchall: merging._def.catchall,
2107
- shape: () => ({
2108
- ...this._def.shape(),
2109
- ...merging._def.shape(),
2110
- }),
2111
- typeName: ZodFirstPartyTypeKind.ZodObject,
2112
- });
2113
- return merged;
2114
- }
2115
- // merge<
2116
- // Incoming extends AnyZodObject,
2117
- // Augmentation extends Incoming["shape"],
2118
- // NewOutput extends {
2119
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
2120
- // ? Augmentation[k]["_output"]
2121
- // : k extends keyof Output
2122
- // ? Output[k]
2123
- // : never;
2124
- // },
2125
- // NewInput extends {
2126
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
2127
- // ? Augmentation[k]["_input"]
2128
- // : k extends keyof Input
2129
- // ? Input[k]
2130
- // : never;
2131
- // }
2132
- // >(
2133
- // merging: Incoming
2134
- // ): ZodObject<
2135
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2136
- // Incoming["_def"]["unknownKeys"],
2137
- // Incoming["_def"]["catchall"],
2138
- // NewOutput,
2139
- // NewInput
2140
- // > {
2141
- // const merged: any = new ZodObject({
2142
- // unknownKeys: merging._def.unknownKeys,
2143
- // catchall: merging._def.catchall,
2144
- // shape: () =>
2145
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2146
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2147
- // }) as any;
2148
- // return merged;
2149
- // }
2150
- setKey(key, schema) {
2151
- return this.augment({ [key]: schema });
2152
- }
2153
- // merge<Incoming extends AnyZodObject>(
2154
- // merging: Incoming
2155
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
2156
- // ZodObject<
2157
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
2158
- // Incoming["_def"]["unknownKeys"],
2159
- // Incoming["_def"]["catchall"]
2160
- // > {
2161
- // // const mergedShape = objectUtil.mergeShapes(
2162
- // // this._def.shape(),
2163
- // // merging._def.shape()
2164
- // // );
2165
- // const merged: any = new ZodObject({
2166
- // unknownKeys: merging._def.unknownKeys,
2167
- // catchall: merging._def.catchall,
2168
- // shape: () =>
2169
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
2170
- // typeName: ZodFirstPartyTypeKind.ZodObject,
2171
- // }) as any;
2172
- // return merged;
2173
- // }
2174
- catchall(index) {
2175
- return new ZodObject({
2176
- ...this._def,
2177
- catchall: index,
2178
- });
2179
- }
2180
- pick(mask) {
2181
- const shape = {};
2182
- for (const key of util.objectKeys(mask)) {
2183
- if (mask[key] && this.shape[key]) {
2184
- shape[key] = this.shape[key];
2185
- }
2186
- }
2187
- return new ZodObject({
2188
- ...this._def,
2189
- shape: () => shape,
2190
- });
2191
- }
2192
- omit(mask) {
2193
- const shape = {};
2194
- for (const key of util.objectKeys(this.shape)) {
2195
- if (!mask[key]) {
2196
- shape[key] = this.shape[key];
2197
- }
2198
- }
2199
- return new ZodObject({
2200
- ...this._def,
2201
- shape: () => shape,
2202
- });
2203
- }
2204
- /**
2205
- * @deprecated
2206
- */
2207
- deepPartial() {
2208
- return deepPartialify(this);
2209
- }
2210
- partial(mask) {
2211
- const newShape = {};
2212
- for (const key of util.objectKeys(this.shape)) {
2213
- const fieldSchema = this.shape[key];
2214
- if (mask && !mask[key]) {
2215
- newShape[key] = fieldSchema;
2216
- }
2217
- else {
2218
- newShape[key] = fieldSchema.optional();
2219
- }
2220
- }
2221
- return new ZodObject({
2222
- ...this._def,
2223
- shape: () => newShape,
2224
- });
2225
- }
2226
- required(mask) {
2227
- const newShape = {};
2228
- for (const key of util.objectKeys(this.shape)) {
2229
- if (mask && !mask[key]) {
2230
- newShape[key] = this.shape[key];
2231
- }
2232
- else {
2233
- const fieldSchema = this.shape[key];
2234
- let newField = fieldSchema;
2235
- while (newField instanceof ZodOptional) {
2236
- newField = newField._def.innerType;
2237
- }
2238
- newShape[key] = newField;
2239
- }
2240
- }
2241
- return new ZodObject({
2242
- ...this._def,
2243
- shape: () => newShape,
2244
- });
2245
- }
2246
- keyof() {
2247
- return createZodEnum(util.objectKeys(this.shape));
2248
- }
2249
- }
2250
- ZodObject.create = (shape, params) => {
2251
- return new ZodObject({
2252
- shape: () => shape,
2253
- unknownKeys: "strip",
2254
- catchall: ZodNever.create(),
2255
- typeName: ZodFirstPartyTypeKind.ZodObject,
2256
- ...processCreateParams(params),
2257
- });
2258
- };
2259
- ZodObject.strictCreate = (shape, params) => {
2260
- return new ZodObject({
2261
- shape: () => shape,
2262
- unknownKeys: "strict",
2263
- catchall: ZodNever.create(),
2264
- typeName: ZodFirstPartyTypeKind.ZodObject,
2265
- ...processCreateParams(params),
2266
- });
2267
- };
2268
- ZodObject.lazycreate = (shape, params) => {
2269
- return new ZodObject({
2270
- shape,
2271
- unknownKeys: "strip",
2272
- catchall: ZodNever.create(),
2273
- typeName: ZodFirstPartyTypeKind.ZodObject,
2274
- ...processCreateParams(params),
2275
- });
2276
- };
2277
- export class ZodUnion extends ZodType {
2278
- _parse(input) {
2279
- const { ctx } = this._processInputParams(input);
2280
- const options = this._def.options;
2281
- function handleResults(results) {
2282
- // return first issue-free validation if it exists
2283
- for (const result of results) {
2284
- if (result.result.status === "valid") {
2285
- return result.result;
2286
- }
2287
- }
2288
- for (const result of results) {
2289
- if (result.result.status === "dirty") {
2290
- // add issues from dirty option
2291
- ctx.common.issues.push(...result.ctx.common.issues);
2292
- return result.result;
2293
- }
2294
- }
2295
- // return invalid
2296
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2297
- addIssueToContext(ctx, {
2298
- code: ZodIssueCode.invalid_union,
2299
- unionErrors,
2300
- });
2301
- return INVALID;
2302
- }
2303
- if (ctx.common.async) {
2304
- return Promise.all(options.map(async (option) => {
2305
- const childCtx = {
2306
- ...ctx,
2307
- common: {
2308
- ...ctx.common,
2309
- issues: [],
2310
- },
2311
- parent: null,
2312
- };
2313
- return {
2314
- result: await option._parseAsync({
2315
- data: ctx.data,
2316
- path: ctx.path,
2317
- parent: childCtx,
2318
- }),
2319
- ctx: childCtx,
2320
- };
2321
- })).then(handleResults);
2322
- }
2323
- else {
2324
- let dirty = undefined;
2325
- const issues = [];
2326
- for (const option of options) {
2327
- const childCtx = {
2328
- ...ctx,
2329
- common: {
2330
- ...ctx.common,
2331
- issues: [],
2332
- },
2333
- parent: null,
2334
- };
2335
- const result = option._parseSync({
2336
- data: ctx.data,
2337
- path: ctx.path,
2338
- parent: childCtx,
2339
- });
2340
- if (result.status === "valid") {
2341
- return result;
2342
- }
2343
- else if (result.status === "dirty" && !dirty) {
2344
- dirty = { result, ctx: childCtx };
2345
- }
2346
- if (childCtx.common.issues.length) {
2347
- issues.push(childCtx.common.issues);
2348
- }
2349
- }
2350
- if (dirty) {
2351
- ctx.common.issues.push(...dirty.ctx.common.issues);
2352
- return dirty.result;
2353
- }
2354
- const unionErrors = issues.map((issues) => new ZodError(issues));
2355
- addIssueToContext(ctx, {
2356
- code: ZodIssueCode.invalid_union,
2357
- unionErrors,
2358
- });
2359
- return INVALID;
2360
- }
2361
- }
2362
- get options() {
2363
- return this._def.options;
2364
- }
2365
- }
2366
- ZodUnion.create = (types, params) => {
2367
- return new ZodUnion({
2368
- options: types,
2369
- typeName: ZodFirstPartyTypeKind.ZodUnion,
2370
- ...processCreateParams(params),
2371
- });
2372
- };
2373
- /////////////////////////////////////////////////////
2374
- /////////////////////////////////////////////////////
2375
- ////////// //////////
2376
- ////////// ZodDiscriminatedUnion //////////
2377
- ////////// //////////
2378
- /////////////////////////////////////////////////////
2379
- /////////////////////////////////////////////////////
2380
- const getDiscriminator = (type) => {
2381
- if (type instanceof ZodLazy) {
2382
- return getDiscriminator(type.schema);
2383
- }
2384
- else if (type instanceof ZodEffects) {
2385
- return getDiscriminator(type.innerType());
2386
- }
2387
- else if (type instanceof ZodLiteral) {
2388
- return [type.value];
2389
- }
2390
- else if (type instanceof ZodEnum) {
2391
- return type.options;
2392
- }
2393
- else if (type instanceof ZodNativeEnum) {
2394
- // eslint-disable-next-line ban/ban
2395
- return util.objectValues(type.enum);
2396
- }
2397
- else if (type instanceof ZodDefault) {
2398
- return getDiscriminator(type._def.innerType);
2399
- }
2400
- else if (type instanceof ZodUndefined) {
2401
- return [undefined];
2402
- }
2403
- else if (type instanceof ZodNull) {
2404
- return [null];
2405
- }
2406
- else if (type instanceof ZodOptional) {
2407
- return [undefined, ...getDiscriminator(type.unwrap())];
2408
- }
2409
- else if (type instanceof ZodNullable) {
2410
- return [null, ...getDiscriminator(type.unwrap())];
2411
- }
2412
- else if (type instanceof ZodBranded) {
2413
- return getDiscriminator(type.unwrap());
2414
- }
2415
- else if (type instanceof ZodReadonly) {
2416
- return getDiscriminator(type.unwrap());
2417
- }
2418
- else if (type instanceof ZodCatch) {
2419
- return getDiscriminator(type._def.innerType);
2420
- }
2421
- else {
2422
- return [];
2423
- }
2424
- };
2425
- export class ZodDiscriminatedUnion extends ZodType {
2426
- _parse(input) {
2427
- const { ctx } = this._processInputParams(input);
2428
- if (ctx.parsedType !== ZodParsedType.object) {
2429
- addIssueToContext(ctx, {
2430
- code: ZodIssueCode.invalid_type,
2431
- expected: ZodParsedType.object,
2432
- received: ctx.parsedType,
2433
- });
2434
- return INVALID;
2435
- }
2436
- const discriminator = this.discriminator;
2437
- const discriminatorValue = ctx.data[discriminator];
2438
- const option = this.optionsMap.get(discriminatorValue);
2439
- if (!option) {
2440
- addIssueToContext(ctx, {
2441
- code: ZodIssueCode.invalid_union_discriminator,
2442
- options: Array.from(this.optionsMap.keys()),
2443
- path: [discriminator],
2444
- });
2445
- return INVALID;
2446
- }
2447
- if (ctx.common.async) {
2448
- return option._parseAsync({
2449
- data: ctx.data,
2450
- path: ctx.path,
2451
- parent: ctx,
2452
- });
2453
- }
2454
- else {
2455
- return option._parseSync({
2456
- data: ctx.data,
2457
- path: ctx.path,
2458
- parent: ctx,
2459
- });
2460
- }
2461
- }
2462
- get discriminator() {
2463
- return this._def.discriminator;
2464
- }
2465
- get options() {
2466
- return this._def.options;
2467
- }
2468
- get optionsMap() {
2469
- return this._def.optionsMap;
2470
- }
2471
- /**
2472
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2473
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2474
- * have a different value for each object in the union.
2475
- * @param discriminator the name of the discriminator property
2476
- * @param types an array of object schemas
2477
- * @param params
2478
- */
2479
- static create(discriminator, options, params) {
2480
- // Get all the valid discriminator values
2481
- const optionsMap = new Map();
2482
- // try {
2483
- for (const type of options) {
2484
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2485
- if (!discriminatorValues.length) {
2486
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2487
- }
2488
- for (const value of discriminatorValues) {
2489
- if (optionsMap.has(value)) {
2490
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2491
- }
2492
- optionsMap.set(value, type);
2493
- }
2494
- }
2495
- return new ZodDiscriminatedUnion({
2496
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2497
- discriminator,
2498
- options,
2499
- optionsMap,
2500
- ...processCreateParams(params),
2501
- });
2502
- }
2503
- }
2504
- function mergeValues(a, b) {
2505
- const aType = getParsedType(a);
2506
- const bType = getParsedType(b);
2507
- if (a === b) {
2508
- return { valid: true, data: a };
2509
- }
2510
- else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2511
- const bKeys = util.objectKeys(b);
2512
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2513
- const newObj = { ...a, ...b };
2514
- for (const key of sharedKeys) {
2515
- const sharedValue = mergeValues(a[key], b[key]);
2516
- if (!sharedValue.valid) {
2517
- return { valid: false };
2518
- }
2519
- newObj[key] = sharedValue.data;
2520
- }
2521
- return { valid: true, data: newObj };
2522
- }
2523
- else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2524
- if (a.length !== b.length) {
2525
- return { valid: false };
2526
- }
2527
- const newArray = [];
2528
- for (let index = 0; index < a.length; index++) {
2529
- const itemA = a[index];
2530
- const itemB = b[index];
2531
- const sharedValue = mergeValues(itemA, itemB);
2532
- if (!sharedValue.valid) {
2533
- return { valid: false };
2534
- }
2535
- newArray.push(sharedValue.data);
2536
- }
2537
- return { valid: true, data: newArray };
2538
- }
2539
- else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
2540
- return { valid: true, data: a };
2541
- }
2542
- else {
2543
- return { valid: false };
2544
- }
2545
- }
2546
- export class ZodIntersection extends ZodType {
2547
- _parse(input) {
2548
- const { status, ctx } = this._processInputParams(input);
2549
- const handleParsed = (parsedLeft, parsedRight) => {
2550
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
2551
- return INVALID;
2552
- }
2553
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
2554
- if (!merged.valid) {
2555
- addIssueToContext(ctx, {
2556
- code: ZodIssueCode.invalid_intersection_types,
2557
- });
2558
- return INVALID;
2559
- }
2560
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
2561
- status.dirty();
2562
- }
2563
- return { status: status.value, value: merged.data };
2564
- };
2565
- if (ctx.common.async) {
2566
- return Promise.all([
2567
- this._def.left._parseAsync({
2568
- data: ctx.data,
2569
- path: ctx.path,
2570
- parent: ctx,
2571
- }),
2572
- this._def.right._parseAsync({
2573
- data: ctx.data,
2574
- path: ctx.path,
2575
- parent: ctx,
2576
- }),
2577
- ]).then(([left, right]) => handleParsed(left, right));
2578
- }
2579
- else {
2580
- return handleParsed(this._def.left._parseSync({
2581
- data: ctx.data,
2582
- path: ctx.path,
2583
- parent: ctx,
2584
- }), this._def.right._parseSync({
2585
- data: ctx.data,
2586
- path: ctx.path,
2587
- parent: ctx,
2588
- }));
2589
- }
2590
- }
2591
- }
2592
- ZodIntersection.create = (left, right, params) => {
2593
- return new ZodIntersection({
2594
- left: left,
2595
- right: right,
2596
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
2597
- ...processCreateParams(params),
2598
- });
2599
- };
2600
- // type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];
2601
- export class ZodTuple extends ZodType {
2602
- _parse(input) {
2603
- const { status, ctx } = this._processInputParams(input);
2604
- if (ctx.parsedType !== ZodParsedType.array) {
2605
- addIssueToContext(ctx, {
2606
- code: ZodIssueCode.invalid_type,
2607
- expected: ZodParsedType.array,
2608
- received: ctx.parsedType,
2609
- });
2610
- return INVALID;
2611
- }
2612
- if (ctx.data.length < this._def.items.length) {
2613
- addIssueToContext(ctx, {
2614
- code: ZodIssueCode.too_small,
2615
- minimum: this._def.items.length,
2616
- inclusive: true,
2617
- exact: false,
2618
- type: "array",
2619
- });
2620
- return INVALID;
2621
- }
2622
- const rest = this._def.rest;
2623
- if (!rest && ctx.data.length > this._def.items.length) {
2624
- addIssueToContext(ctx, {
2625
- code: ZodIssueCode.too_big,
2626
- maximum: this._def.items.length,
2627
- inclusive: true,
2628
- exact: false,
2629
- type: "array",
2630
- });
2631
- status.dirty();
2632
- }
2633
- const items = [...ctx.data]
2634
- .map((item, itemIndex) => {
2635
- const schema = this._def.items[itemIndex] || this._def.rest;
2636
- if (!schema)
2637
- return null;
2638
- return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2639
- })
2640
- .filter((x) => !!x); // filter nulls
2641
- if (ctx.common.async) {
2642
- return Promise.all(items).then((results) => {
2643
- return ParseStatus.mergeArray(status, results);
2644
- });
2645
- }
2646
- else {
2647
- return ParseStatus.mergeArray(status, items);
2648
- }
2649
- }
2650
- get items() {
2651
- return this._def.items;
2652
- }
2653
- rest(rest) {
2654
- return new ZodTuple({
2655
- ...this._def,
2656
- rest,
2657
- });
2658
- }
2659
- }
2660
- ZodTuple.create = (schemas, params) => {
2661
- if (!Array.isArray(schemas)) {
2662
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2663
- }
2664
- return new ZodTuple({
2665
- items: schemas,
2666
- typeName: ZodFirstPartyTypeKind.ZodTuple,
2667
- rest: null,
2668
- ...processCreateParams(params),
2669
- });
2670
- };
2671
- export class ZodRecord extends ZodType {
2672
- get keySchema() {
2673
- return this._def.keyType;
2674
- }
2675
- get valueSchema() {
2676
- return this._def.valueType;
2677
- }
2678
- _parse(input) {
2679
- const { status, ctx } = this._processInputParams(input);
2680
- if (ctx.parsedType !== ZodParsedType.object) {
2681
- addIssueToContext(ctx, {
2682
- code: ZodIssueCode.invalid_type,
2683
- expected: ZodParsedType.object,
2684
- received: ctx.parsedType,
2685
- });
2686
- return INVALID;
2687
- }
2688
- const pairs = [];
2689
- const keyType = this._def.keyType;
2690
- const valueType = this._def.valueType;
2691
- for (const key in ctx.data) {
2692
- pairs.push({
2693
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
2694
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
2695
- alwaysSet: key in ctx.data,
2696
- });
2697
- }
2698
- if (ctx.common.async) {
2699
- return ParseStatus.mergeObjectAsync(status, pairs);
2700
- }
2701
- else {
2702
- return ParseStatus.mergeObjectSync(status, pairs);
2703
- }
2704
- }
2705
- get element() {
2706
- return this._def.valueType;
2707
- }
2708
- static create(first, second, third) {
2709
- if (second instanceof ZodType) {
2710
- return new ZodRecord({
2711
- keyType: first,
2712
- valueType: second,
2713
- typeName: ZodFirstPartyTypeKind.ZodRecord,
2714
- ...processCreateParams(third),
2715
- });
2716
- }
2717
- return new ZodRecord({
2718
- keyType: ZodString.create(),
2719
- valueType: first,
2720
- typeName: ZodFirstPartyTypeKind.ZodRecord,
2721
- ...processCreateParams(second),
2722
- });
2723
- }
2724
- }
2725
- export class ZodMap extends ZodType {
2726
- get keySchema() {
2727
- return this._def.keyType;
2728
- }
2729
- get valueSchema() {
2730
- return this._def.valueType;
2731
- }
2732
- _parse(input) {
2733
- const { status, ctx } = this._processInputParams(input);
2734
- if (ctx.parsedType !== ZodParsedType.map) {
2735
- addIssueToContext(ctx, {
2736
- code: ZodIssueCode.invalid_type,
2737
- expected: ZodParsedType.map,
2738
- received: ctx.parsedType,
2739
- });
2740
- return INVALID;
2741
- }
2742
- const keyType = this._def.keyType;
2743
- const valueType = this._def.valueType;
2744
- const pairs = [...ctx.data.entries()].map(([key, value], index) => {
2745
- return {
2746
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
2747
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
2748
- };
2749
- });
2750
- if (ctx.common.async) {
2751
- const finalMap = new Map();
2752
- return Promise.resolve().then(async () => {
2753
- for (const pair of pairs) {
2754
- const key = await pair.key;
2755
- const value = await pair.value;
2756
- if (key.status === "aborted" || value.status === "aborted") {
2757
- return INVALID;
2758
- }
2759
- if (key.status === "dirty" || value.status === "dirty") {
2760
- status.dirty();
2761
- }
2762
- finalMap.set(key.value, value.value);
2763
- }
2764
- return { status: status.value, value: finalMap };
2765
- });
2766
- }
2767
- else {
2768
- const finalMap = new Map();
2769
- for (const pair of pairs) {
2770
- const key = pair.key;
2771
- const value = pair.value;
2772
- if (key.status === "aborted" || value.status === "aborted") {
2773
- return INVALID;
2774
- }
2775
- if (key.status === "dirty" || value.status === "dirty") {
2776
- status.dirty();
2777
- }
2778
- finalMap.set(key.value, value.value);
2779
- }
2780
- return { status: status.value, value: finalMap };
2781
- }
2782
- }
2783
- }
2784
- ZodMap.create = (keyType, valueType, params) => {
2785
- return new ZodMap({
2786
- valueType,
2787
- keyType,
2788
- typeName: ZodFirstPartyTypeKind.ZodMap,
2789
- ...processCreateParams(params),
2790
- });
2791
- };
2792
- export class ZodSet extends ZodType {
2793
- _parse(input) {
2794
- const { status, ctx } = this._processInputParams(input);
2795
- if (ctx.parsedType !== ZodParsedType.set) {
2796
- addIssueToContext(ctx, {
2797
- code: ZodIssueCode.invalid_type,
2798
- expected: ZodParsedType.set,
2799
- received: ctx.parsedType,
2800
- });
2801
- return INVALID;
2802
- }
2803
- const def = this._def;
2804
- if (def.minSize !== null) {
2805
- if (ctx.data.size < def.minSize.value) {
2806
- addIssueToContext(ctx, {
2807
- code: ZodIssueCode.too_small,
2808
- minimum: def.minSize.value,
2809
- type: "set",
2810
- inclusive: true,
2811
- exact: false,
2812
- message: def.minSize.message,
2813
- });
2814
- status.dirty();
2815
- }
2816
- }
2817
- if (def.maxSize !== null) {
2818
- if (ctx.data.size > def.maxSize.value) {
2819
- addIssueToContext(ctx, {
2820
- code: ZodIssueCode.too_big,
2821
- maximum: def.maxSize.value,
2822
- type: "set",
2823
- inclusive: true,
2824
- exact: false,
2825
- message: def.maxSize.message,
2826
- });
2827
- status.dirty();
2828
- }
2829
- }
2830
- const valueType = this._def.valueType;
2831
- function finalizeSet(elements) {
2832
- const parsedSet = new Set();
2833
- for (const element of elements) {
2834
- if (element.status === "aborted")
2835
- return INVALID;
2836
- if (element.status === "dirty")
2837
- status.dirty();
2838
- parsedSet.add(element.value);
2839
- }
2840
- return { status: status.value, value: parsedSet };
2841
- }
2842
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
2843
- if (ctx.common.async) {
2844
- return Promise.all(elements).then((elements) => finalizeSet(elements));
2845
- }
2846
- else {
2847
- return finalizeSet(elements);
2848
- }
2849
- }
2850
- min(minSize, message) {
2851
- return new ZodSet({
2852
- ...this._def,
2853
- minSize: { value: minSize, message: errorUtil.toString(message) },
2854
- });
2855
- }
2856
- max(maxSize, message) {
2857
- return new ZodSet({
2858
- ...this._def,
2859
- maxSize: { value: maxSize, message: errorUtil.toString(message) },
2860
- });
2861
- }
2862
- size(size, message) {
2863
- return this.min(size, message).max(size, message);
2864
- }
2865
- nonempty(message) {
2866
- return this.min(1, message);
2867
- }
2868
- }
2869
- ZodSet.create = (valueType, params) => {
2870
- return new ZodSet({
2871
- valueType,
2872
- minSize: null,
2873
- maxSize: null,
2874
- typeName: ZodFirstPartyTypeKind.ZodSet,
2875
- ...processCreateParams(params),
2876
- });
2877
- };
2878
- export class ZodFunction extends ZodType {
2879
- constructor() {
2880
- super(...arguments);
2881
- this.validate = this.implement;
2882
- }
2883
- _parse(input) {
2884
- const { ctx } = this._processInputParams(input);
2885
- if (ctx.parsedType !== ZodParsedType.function) {
2886
- addIssueToContext(ctx, {
2887
- code: ZodIssueCode.invalid_type,
2888
- expected: ZodParsedType.function,
2889
- received: ctx.parsedType,
2890
- });
2891
- return INVALID;
2892
- }
2893
- function makeArgsIssue(args, error) {
2894
- return makeIssue({
2895
- data: args,
2896
- path: ctx.path,
2897
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),
2898
- issueData: {
2899
- code: ZodIssueCode.invalid_arguments,
2900
- argumentsError: error,
2901
- },
2902
- });
2903
- }
2904
- function makeReturnsIssue(returns, error) {
2905
- return makeIssue({
2906
- data: returns,
2907
- path: ctx.path,
2908
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),
2909
- issueData: {
2910
- code: ZodIssueCode.invalid_return_type,
2911
- returnTypeError: error,
2912
- },
2913
- });
2914
- }
2915
- const params = { errorMap: ctx.common.contextualErrorMap };
2916
- const fn = ctx.data;
2917
- if (this._def.returns instanceof ZodPromise) {
2918
- // Would love a way to avoid disabling this rule, but we need
2919
- // an alias (using an arrow function was what caused 2651).
2920
- // eslint-disable-next-line @typescript-eslint/no-this-alias
2921
- const me = this;
2922
- return OK(async function (...args) {
2923
- const error = new ZodError([]);
2924
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
2925
- error.addIssue(makeArgsIssue(args, e));
2926
- throw error;
2927
- });
2928
- const result = await Reflect.apply(fn, this, parsedArgs);
2929
- const parsedReturns = await me._def.returns._def.type
2930
- .parseAsync(result, params)
2931
- .catch((e) => {
2932
- error.addIssue(makeReturnsIssue(result, e));
2933
- throw error;
2934
- });
2935
- return parsedReturns;
2936
- });
2937
- }
2938
- else {
2939
- // Would love a way to avoid disabling this rule, but we need
2940
- // an alias (using an arrow function was what caused 2651).
2941
- // eslint-disable-next-line @typescript-eslint/no-this-alias
2942
- const me = this;
2943
- return OK(function (...args) {
2944
- const parsedArgs = me._def.args.safeParse(args, params);
2945
- if (!parsedArgs.success) {
2946
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
2947
- }
2948
- const result = Reflect.apply(fn, this, parsedArgs.data);
2949
- const parsedReturns = me._def.returns.safeParse(result, params);
2950
- if (!parsedReturns.success) {
2951
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
2952
- }
2953
- return parsedReturns.data;
2954
- });
2955
- }
2956
- }
2957
- parameters() {
2958
- return this._def.args;
2959
- }
2960
- returnType() {
2961
- return this._def.returns;
2962
- }
2963
- args(...items) {
2964
- return new ZodFunction({
2965
- ...this._def,
2966
- args: ZodTuple.create(items).rest(ZodUnknown.create()),
2967
- });
2968
- }
2969
- returns(returnType) {
2970
- return new ZodFunction({
2971
- ...this._def,
2972
- returns: returnType,
2973
- });
2974
- }
2975
- implement(func) {
2976
- const validatedFunc = this.parse(func);
2977
- return validatedFunc;
2978
- }
2979
- strictImplement(func) {
2980
- const validatedFunc = this.parse(func);
2981
- return validatedFunc;
2982
- }
2983
- static create(args, returns, params) {
2984
- return new ZodFunction({
2985
- args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),
2986
- returns: returns || ZodUnknown.create(),
2987
- typeName: ZodFirstPartyTypeKind.ZodFunction,
2988
- ...processCreateParams(params),
2989
- });
2990
- }
2991
- }
2992
- export class ZodLazy extends ZodType {
2993
- get schema() {
2994
- return this._def.getter();
2995
- }
2996
- _parse(input) {
2997
- const { ctx } = this._processInputParams(input);
2998
- const lazySchema = this._def.getter();
2999
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
3000
- }
3001
- }
3002
- ZodLazy.create = (getter, params) => {
3003
- return new ZodLazy({
3004
- getter: getter,
3005
- typeName: ZodFirstPartyTypeKind.ZodLazy,
3006
- ...processCreateParams(params),
3007
- });
3008
- };
3009
- export class ZodLiteral extends ZodType {
3010
- _parse(input) {
3011
- if (input.data !== this._def.value) {
3012
- const ctx = this._getOrReturnCtx(input);
3013
- addIssueToContext(ctx, {
3014
- received: ctx.data,
3015
- code: ZodIssueCode.invalid_literal,
3016
- expected: this._def.value,
3017
- });
3018
- return INVALID;
3019
- }
3020
- return { status: "valid", value: input.data };
3021
- }
3022
- get value() {
3023
- return this._def.value;
3024
- }
3025
- }
3026
- ZodLiteral.create = (value, params) => {
3027
- return new ZodLiteral({
3028
- value: value,
3029
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
3030
- ...processCreateParams(params),
3031
- });
3032
- };
3033
- function createZodEnum(values, params) {
3034
- return new ZodEnum({
3035
- values,
3036
- typeName: ZodFirstPartyTypeKind.ZodEnum,
3037
- ...processCreateParams(params),
3038
- });
3039
- }
3040
- export class ZodEnum extends ZodType {
3041
- constructor() {
3042
- super(...arguments);
3043
- _ZodEnum_cache.set(this, void 0);
3044
- }
3045
- _parse(input) {
3046
- if (typeof input.data !== "string") {
3047
- const ctx = this._getOrReturnCtx(input);
3048
- const expectedValues = this._def.values;
3049
- addIssueToContext(ctx, {
3050
- expected: util.joinValues(expectedValues),
3051
- received: ctx.parsedType,
3052
- code: ZodIssueCode.invalid_type,
3053
- });
3054
- return INVALID;
3055
- }
3056
- if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
3057
- __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
3058
- }
3059
- if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
3060
- const ctx = this._getOrReturnCtx(input);
3061
- const expectedValues = this._def.values;
3062
- addIssueToContext(ctx, {
3063
- received: ctx.data,
3064
- code: ZodIssueCode.invalid_enum_value,
3065
- options: expectedValues,
3066
- });
3067
- return INVALID;
3068
- }
3069
- return OK(input.data);
3070
- }
3071
- get options() {
3072
- return this._def.values;
3073
- }
3074
- get enum() {
3075
- const enumValues = {};
3076
- for (const val of this._def.values) {
3077
- enumValues[val] = val;
3078
- }
3079
- return enumValues;
3080
- }
3081
- get Values() {
3082
- const enumValues = {};
3083
- for (const val of this._def.values) {
3084
- enumValues[val] = val;
3085
- }
3086
- return enumValues;
3087
- }
3088
- get Enum() {
3089
- const enumValues = {};
3090
- for (const val of this._def.values) {
3091
- enumValues[val] = val;
3092
- }
3093
- return enumValues;
3094
- }
3095
- extract(values, newDef = this._def) {
3096
- return ZodEnum.create(values, {
3097
- ...this._def,
3098
- ...newDef,
3099
- });
3100
- }
3101
- exclude(values, newDef = this._def) {
3102
- return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3103
- ...this._def,
3104
- ...newDef,
3105
- });
3106
- }
3107
- }
3108
- _ZodEnum_cache = new WeakMap();
3109
- ZodEnum.create = createZodEnum;
3110
- export class ZodNativeEnum extends ZodType {
3111
- constructor() {
3112
- super(...arguments);
3113
- _ZodNativeEnum_cache.set(this, void 0);
3114
- }
3115
- _parse(input) {
3116
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
3117
- const ctx = this._getOrReturnCtx(input);
3118
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3119
- const expectedValues = util.objectValues(nativeEnumValues);
3120
- addIssueToContext(ctx, {
3121
- expected: util.joinValues(expectedValues),
3122
- received: ctx.parsedType,
3123
- code: ZodIssueCode.invalid_type,
3124
- });
3125
- return INVALID;
3126
- }
3127
- if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
3128
- __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
3129
- }
3130
- if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
3131
- const expectedValues = util.objectValues(nativeEnumValues);
3132
- addIssueToContext(ctx, {
3133
- received: ctx.data,
3134
- code: ZodIssueCode.invalid_enum_value,
3135
- options: expectedValues,
3136
- });
3137
- return INVALID;
3138
- }
3139
- return OK(input.data);
3140
- }
3141
- get enum() {
3142
- return this._def.values;
3143
- }
3144
- }
3145
- _ZodNativeEnum_cache = new WeakMap();
3146
- ZodNativeEnum.create = (values, params) => {
3147
- return new ZodNativeEnum({
3148
- values: values,
3149
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3150
- ...processCreateParams(params),
3151
- });
3152
- };
3153
- export class ZodPromise extends ZodType {
3154
- unwrap() {
3155
- return this._def.type;
3156
- }
3157
- _parse(input) {
3158
- const { ctx } = this._processInputParams(input);
3159
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3160
- addIssueToContext(ctx, {
3161
- code: ZodIssueCode.invalid_type,
3162
- expected: ZodParsedType.promise,
3163
- received: ctx.parsedType,
3164
- });
3165
- return INVALID;
3166
- }
3167
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3168
- return OK(promisified.then((data) => {
3169
- return this._def.type.parseAsync(data, {
3170
- path: ctx.path,
3171
- errorMap: ctx.common.contextualErrorMap,
3172
- });
3173
- }));
3174
- }
3175
- }
3176
- ZodPromise.create = (schema, params) => {
3177
- return new ZodPromise({
3178
- type: schema,
3179
- typeName: ZodFirstPartyTypeKind.ZodPromise,
3180
- ...processCreateParams(params),
3181
- });
3182
- };
3183
- export class ZodEffects extends ZodType {
3184
- innerType() {
3185
- return this._def.schema;
3186
- }
3187
- sourceType() {
3188
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
3189
- ? this._def.schema.sourceType()
3190
- : this._def.schema;
3191
- }
3192
- _parse(input) {
3193
- const { status, ctx } = this._processInputParams(input);
3194
- const effect = this._def.effect || null;
3195
- const checkCtx = {
3196
- addIssue: (arg) => {
3197
- addIssueToContext(ctx, arg);
3198
- if (arg.fatal) {
3199
- status.abort();
3200
- }
3201
- else {
3202
- status.dirty();
3203
- }
3204
- },
3205
- get path() {
3206
- return ctx.path;
3207
- },
3208
- };
3209
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3210
- if (effect.type === "preprocess") {
3211
- const processed = effect.transform(ctx.data, checkCtx);
3212
- if (ctx.common.async) {
3213
- return Promise.resolve(processed).then(async (processed) => {
3214
- if (status.value === "aborted")
3215
- return INVALID;
3216
- const result = await this._def.schema._parseAsync({
3217
- data: processed,
3218
- path: ctx.path,
3219
- parent: ctx,
3220
- });
3221
- if (result.status === "aborted")
3222
- return INVALID;
3223
- if (result.status === "dirty")
3224
- return DIRTY(result.value);
3225
- if (status.value === "dirty")
3226
- return DIRTY(result.value);
3227
- return result;
3228
- });
3229
- }
3230
- else {
3231
- if (status.value === "aborted")
3232
- return INVALID;
3233
- const result = this._def.schema._parseSync({
3234
- data: processed,
3235
- path: ctx.path,
3236
- parent: ctx,
3237
- });
3238
- if (result.status === "aborted")
3239
- return INVALID;
3240
- if (result.status === "dirty")
3241
- return DIRTY(result.value);
3242
- if (status.value === "dirty")
3243
- return DIRTY(result.value);
3244
- return result;
3245
- }
3246
- }
3247
- if (effect.type === "refinement") {
3248
- const executeRefinement = (acc) => {
3249
- const result = effect.refinement(acc, checkCtx);
3250
- if (ctx.common.async) {
3251
- return Promise.resolve(result);
3252
- }
3253
- if (result instanceof Promise) {
3254
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3255
- }
3256
- return acc;
3257
- };
3258
- if (ctx.common.async === false) {
3259
- const inner = this._def.schema._parseSync({
3260
- data: ctx.data,
3261
- path: ctx.path,
3262
- parent: ctx,
3263
- });
3264
- if (inner.status === "aborted")
3265
- return INVALID;
3266
- if (inner.status === "dirty")
3267
- status.dirty();
3268
- // return value is ignored
3269
- executeRefinement(inner.value);
3270
- return { status: status.value, value: inner.value };
3271
- }
3272
- else {
3273
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
3274
- if (inner.status === "aborted")
3275
- return INVALID;
3276
- if (inner.status === "dirty")
3277
- status.dirty();
3278
- return executeRefinement(inner.value).then(() => {
3279
- return { status: status.value, value: inner.value };
3280
- });
3281
- });
3282
- }
3283
- }
3284
- if (effect.type === "transform") {
3285
- if (ctx.common.async === false) {
3286
- const base = this._def.schema._parseSync({
3287
- data: ctx.data,
3288
- path: ctx.path,
3289
- parent: ctx,
3290
- });
3291
- if (!isValid(base))
3292
- return base;
3293
- const result = effect.transform(base.value, checkCtx);
3294
- if (result instanceof Promise) {
3295
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3296
- }
3297
- return { status: status.value, value: result };
3298
- }
3299
- else {
3300
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
3301
- if (!isValid(base))
3302
- return base;
3303
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3304
- status: status.value,
3305
- value: result,
3306
- }));
3307
- });
3308
- }
3309
- }
3310
- util.assertNever(effect);
3311
- }
3312
- }
3313
- ZodEffects.create = (schema, effect, params) => {
3314
- return new ZodEffects({
3315
- schema,
3316
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3317
- effect,
3318
- ...processCreateParams(params),
3319
- });
3320
- };
3321
- ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3322
- return new ZodEffects({
3323
- schema,
3324
- effect: { type: "preprocess", transform: preprocess },
3325
- typeName: ZodFirstPartyTypeKind.ZodEffects,
3326
- ...processCreateParams(params),
3327
- });
3328
- };
3329
- export { ZodEffects as ZodTransformer };
3330
- export class ZodOptional extends ZodType {
3331
- _parse(input) {
3332
- const parsedType = this._getType(input);
3333
- if (parsedType === ZodParsedType.undefined) {
3334
- return OK(undefined);
3335
- }
3336
- return this._def.innerType._parse(input);
3337
- }
3338
- unwrap() {
3339
- return this._def.innerType;
3340
- }
3341
- }
3342
- ZodOptional.create = (type, params) => {
3343
- return new ZodOptional({
3344
- innerType: type,
3345
- typeName: ZodFirstPartyTypeKind.ZodOptional,
3346
- ...processCreateParams(params),
3347
- });
3348
- };
3349
- export class ZodNullable extends ZodType {
3350
- _parse(input) {
3351
- const parsedType = this._getType(input);
3352
- if (parsedType === ZodParsedType.null) {
3353
- return OK(null);
3354
- }
3355
- return this._def.innerType._parse(input);
3356
- }
3357
- unwrap() {
3358
- return this._def.innerType;
3359
- }
3360
- }
3361
- ZodNullable.create = (type, params) => {
3362
- return new ZodNullable({
3363
- innerType: type,
3364
- typeName: ZodFirstPartyTypeKind.ZodNullable,
3365
- ...processCreateParams(params),
3366
- });
3367
- };
3368
- export class ZodDefault extends ZodType {
3369
- _parse(input) {
3370
- const { ctx } = this._processInputParams(input);
3371
- let data = ctx.data;
3372
- if (ctx.parsedType === ZodParsedType.undefined) {
3373
- data = this._def.defaultValue();
3374
- }
3375
- return this._def.innerType._parse({
3376
- data,
3377
- path: ctx.path,
3378
- parent: ctx,
3379
- });
3380
- }
3381
- removeDefault() {
3382
- return this._def.innerType;
3383
- }
3384
- }
3385
- ZodDefault.create = (type, params) => {
3386
- return new ZodDefault({
3387
- innerType: type,
3388
- typeName: ZodFirstPartyTypeKind.ZodDefault,
3389
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3390
- ...processCreateParams(params),
3391
- });
3392
- };
3393
- export class ZodCatch extends ZodType {
3394
- _parse(input) {
3395
- const { ctx } = this._processInputParams(input);
3396
- // newCtx is used to not collect issues from inner types in ctx
3397
- const newCtx = {
3398
- ...ctx,
3399
- common: {
3400
- ...ctx.common,
3401
- issues: [],
3402
- },
3403
- };
3404
- const result = this._def.innerType._parse({
3405
- data: newCtx.data,
3406
- path: newCtx.path,
3407
- parent: {
3408
- ...newCtx,
3409
- },
3410
- });
3411
- if (isAsync(result)) {
3412
- return result.then((result) => {
3413
- return {
3414
- status: "valid",
3415
- value: result.status === "valid"
3416
- ? result.value
3417
- : this._def.catchValue({
3418
- get error() {
3419
- return new ZodError(newCtx.common.issues);
3420
- },
3421
- input: newCtx.data,
3422
- }),
3423
- };
3424
- });
3425
- }
3426
- else {
3427
- return {
3428
- status: "valid",
3429
- value: result.status === "valid"
3430
- ? result.value
3431
- : this._def.catchValue({
3432
- get error() {
3433
- return new ZodError(newCtx.common.issues);
3434
- },
3435
- input: newCtx.data,
3436
- }),
3437
- };
3438
- }
3439
- }
3440
- removeCatch() {
3441
- return this._def.innerType;
3442
- }
3443
- }
3444
- ZodCatch.create = (type, params) => {
3445
- return new ZodCatch({
3446
- innerType: type,
3447
- typeName: ZodFirstPartyTypeKind.ZodCatch,
3448
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3449
- ...processCreateParams(params),
3450
- });
3451
- };
3452
- export class ZodNaN extends ZodType {
3453
- _parse(input) {
3454
- const parsedType = this._getType(input);
3455
- if (parsedType !== ZodParsedType.nan) {
3456
- const ctx = this._getOrReturnCtx(input);
3457
- addIssueToContext(ctx, {
3458
- code: ZodIssueCode.invalid_type,
3459
- expected: ZodParsedType.nan,
3460
- received: ctx.parsedType,
3461
- });
3462
- return INVALID;
3463
- }
3464
- return { status: "valid", value: input.data };
3465
- }
3466
- }
3467
- ZodNaN.create = (params) => {
3468
- return new ZodNaN({
3469
- typeName: ZodFirstPartyTypeKind.ZodNaN,
3470
- ...processCreateParams(params),
3471
- });
3472
- };
3473
- export const BRAND = Symbol("zod_brand");
3474
- export class ZodBranded extends ZodType {
3475
- _parse(input) {
3476
- const { ctx } = this._processInputParams(input);
3477
- const data = ctx.data;
3478
- return this._def.type._parse({
3479
- data,
3480
- path: ctx.path,
3481
- parent: ctx,
3482
- });
3483
- }
3484
- unwrap() {
3485
- return this._def.type;
3486
- }
3487
- }
3488
- export class ZodPipeline extends ZodType {
3489
- _parse(input) {
3490
- const { status, ctx } = this._processInputParams(input);
3491
- if (ctx.common.async) {
3492
- const handleAsync = async () => {
3493
- const inResult = await this._def.in._parseAsync({
3494
- data: ctx.data,
3495
- path: ctx.path,
3496
- parent: ctx,
3497
- });
3498
- if (inResult.status === "aborted")
3499
- return INVALID;
3500
- if (inResult.status === "dirty") {
3501
- status.dirty();
3502
- return DIRTY(inResult.value);
3503
- }
3504
- else {
3505
- return this._def.out._parseAsync({
3506
- data: inResult.value,
3507
- path: ctx.path,
3508
- parent: ctx,
3509
- });
3510
- }
3511
- };
3512
- return handleAsync();
3513
- }
3514
- else {
3515
- const inResult = this._def.in._parseSync({
3516
- data: ctx.data,
3517
- path: ctx.path,
3518
- parent: ctx,
3519
- });
3520
- if (inResult.status === "aborted")
3521
- return INVALID;
3522
- if (inResult.status === "dirty") {
3523
- status.dirty();
3524
- return {
3525
- status: "dirty",
3526
- value: inResult.value,
3527
- };
3528
- }
3529
- else {
3530
- return this._def.out._parseSync({
3531
- data: inResult.value,
3532
- path: ctx.path,
3533
- parent: ctx,
3534
- });
3535
- }
3536
- }
3537
- }
3538
- static create(a, b) {
3539
- return new ZodPipeline({
3540
- in: a,
3541
- out: b,
3542
- typeName: ZodFirstPartyTypeKind.ZodPipeline,
3543
- });
3544
- }
3545
- }
3546
- export class ZodReadonly extends ZodType {
3547
- _parse(input) {
3548
- const result = this._def.innerType._parse(input);
3549
- const freeze = (data) => {
3550
- if (isValid(data)) {
3551
- data.value = Object.freeze(data.value);
3552
- }
3553
- return data;
3554
- };
3555
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3556
- }
3557
- unwrap() {
3558
- return this._def.innerType;
3559
- }
3560
- }
3561
- ZodReadonly.create = (type, params) => {
3562
- return new ZodReadonly({
3563
- innerType: type,
3564
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
3565
- ...processCreateParams(params),
3566
- });
3567
- };
3568
- ////////////////////////////////////////
3569
- ////////////////////////////////////////
3570
- ////////// //////////
3571
- ////////// z.custom //////////
3572
- ////////// //////////
3573
- ////////////////////////////////////////
3574
- ////////////////////////////////////////
3575
- function cleanParams(params, data) {
3576
- const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
3577
- const p2 = typeof p === "string" ? { message: p } : p;
3578
- return p2;
3579
- }
3580
- export function custom(check, _params = {},
3581
- /**
3582
- * @deprecated
3583
- *
3584
- * Pass `fatal` into the params object instead:
3585
- *
3586
- * ```ts
3587
- * z.string().custom((val) => val.length > 5, { fatal: false })
3588
- * ```
3589
- *
3590
- */
3591
- fatal) {
3592
- if (check)
3593
- return ZodAny.create().superRefine((data, ctx) => {
3594
- const r = check(data);
3595
- if (r instanceof Promise) {
3596
- return r.then((r) => {
3597
- if (!r) {
3598
- const params = cleanParams(_params, data);
3599
- const _fatal = params.fatal ?? fatal ?? true;
3600
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3601
- }
3602
- });
3603
- }
3604
- if (!r) {
3605
- const params = cleanParams(_params, data);
3606
- const _fatal = params.fatal ?? fatal ?? true;
3607
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
3608
- }
3609
- return;
3610
- });
3611
- return ZodAny.create();
3612
- }
3613
- export { ZodType as Schema, ZodType as ZodSchema };
3614
- export const late = {
3615
- object: ZodObject.lazycreate,
3616
- };
3617
- export var ZodFirstPartyTypeKind;
3618
- (function (ZodFirstPartyTypeKind) {
3619
- ZodFirstPartyTypeKind["ZodString"] = "ZodString";
3620
- ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
3621
- ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
3622
- ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
3623
- ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
3624
- ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
3625
- ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
3626
- ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
3627
- ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
3628
- ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
3629
- ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
3630
- ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
3631
- ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
3632
- ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
3633
- ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
3634
- ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
3635
- ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3636
- ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
3637
- ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
3638
- ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
3639
- ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
3640
- ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
3641
- ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
3642
- ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
3643
- ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
3644
- ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
3645
- ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
3646
- ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
3647
- ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
3648
- ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
3649
- ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
3650
- ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
3651
- ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
3652
- ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
3653
- ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
3654
- ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
3655
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3656
- // requires TS 4.4+
3657
- class Class {
3658
- constructor(..._) { }
3659
- }
3660
- const instanceOfType = (
3661
- // const instanceOfType = <T extends new (...args: any[]) => any>(
3662
- cls, params = {
3663
- message: `Input not instance of ${cls.name}`,
3664
- }) => custom((data) => data instanceof cls, params);
3665
- const stringType = ZodString.create;
3666
- const numberType = ZodNumber.create;
3667
- const nanType = ZodNaN.create;
3668
- const bigIntType = ZodBigInt.create;
3669
- const booleanType = ZodBoolean.create;
3670
- const dateType = ZodDate.create;
3671
- const symbolType = ZodSymbol.create;
3672
- const undefinedType = ZodUndefined.create;
3673
- const nullType = ZodNull.create;
3674
- const anyType = ZodAny.create;
3675
- const unknownType = ZodUnknown.create;
3676
- const neverType = ZodNever.create;
3677
- const voidType = ZodVoid.create;
3678
- const arrayType = ZodArray.create;
3679
- const objectType = ZodObject.create;
3680
- const strictObjectType = ZodObject.strictCreate;
3681
- const unionType = ZodUnion.create;
3682
- const discriminatedUnionType = ZodDiscriminatedUnion.create;
3683
- const intersectionType = ZodIntersection.create;
3684
- const tupleType = ZodTuple.create;
3685
- const recordType = ZodRecord.create;
3686
- const mapType = ZodMap.create;
3687
- const setType = ZodSet.create;
3688
- const functionType = ZodFunction.create;
3689
- const lazyType = ZodLazy.create;
3690
- const literalType = ZodLiteral.create;
3691
- const enumType = ZodEnum.create;
3692
- const nativeEnumType = ZodNativeEnum.create;
3693
- const promiseType = ZodPromise.create;
3694
- const effectsType = ZodEffects.create;
3695
- const optionalType = ZodOptional.create;
3696
- const nullableType = ZodNullable.create;
3697
- const preprocessType = ZodEffects.createWithPreprocess;
3698
- const pipelineType = ZodPipeline.create;
3699
- const ostring = () => stringType().optional();
3700
- const onumber = () => numberType().optional();
3701
- const oboolean = () => booleanType().optional();
3702
- export const coerce = {
3703
- string: ((arg) => ZodString.create({ ...arg, coerce: true })),
3704
- number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
3705
- boolean: ((arg) => ZodBoolean.create({
3706
- ...arg,
3707
- coerce: true,
3708
- })),
3709
- bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
3710
- date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
3711
- };
3712
- export { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };
3713
- export const NEVER = INVALID;