@heritsilavo/react-error-boundary 2.0.0 → 2.1.1

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