@marteye/studiojs 1.1.14 → 1.1.16

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