zod 3.25.0-canary.20250211T214501 → 4.0.0-beta.0

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