@mastra/mcp 0.3.10-alpha.5 → 0.3.10-alpha.6

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