hono-ban 0.2.3 → 0.2.4

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