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