@heritsilavo/react-error-boundary 1.1.0

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