tidewave 0.1.0 → 0.3.0

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