zod 3.18.0 → 3.19.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -63,7 +63,7 @@
63
63
  - [Nullables](#nullables)
64
64
  - [Objects](#objects)
65
65
  - [.shape](#shape)
66
- - [.enum](#enum)
66
+ - [.keyof](#keyof)
67
67
  - [.extend](#extend)
68
68
  - [.merge](#merge)
69
69
  - [.pick/.omit](#pickomit)
@@ -90,7 +90,6 @@
90
90
  - [Instanceof](#instanceof)
91
91
  - [Function schemas](#function-schemas)
92
92
  - [Preprocess](#preprocess)
93
- - [Branded types](#branded-types)
94
93
  - [Schema methods](#schema-methods)
95
94
  - [.parse](#parse)
96
95
  - [.parseAsync](#parseasync)
@@ -107,6 +106,7 @@
107
106
  - [.promise](#promise)
108
107
  - [.or](#or)
109
108
  - [.and](#and)
109
+ - [.brand](#brand)
110
110
  - [Guides and concepts](#guides-and-concepts)
111
111
  - [Type inference](#type-inference)
112
112
  - [Writing generic functions](#writing-generic-functions)
@@ -306,9 +306,9 @@ There are a growing number of tools that are built atop or support Zod natively!
306
306
  - [`tRPC`](https://github.com/trpc/trpc): Build end-to-end typesafe APIs without GraphQL.
307
307
  - [`ts-to-zod`](https://github.com/fabien0102/ts-to-zod): Convert TypeScript definitions into Zod schemas.
308
308
  - [`zod-to-ts`](https://github.com/sachinraja/zod-to-ts): Generate TypeScript definitions from Zod schemas.
309
- - [`@anatine/zod-openapi`](https://github.com/anatine/zod-plugins/tree/main/libs/zod-openapi): Converts a Zod schema to an OpenAPI v3.x `SchemaObject`.
310
- - [`@anatine/zod-mock`](https://github.com/anatine/zod-plugins/tree/main/libs/zod-mock): Generate mock data from a Zod schema. Powered by [faker.js](https://github.com/Marak/Faker.js).
311
- - [`@anatine/zod-nestjs`](https://github.com/anatine/zod-plugins/tree/main/libs/zod-nestjs): Helper methods for using Zod in a NestJS project.
309
+ - [`@anatine/zod-openapi`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-openapi): Converts a Zod schema to an OpenAPI v3.x `SchemaObject`.
310
+ - [`@anatine/zod-mock`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-mock): Generate mock data from a Zod schema. Powered by [faker.js](https://github.com/Marak/Faker.js).
311
+ - [`@anatine/zod-nestjs`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-nestjs): Helper methods for using Zod in a NestJS project.
312
312
  - [`zod-mocking`](https://github.com/dipasqualew/zod-mocking): Generate mock data from your Zod schemas.
313
313
  - [`zod-fast-check`](https://github.com/DavidTimms/zod-fast-check): Generate `fast-check` arbitraries from Zod schemas.
314
314
  - [`zod-endpoints`](https://github.com/flock-community/zod-endpoints): Contract-first strictly typed endpoints with Zod. OpenAPI compatible.
@@ -330,6 +330,7 @@ There are a growing number of tools that are built atop or support Zod natively!
330
330
  - [`remix-domains`](https://github.com/SeasonedSoftware/remix-domains/): Improves end-to-end type safety in [Remix](https://remix.run/) by leveraging Zod to parse the framework's inputs such as FormData, URLSearchParams, etc.
331
331
  - [`@zodios/core`](https://github.com/ecyrbe/zodios): A typescript API client with runtime and compile time validation backed by axios and zod.
332
332
  - [`@runtyping/zod`](https://github.com/johngeorgewright/runtyping/tree/master/packages/zod): Generate zod from static types & JSON schema.
333
+ - [`slonik`](https://github.com/gajus/slonik/tree/gajus/add-zod-validation-backwards-compatible#runtime-validation-and-static-type-inference): Node.js Postgres client with strong Zod integration
333
334
 
334
335
  #### Form integrations
335
336
 
@@ -603,7 +604,7 @@ dateSchema.safeParse(new Date("1/12/22")); // success: true
603
604
  dateSchema.safeParse("2022-01-12T00:00:00.000Z"); // success: true
604
605
  ```
605
606
 
606
- ## Zod enums
607
+ ## Zod enums-
607
608
 
608
609
  ```ts
609
610
  const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]);
@@ -799,7 +800,7 @@ Dog.shape.age; // => number schema
799
800
 
800
801
  ### `.keyof`
801
802
 
802
- Use `.key` to create a `ZodEnum` schema from the keys of an object schema.
803
+ Use `.keyof` to create a `ZodEnum` schema from the keys of an object schema.
803
804
 
804
805
  ```ts
805
806
  const keySchema = Dog.keyof();
@@ -1073,6 +1074,14 @@ type Athlete = z.infer<typeof athleteSchema>;
1073
1074
  // type Athlete = [string, number, { pointsScored: number }]
1074
1075
  ```
1075
1076
 
1077
+ A variadic ("rest") argument can be added with the `.rest` method.
1078
+
1079
+ ```ts
1080
+ const variadicTuple = z.tuple([z.string()]).rest(z.number());
1081
+ const result = variadicTuple.parse(["hello", 1, 2, 3]);
1082
+ // => [string, ...number[]];
1083
+ ```
1084
+
1076
1085
  ## Unions
1077
1086
 
1078
1087
  Zod includes a built-in `z.union` method for composing "OR" types.
@@ -1683,34 +1692,33 @@ const Strings = z.array(z.string()).superRefine((val, ctx) => {
1683
1692
  });
1684
1693
  ```
1685
1694
 
1686
- You can add as many issues as you like. If `ctx.addIssue` is NOT called during the execution of the function, validation passes.
1695
+ You can add as many issues as you like. If `ctx.addIssue` is _not_ called during the execution of the function, validation passes.
1687
1696
 
1688
1697
  Normally refinements always create issues with a `ZodIssueCode.custom` error code, but with `superRefine` you can create any issue of any code. Each issue code is described in detail in the Error Handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md).
1689
1698
 
1690
1699
  #### Abort early
1691
1700
 
1692
- By default, parsing will continue even after a refinement check fails. For instance, if you chain together multiple refinements, they will all be executed. However, it may be desirable to _abort early_ to prevent later refinements from being executed. To achieve this, pass the `fatal` flag to `ctx.addIssue`:
1701
+ By default, parsing will continue even after a refinement check fails. For instance, if you chain together multiple refinements, they will all be executed. However, it may be desirable to _abort early_ to prevent later refinements from being executed. To achieve this, pass the `fatal` flag to `ctx.addIssue` and return `z.NEVER`.
1693
1702
 
1694
1703
  ```ts
1695
- const Strings = z
1696
- .number()
1697
- .superRefine((val, ctx) => {
1698
- if (val < 10) {
1699
- ctx.addIssue({
1700
- code: z.ZodIssueCode.custom,
1701
- message: "foo",
1702
- fatal: true,
1703
- });
1704
- }
1705
- })
1706
- .superRefine((val, ctx) => {
1707
- if (val !== " ") {
1708
- ctx.addIssue({
1709
- code: z.ZodIssueCode.custom,
1710
- message: "bar",
1711
- });
1712
- }
1713
- });
1704
+ const schema = z.number().superRefine((val, ctx) => {
1705
+ if (val < 10) {
1706
+ ctx.addIssue({
1707
+ code: z.ZodIssueCode.custom,
1708
+ message: "should be >= 10",
1709
+ fatal: true,
1710
+ });
1711
+
1712
+ return z.NEVER;
1713
+ }
1714
+
1715
+ if (val !== 12) {
1716
+ ctx.addIssue({
1717
+ code: z.ZodIssueCode.custom,
1718
+ message: "should be twelve",
1719
+ });
1720
+ }
1721
+ });
1714
1722
  ```
1715
1723
 
1716
1724
  ### `.transform`
@@ -1749,6 +1757,12 @@ const Strings = z.string().transform((val, ctx) => {
1749
1757
  code: z.ZodIssueCode.custom,
1750
1758
  message: "Not a number",
1751
1759
  });
1760
+
1761
+ // This is a special symbol you can use to
1762
+ // return early from the transform function.
1763
+ // It has type `never` so it does not affect the
1764
+ // inferred return type.
1765
+ return z.NEVER;
1752
1766
  }
1753
1767
  return parsed;
1754
1768
  });
package/lib/ZodError.d.ts CHANGED
@@ -142,16 +142,11 @@ export declare type IssueData = stripPath<ZodIssueOptionalMessage> & {
142
142
  fatal?: boolean;
143
143
  };
144
144
  export declare type MakeErrorData = IssueData;
145
- declare type ErrorMapCtx = {
145
+ export declare type ErrorMapCtx = {
146
146
  defaultError: string;
147
147
  data: any;
148
148
  };
149
- export declare type ZodErrorMap = typeof defaultErrorMap;
150
- export declare const defaultErrorMap: (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => {
151
- message: string;
152
- };
153
- export declare function setErrorMap(map: ZodErrorMap): void;
154
- export declare function getErrorMap(): (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => {
149
+ export declare type ZodErrorMap = (issue: ZodIssueOptionalMessage, _ctx: ErrorMapCtx) => {
155
150
  message: string;
156
151
  };
157
152
  export {};
package/lib/ZodError.js CHANGED
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0;
4
- const parseUtil_1 = require("./helpers/parseUtil");
3
+ exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0;
5
4
  const util_1 = require("./helpers/util");
6
5
  exports.ZodIssueCode = util_1.util.arrayToEnum([
7
6
  "invalid_type",
@@ -102,7 +101,7 @@ class ZodError extends Error {
102
101
  return this.message;
103
102
  }
104
103
  get message() {
105
- return JSON.stringify(this.issues, parseUtil_1.jsonStringifyReplacer, 2);
104
+ return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2);
106
105
  }
107
106
  get isEmpty() {
108
107
  return this.issues.length === 0;
@@ -130,106 +129,3 @@ ZodError.create = (issues) => {
130
129
  const error = new ZodError(issues);
131
130
  return error;
132
131
  };
133
- const defaultErrorMap = (issue, _ctx) => {
134
- let message;
135
- switch (issue.code) {
136
- case exports.ZodIssueCode.invalid_type:
137
- if (issue.received === util_1.ZodParsedType.undefined) {
138
- message = "Required";
139
- }
140
- else {
141
- message = `Expected ${issue.expected}, received ${issue.received}`;
142
- }
143
- break;
144
- case exports.ZodIssueCode.invalid_literal:
145
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, parseUtil_1.jsonStringifyReplacer)}`;
146
- break;
147
- case exports.ZodIssueCode.unrecognized_keys:
148
- message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`;
149
- break;
150
- case exports.ZodIssueCode.invalid_union:
151
- message = `Invalid input`;
152
- break;
153
- case exports.ZodIssueCode.invalid_union_discriminator:
154
- message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`;
155
- break;
156
- case exports.ZodIssueCode.invalid_enum_value:
157
- message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`;
158
- break;
159
- case exports.ZodIssueCode.invalid_arguments:
160
- message = `Invalid function arguments`;
161
- break;
162
- case exports.ZodIssueCode.invalid_return_type:
163
- message = `Invalid function return type`;
164
- break;
165
- case exports.ZodIssueCode.invalid_date:
166
- message = `Invalid date`;
167
- break;
168
- case exports.ZodIssueCode.invalid_string:
169
- if (typeof issue.validation === "object") {
170
- if ("startsWith" in issue.validation) {
171
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
172
- }
173
- else if ("endsWith" in issue.validation) {
174
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
175
- }
176
- else {
177
- util_1.util.assertNever(issue.validation);
178
- }
179
- }
180
- else if (issue.validation !== "regex") {
181
- message = `Invalid ${issue.validation}`;
182
- }
183
- else {
184
- message = "Invalid";
185
- }
186
- break;
187
- case exports.ZodIssueCode.too_small:
188
- if (issue.type === "array")
189
- message = `Array must contain ${issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
190
- else if (issue.type === "string")
191
- message = `String must contain ${issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
192
- else if (issue.type === "number")
193
- message = `Number must be greater than ${issue.inclusive ? `or equal to ` : ``}${issue.minimum}`;
194
- else if (issue.type === "date")
195
- message = `Date must be greater than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.minimum)}`;
196
- else
197
- message = "Invalid input";
198
- break;
199
- case exports.ZodIssueCode.too_big:
200
- if (issue.type === "array")
201
- message = `Array must contain ${issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
202
- else if (issue.type === "string")
203
- message = `String must contain ${issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
204
- else if (issue.type === "number")
205
- message = `Number must be less than ${issue.inclusive ? `or equal to ` : ``}${issue.maximum}`;
206
- else if (issue.type === "date")
207
- message = `Date must be smaller than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.maximum)}`;
208
- else
209
- message = "Invalid input";
210
- break;
211
- case exports.ZodIssueCode.custom:
212
- message = `Invalid input`;
213
- break;
214
- case exports.ZodIssueCode.invalid_intersection_types:
215
- message = `Intersection results could not be merged`;
216
- break;
217
- case exports.ZodIssueCode.not_multiple_of:
218
- message = `Number must be a multiple of ${issue.multipleOf}`;
219
- break;
220
- default:
221
- message = _ctx.defaultError;
222
- util_1.util.assertNever(issue);
223
- }
224
- return { message };
225
- };
226
- exports.defaultErrorMap = defaultErrorMap;
227
- let overrideErrorMap = exports.defaultErrorMap;
228
- function setErrorMap(map) {
229
- overrideErrorMap = map;
230
- }
231
- exports.setErrorMap = setErrorMap;
232
- function getErrorMap() {
233
- return overrideErrorMap;
234
- }
235
- exports.getErrorMap = getErrorMap;
@@ -0,0 +1,5 @@
1
+ import defaultErrorMap from "./locales/en";
2
+ import type { ZodErrorMap } from "./ZodError";
3
+ export { defaultErrorMap };
4
+ export declare function setErrorMap(map: ZodErrorMap): void;
5
+ export declare function getErrorMap(): ZodErrorMap;
package/lib/errors.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0;
7
+ const en_1 = __importDefault(require("./locales/en"));
8
+ exports.defaultErrorMap = en_1.default;
9
+ let overrideErrorMap = en_1.default;
10
+ function setErrorMap(map) {
11
+ overrideErrorMap = map;
12
+ }
13
+ exports.setErrorMap = setErrorMap;
14
+ function getErrorMap() {
15
+ return overrideErrorMap;
16
+ }
17
+ exports.getErrorMap = getErrorMap;
package/lib/external.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./errors";
1
2
  export * from "./helpers/parseUtil";
2
3
  export * from "./helpers/typeAliases";
3
4
  export { getParsedType, ZodParsedType } from "./helpers/util";
package/lib/external.js CHANGED
@@ -11,6 +11,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.ZodParsedType = exports.getParsedType = void 0;
14
+ __exportStar(require("./errors"), exports);
14
15
  __exportStar(require("./helpers/parseUtil"), exports);
15
16
  __exportStar(require("./helpers/typeAliases"), exports);
16
17
  var util_1 = require("./helpers/util");
@@ -76,4 +76,3 @@ export declare const isAborted: (x: ParseReturnType<any>) => x is INVALID;
76
76
  export declare const isDirty: <T>(x: ParseReturnType<T>) => x is OK<T> | DIRTY<T>;
77
77
  export declare const isValid: <T>(x: ParseReturnType<T>) => x is OK<T> | DIRTY<T>;
78
78
  export declare const isAsync: <T>(x: ParseReturnType<T>) => x is AsyncParseReturnType<T>;
79
- export declare const jsonStringifyReplacer: (_: string, value: any) => any;
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.jsonStringifyReplacer = exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0;
4
- const ZodError_1 = require("../ZodError");
6
+ exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0;
7
+ const errors_1 = require("../errors");
8
+ const en_1 = __importDefault(require("../locales/en"));
5
9
  const makeIssue = (params) => {
6
10
  const { data, path, errorMaps, issueData } = params;
7
11
  const fullPath = [...path, ...(issueData.path || [])];
@@ -33,8 +37,8 @@ function addIssueToContext(ctx, issueData) {
33
37
  errorMaps: [
34
38
  ctx.common.contextualErrorMap,
35
39
  ctx.schemaErrorMap,
36
- ZodError_1.getErrorMap(),
37
- ZodError_1.defaultErrorMap,
40
+ errors_1.getErrorMap(),
41
+ en_1.default,
38
42
  ].filter((x) => !!x),
39
43
  });
40
44
  ctx.common.issues.push(issue);
@@ -108,10 +112,3 @@ const isValid = (x) => x.status === "valid";
108
112
  exports.isValid = isValid;
109
113
  const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise;
110
114
  exports.isAsync = isAsync;
111
- const jsonStringifyReplacer = (_, value) => {
112
- if (typeof value === "bigint") {
113
- return value.toString();
114
- }
115
- return value;
116
- };
117
- exports.jsonStringifyReplacer = jsonStringifyReplacer;
@@ -18,6 +18,7 @@ export declare namespace util {
18
18
  export type noUndefined<T> = T extends undefined ? never : T;
19
19
  export const isInteger: NumberConstructor["isInteger"];
20
20
  export function joinValues<T extends any[]>(array: T, separator?: string): string;
21
+ export const jsonStringifyReplacer: (_: string, value: any) => any;
21
22
  export {};
22
23
  }
23
24
  export declare const ZodParsedType: {
@@ -57,6 +57,12 @@ var util;
57
57
  .join(separator);
58
58
  }
59
59
  util.joinValues = joinValues;
60
+ util.jsonStringifyReplacer = (_, value) => {
61
+ if (typeof value === "bigint") {
62
+ return value.toString();
63
+ }
64
+ return value;
65
+ };
60
66
  })(util = exports.util || (exports.util = {}));
61
67
  exports.ZodParsedType = util.arrayToEnum([
62
68
  "string",
package/lib/index.mjs CHANGED
@@ -54,6 +54,12 @@ var util;
54
54
  .join(separator);
55
55
  }
56
56
  util.joinValues = joinValues;
57
+ util.jsonStringifyReplacer = (_, value) => {
58
+ if (typeof value === "bigint") {
59
+ return value.toString();
60
+ }
61
+ return value;
62
+ };
57
63
  })(util || (util = {}));
58
64
  const ZodParsedType = util.arrayToEnum([
59
65
  "string",
@@ -218,7 +224,7 @@ class ZodError extends Error {
218
224
  return this.message;
219
225
  }
220
226
  get message() {
221
- return JSON.stringify(this.issues, jsonStringifyReplacer, 2);
227
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
222
228
  }
223
229
  get isEmpty() {
224
230
  return this.issues.length === 0;
@@ -245,7 +251,8 @@ ZodError.create = (issues) => {
245
251
  const error = new ZodError(issues);
246
252
  return error;
247
253
  };
248
- const defaultErrorMap = (issue, _ctx) => {
254
+
255
+ const errorMap = (issue, _ctx) => {
249
256
  let message;
250
257
  switch (issue.code) {
251
258
  case ZodIssueCode.invalid_type:
@@ -257,7 +264,7 @@ const defaultErrorMap = (issue, _ctx) => {
257
264
  }
258
265
  break;
259
266
  case ZodIssueCode.invalid_literal:
260
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, jsonStringifyReplacer)}`;
267
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
261
268
  break;
262
269
  case ZodIssueCode.unrecognized_keys:
263
270
  message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
@@ -338,7 +345,8 @@ const defaultErrorMap = (issue, _ctx) => {
338
345
  }
339
346
  return { message };
340
347
  };
341
- let overrideErrorMap = defaultErrorMap;
348
+
349
+ let overrideErrorMap = errorMap;
342
350
  function setErrorMap(map) {
343
351
  overrideErrorMap = map;
344
352
  }
@@ -377,7 +385,7 @@ function addIssueToContext(ctx, issueData) {
377
385
  ctx.common.contextualErrorMap,
378
386
  ctx.schemaErrorMap,
379
387
  getErrorMap(),
380
- defaultErrorMap,
388
+ errorMap,
381
389
  ].filter((x) => !!x),
382
390
  });
383
391
  ctx.common.issues.push(issue);
@@ -443,12 +451,6 @@ const isAborted = (x) => x.status === "aborted";
443
451
  const isDirty = (x) => x.status === "dirty";
444
452
  const isValid = (x) => x.status === "valid";
445
453
  const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise;
446
- const jsonStringifyReplacer = (_, value) => {
447
- if (typeof value === "bigint") {
448
- return value.toString();
449
- }
450
- return value;
451
- };
452
454
 
453
455
  var errorUtil;
454
456
  (function (errorUtil) {
@@ -484,7 +486,7 @@ function processCreateParams(params) {
484
486
  return {};
485
487
  const { errorMap, invalid_type_error, required_error, description } = params;
486
488
  if (errorMap && (invalid_type_error || required_error)) {
487
- throw new Error(`Can't use "invalid" or "required" in conjunction with custom error map.`);
489
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
488
490
  }
489
491
  if (errorMap)
490
492
  return { errorMap: errorMap, description };
@@ -2175,6 +2177,9 @@ class ZodTuple extends ZodType {
2175
2177
  }
2176
2178
  }
2177
2179
  ZodTuple.create = (schemas, params) => {
2180
+ if (!Array.isArray(schemas)) {
2181
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2182
+ }
2178
2183
  return new ZodTuple({
2179
2184
  items: schemas,
2180
2185
  typeName: ZodFirstPartyTypeKind.ZodTuple,
@@ -2403,7 +2408,7 @@ class ZodFunction extends ZodType {
2403
2408
  ctx.common.contextualErrorMap,
2404
2409
  ctx.schemaErrorMap,
2405
2410
  getErrorMap(),
2406
- defaultErrorMap,
2411
+ errorMap,
2407
2412
  ].filter((x) => !!x),
2408
2413
  issueData: {
2409
2414
  code: ZodIssueCode.invalid_arguments,
@@ -2419,7 +2424,7 @@ class ZodFunction extends ZodType {
2419
2424
  ctx.common.contextualErrorMap,
2420
2425
  ctx.schemaErrorMap,
2421
2426
  getErrorMap(),
2422
- defaultErrorMap,
2427
+ errorMap,
2423
2428
  ].filter((x) => !!x),
2424
2429
  issueData: {
2425
2430
  code: ZodIssueCode.invalid_return_type,
@@ -2489,17 +2494,17 @@ class ZodFunction extends ZodType {
2489
2494
  const validatedFunc = this.parse(func);
2490
2495
  return validatedFunc;
2491
2496
  }
2497
+ static create(args, returns, params) {
2498
+ return new ZodFunction({
2499
+ args: (args
2500
+ ? args
2501
+ : ZodTuple.create([]).rest(ZodUnknown.create())),
2502
+ returns: returns || ZodUnknown.create(),
2503
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
2504
+ ...processCreateParams(params),
2505
+ });
2506
+ }
2492
2507
  }
2493
- ZodFunction.create = (args, returns, params) => {
2494
- return new ZodFunction({
2495
- args: (args
2496
- ? args.rest(ZodUnknown.create())
2497
- : ZodTuple.create([]).rest(ZodUnknown.create())),
2498
- returns: returns || ZodUnknown.create(),
2499
- typeName: ZodFirstPartyTypeKind.ZodFunction,
2500
- ...processCreateParams(params),
2501
- });
2502
- };
2503
2508
  class ZodLazy extends ZodType {
2504
2509
  get schema() {
2505
2510
  return this._def.getter();
@@ -2944,6 +2949,12 @@ var ZodFirstPartyTypeKind;
2944
2949
  ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
2945
2950
  ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
2946
2951
  })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
2952
+ // new approach that works for abstract classes
2953
+ // but required TS 4.4+
2954
+ // abstract class Class {
2955
+ // constructor(..._: any[]) {}
2956
+ // }
2957
+ // const instanceOfType = <T extends typeof Class>(
2947
2958
  const instanceOfType = (cls, params = {
2948
2959
  message: `Input not instance of ${cls.name}`,
2949
2960
  }) => custom((data) => data instanceof cls, params, true);
@@ -2982,11 +2993,15 @@ const preprocessType = ZodEffects.createWithPreprocess;
2982
2993
  const ostring = () => stringType().optional();
2983
2994
  const onumber = () => numberType().optional();
2984
2995
  const oboolean = () => booleanType().optional();
2996
+ const NEVER = INVALID;
2985
2997
 
2986
2998
  var mod = /*#__PURE__*/Object.freeze({
2987
2999
  __proto__: null,
2988
3000
  getParsedType: getParsedType,
2989
3001
  ZodParsedType: ZodParsedType,
3002
+ defaultErrorMap: errorMap,
3003
+ setErrorMap: setErrorMap,
3004
+ getErrorMap: getErrorMap,
2990
3005
  makeIssue: makeIssue,
2991
3006
  EMPTY_PATH: EMPTY_PATH,
2992
3007
  addIssueToContext: addIssueToContext,
@@ -2998,7 +3013,6 @@ var mod = /*#__PURE__*/Object.freeze({
2998
3013
  isDirty: isDirty,
2999
3014
  isValid: isValid,
3000
3015
  isAsync: isAsync,
3001
- jsonStringifyReplacer: jsonStringifyReplacer,
3002
3016
  ZodType: ZodType,
3003
3017
  ZodString: ZodString,
3004
3018
  ZodNumber: ZodNumber,
@@ -3077,12 +3091,10 @@ var mod = /*#__PURE__*/Object.freeze({
3077
3091
  union: unionType,
3078
3092
  unknown: unknownType,
3079
3093
  'void': voidType,
3094
+ NEVER: NEVER,
3080
3095
  ZodIssueCode: ZodIssueCode,
3081
3096
  quotelessJson: quotelessJson,
3082
- ZodError: ZodError,
3083
- defaultErrorMap: defaultErrorMap,
3084
- setErrorMap: setErrorMap,
3085
- getErrorMap: getErrorMap
3097
+ ZodError: ZodError
3086
3098
  });
3087
3099
 
3088
- export { BRAND, DIRTY, EMPTY_PATH, INVALID, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPromise, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, custom, dateType as date, mod as default, defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, jsonStringifyReplacer, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, mod as z };
3100
+ export { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPromise, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, custom, dateType as date, mod as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, mod as z };
package/lib/index.umd.js CHANGED
@@ -60,6 +60,12 @@
60
60
  .join(separator);
61
61
  }
62
62
  util.joinValues = joinValues;
63
+ util.jsonStringifyReplacer = (_, value) => {
64
+ if (typeof value === "bigint") {
65
+ return value.toString();
66
+ }
67
+ return value;
68
+ };
63
69
  })(util || (util = {}));
64
70
  const ZodParsedType = util.arrayToEnum([
65
71
  "string",
@@ -224,7 +230,7 @@
224
230
  return this.message;
225
231
  }
226
232
  get message() {
227
- return JSON.stringify(this.issues, jsonStringifyReplacer, 2);
233
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
228
234
  }
229
235
  get isEmpty() {
230
236
  return this.issues.length === 0;
@@ -251,7 +257,8 @@
251
257
  const error = new ZodError(issues);
252
258
  return error;
253
259
  };
254
- const defaultErrorMap = (issue, _ctx) => {
260
+
261
+ const errorMap = (issue, _ctx) => {
255
262
  let message;
256
263
  switch (issue.code) {
257
264
  case ZodIssueCode.invalid_type:
@@ -263,7 +270,7 @@
263
270
  }
264
271
  break;
265
272
  case ZodIssueCode.invalid_literal:
266
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, jsonStringifyReplacer)}`;
273
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
267
274
  break;
268
275
  case ZodIssueCode.unrecognized_keys:
269
276
  message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
@@ -344,7 +351,8 @@
344
351
  }
345
352
  return { message };
346
353
  };
347
- let overrideErrorMap = defaultErrorMap;
354
+
355
+ let overrideErrorMap = errorMap;
348
356
  function setErrorMap(map) {
349
357
  overrideErrorMap = map;
350
358
  }
@@ -383,7 +391,7 @@
383
391
  ctx.common.contextualErrorMap,
384
392
  ctx.schemaErrorMap,
385
393
  getErrorMap(),
386
- defaultErrorMap,
394
+ errorMap,
387
395
  ].filter((x) => !!x),
388
396
  });
389
397
  ctx.common.issues.push(issue);
@@ -449,12 +457,6 @@
449
457
  const isDirty = (x) => x.status === "dirty";
450
458
  const isValid = (x) => x.status === "valid";
451
459
  const isAsync = (x) => typeof Promise !== undefined && x instanceof Promise;
452
- const jsonStringifyReplacer = (_, value) => {
453
- if (typeof value === "bigint") {
454
- return value.toString();
455
- }
456
- return value;
457
- };
458
460
 
459
461
  var errorUtil;
460
462
  (function (errorUtil) {
@@ -490,7 +492,7 @@
490
492
  return {};
491
493
  const { errorMap, invalid_type_error, required_error, description } = params;
492
494
  if (errorMap && (invalid_type_error || required_error)) {
493
- throw new Error(`Can't use "invalid" or "required" in conjunction with custom error map.`);
495
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
494
496
  }
495
497
  if (errorMap)
496
498
  return { errorMap: errorMap, description };
@@ -2181,6 +2183,9 @@
2181
2183
  }
2182
2184
  }
2183
2185
  ZodTuple.create = (schemas, params) => {
2186
+ if (!Array.isArray(schemas)) {
2187
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2188
+ }
2184
2189
  return new ZodTuple({
2185
2190
  items: schemas,
2186
2191
  typeName: exports.ZodFirstPartyTypeKind.ZodTuple,
@@ -2409,7 +2414,7 @@
2409
2414
  ctx.common.contextualErrorMap,
2410
2415
  ctx.schemaErrorMap,
2411
2416
  getErrorMap(),
2412
- defaultErrorMap,
2417
+ errorMap,
2413
2418
  ].filter((x) => !!x),
2414
2419
  issueData: {
2415
2420
  code: ZodIssueCode.invalid_arguments,
@@ -2425,7 +2430,7 @@
2425
2430
  ctx.common.contextualErrorMap,
2426
2431
  ctx.schemaErrorMap,
2427
2432
  getErrorMap(),
2428
- defaultErrorMap,
2433
+ errorMap,
2429
2434
  ].filter((x) => !!x),
2430
2435
  issueData: {
2431
2436
  code: ZodIssueCode.invalid_return_type,
@@ -2495,17 +2500,17 @@
2495
2500
  const validatedFunc = this.parse(func);
2496
2501
  return validatedFunc;
2497
2502
  }
2503
+ static create(args, returns, params) {
2504
+ return new ZodFunction({
2505
+ args: (args
2506
+ ? args
2507
+ : ZodTuple.create([]).rest(ZodUnknown.create())),
2508
+ returns: returns || ZodUnknown.create(),
2509
+ typeName: exports.ZodFirstPartyTypeKind.ZodFunction,
2510
+ ...processCreateParams(params),
2511
+ });
2512
+ }
2498
2513
  }
2499
- ZodFunction.create = (args, returns, params) => {
2500
- return new ZodFunction({
2501
- args: (args
2502
- ? args.rest(ZodUnknown.create())
2503
- : ZodTuple.create([]).rest(ZodUnknown.create())),
2504
- returns: returns || ZodUnknown.create(),
2505
- typeName: exports.ZodFirstPartyTypeKind.ZodFunction,
2506
- ...processCreateParams(params),
2507
- });
2508
- };
2509
2514
  class ZodLazy extends ZodType {
2510
2515
  get schema() {
2511
2516
  return this._def.getter();
@@ -2950,6 +2955,12 @@
2950
2955
  ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
2951
2956
  ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
2952
2957
  })(exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
2958
+ // new approach that works for abstract classes
2959
+ // but required TS 4.4+
2960
+ // abstract class Class {
2961
+ // constructor(..._: any[]) {}
2962
+ // }
2963
+ // const instanceOfType = <T extends typeof Class>(
2953
2964
  const instanceOfType = (cls, params = {
2954
2965
  message: `Input not instance of ${cls.name}`,
2955
2966
  }) => custom((data) => data instanceof cls, params, true);
@@ -2988,11 +2999,15 @@
2988
2999
  const ostring = () => stringType().optional();
2989
3000
  const onumber = () => numberType().optional();
2990
3001
  const oboolean = () => booleanType().optional();
3002
+ const NEVER = INVALID;
2991
3003
 
2992
3004
  var mod = /*#__PURE__*/Object.freeze({
2993
3005
  __proto__: null,
2994
3006
  getParsedType: getParsedType,
2995
3007
  ZodParsedType: ZodParsedType,
3008
+ defaultErrorMap: errorMap,
3009
+ setErrorMap: setErrorMap,
3010
+ getErrorMap: getErrorMap,
2996
3011
  makeIssue: makeIssue,
2997
3012
  EMPTY_PATH: EMPTY_PATH,
2998
3013
  addIssueToContext: addIssueToContext,
@@ -3004,7 +3019,6 @@
3004
3019
  isDirty: isDirty,
3005
3020
  isValid: isValid,
3006
3021
  isAsync: isAsync,
3007
- jsonStringifyReplacer: jsonStringifyReplacer,
3008
3022
  ZodType: ZodType,
3009
3023
  ZodString: ZodString,
3010
3024
  ZodNumber: ZodNumber,
@@ -3083,18 +3097,17 @@
3083
3097
  union: unionType,
3084
3098
  unknown: unknownType,
3085
3099
  'void': voidType,
3100
+ NEVER: NEVER,
3086
3101
  ZodIssueCode: ZodIssueCode,
3087
3102
  quotelessJson: quotelessJson,
3088
- ZodError: ZodError,
3089
- defaultErrorMap: defaultErrorMap,
3090
- setErrorMap: setErrorMap,
3091
- getErrorMap: getErrorMap
3103
+ ZodError: ZodError
3092
3104
  });
3093
3105
 
3094
3106
  exports.BRAND = BRAND;
3095
3107
  exports.DIRTY = DIRTY;
3096
3108
  exports.EMPTY_PATH = EMPTY_PATH;
3097
3109
  exports.INVALID = INVALID;
3110
+ exports.NEVER = NEVER;
3098
3111
  exports.OK = OK;
3099
3112
  exports.ParseStatus = ParseStatus;
3100
3113
  exports.Schema = ZodType;
@@ -3144,7 +3157,7 @@
3144
3157
  exports.custom = custom;
3145
3158
  exports.date = dateType;
3146
3159
  exports["default"] = mod;
3147
- exports.defaultErrorMap = defaultErrorMap;
3160
+ exports.defaultErrorMap = errorMap;
3148
3161
  exports.discriminatedUnion = discriminatedUnionType;
3149
3162
  exports.effect = effectsType;
3150
3163
  exports["enum"] = enumType;
@@ -3157,7 +3170,6 @@
3157
3170
  exports.isAsync = isAsync;
3158
3171
  exports.isDirty = isDirty;
3159
3172
  exports.isValid = isValid;
3160
- exports.jsonStringifyReplacer = jsonStringifyReplacer;
3161
3173
  exports.late = late;
3162
3174
  exports.lazy = lazyType;
3163
3175
  exports.literal = literalType;
@@ -0,0 +1,3 @@
1
+ import { ZodErrorMap } from "../ZodError";
2
+ declare const errorMap: ZodErrorMap;
3
+ export default errorMap;
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const util_1 = require("../helpers/util");
4
+ const ZodError_1 = require("../ZodError");
5
+ const errorMap = (issue, _ctx) => {
6
+ let message;
7
+ switch (issue.code) {
8
+ case ZodError_1.ZodIssueCode.invalid_type:
9
+ if (issue.received === util_1.ZodParsedType.undefined) {
10
+ message = "Required";
11
+ }
12
+ else {
13
+ message = `Expected ${issue.expected}, received ${issue.received}`;
14
+ }
15
+ break;
16
+ case ZodError_1.ZodIssueCode.invalid_literal:
17
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`;
18
+ break;
19
+ case ZodError_1.ZodIssueCode.unrecognized_keys:
20
+ message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`;
21
+ break;
22
+ case ZodError_1.ZodIssueCode.invalid_union:
23
+ message = `Invalid input`;
24
+ break;
25
+ case ZodError_1.ZodIssueCode.invalid_union_discriminator:
26
+ message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`;
27
+ break;
28
+ case ZodError_1.ZodIssueCode.invalid_enum_value:
29
+ message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`;
30
+ break;
31
+ case ZodError_1.ZodIssueCode.invalid_arguments:
32
+ message = `Invalid function arguments`;
33
+ break;
34
+ case ZodError_1.ZodIssueCode.invalid_return_type:
35
+ message = `Invalid function return type`;
36
+ break;
37
+ case ZodError_1.ZodIssueCode.invalid_date:
38
+ message = `Invalid date`;
39
+ break;
40
+ case ZodError_1.ZodIssueCode.invalid_string:
41
+ if (typeof issue.validation === "object") {
42
+ if ("startsWith" in issue.validation) {
43
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
44
+ }
45
+ else if ("endsWith" in issue.validation) {
46
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
47
+ }
48
+ else {
49
+ util_1.util.assertNever(issue.validation);
50
+ }
51
+ }
52
+ else if (issue.validation !== "regex") {
53
+ message = `Invalid ${issue.validation}`;
54
+ }
55
+ else {
56
+ message = "Invalid";
57
+ }
58
+ break;
59
+ case ZodError_1.ZodIssueCode.too_small:
60
+ if (issue.type === "array")
61
+ message = `Array must contain ${issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
62
+ else if (issue.type === "string")
63
+ message = `String must contain ${issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
64
+ else if (issue.type === "number")
65
+ message = `Number must be greater than ${issue.inclusive ? `or equal to ` : ``}${issue.minimum}`;
66
+ else if (issue.type === "date")
67
+ message = `Date must be greater than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.minimum)}`;
68
+ else
69
+ message = "Invalid input";
70
+ break;
71
+ case ZodError_1.ZodIssueCode.too_big:
72
+ if (issue.type === "array")
73
+ message = `Array must contain ${issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
74
+ else if (issue.type === "string")
75
+ message = `String must contain ${issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
76
+ else if (issue.type === "number")
77
+ message = `Number must be less than ${issue.inclusive ? `or equal to ` : ``}${issue.maximum}`;
78
+ else if (issue.type === "date")
79
+ message = `Date must be smaller than ${issue.inclusive ? `or equal to ` : ``}${new Date(issue.maximum)}`;
80
+ else
81
+ message = "Invalid input";
82
+ break;
83
+ case ZodError_1.ZodIssueCode.custom:
84
+ message = `Invalid input`;
85
+ break;
86
+ case ZodError_1.ZodIssueCode.invalid_intersection_types:
87
+ message = `Intersection results could not be merged`;
88
+ break;
89
+ case ZodError_1.ZodIssueCode.not_multiple_of:
90
+ message = `Number must be a multiple of ${issue.multipleOf}`;
91
+ break;
92
+ default:
93
+ message = _ctx.defaultError;
94
+ util_1.util.assertNever(issue);
95
+ }
96
+ return { message };
97
+ };
98
+ exports.default = errorMap;
package/lib/types.d.ts CHANGED
@@ -379,7 +379,7 @@ export declare class ZodObject<T extends ZodRawShape, UnknownKeys extends Unknow
379
379
  * inferred type of merged objects. Please
380
380
  * upgrade if you are experiencing issues.
381
381
  */
382
- merge<Incoming extends AnyZodObject>(merging: Incoming): ZodObject<extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, UnknownKeys, Catchall>;
382
+ merge<Incoming extends AnyZodObject>(merging: Incoming): ZodObject<extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, Incoming["_def"]["unknownKeys"], Incoming["_def"]["catchall"]>;
383
383
  catchall<Index extends ZodTypeAny>(index: Index): ZodObject<T, UnknownKeys, Index>;
384
384
  pick<Mask extends {
385
385
  [k in keyof T]?: true;
@@ -470,6 +470,10 @@ export interface ZodTupleDef<T extends ZodTupleItems | [] = ZodTupleItems, Rest
470
470
  rest: Rest;
471
471
  typeName: ZodFirstPartyTypeKind.ZodTuple;
472
472
  }
473
+ export declare type AnyZodTuple = ZodTuple<[
474
+ ZodTypeAny,
475
+ ...ZodTypeAny[]
476
+ ] | [], ZodTypeAny | null>;
473
477
  export declare class ZodTuple<T extends [ZodTypeAny, ...ZodTypeAny[]] | [] = [ZodTypeAny, ...ZodTypeAny[]], Rest extends ZodTypeAny | null = null> extends ZodType<OutputTypeOfTupleWithRest<T, Rest>, ZodTupleDef<T, Rest>, InputTypeOfTupleWithRest<T, Rest>> {
474
478
  _parse(input: ParseInput): ParseReturnType<this["_output"]>;
475
479
  get items(): T;
@@ -536,7 +540,10 @@ export declare class ZodFunction<Args extends ZodTuple<any, any>, Returns extend
536
540
  implement<F extends InnerTypeOfFunction<Args, Returns>>(func: F): ReturnType<F> extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType<F> : OuterTypeOfFunction<Args, Returns>;
537
541
  strictImplement(func: InnerTypeOfFunction<Args, Returns>): InnerTypeOfFunction<Args, Returns>;
538
542
  validate: <F extends InnerTypeOfFunction<Args, Returns>>(func: F) => ReturnType<F> extends Returns["_output"] ? (...args: Args["_input"]) => ReturnType<F> : OuterTypeOfFunction<Args, Returns>;
539
- static create: <T extends ZodTuple<any, any> = ZodTuple<[], ZodUnknown>, U extends ZodTypeAny = ZodUnknown>(args?: T | undefined, returns?: U | undefined, params?: RawCreateParams) => ZodFunction<T, U>;
543
+ static create(): ZodFunction<ZodTuple<[], ZodUnknown>, ZodUnknown>;
544
+ static create<T extends AnyZodTuple = ZodTuple<[], ZodUnknown>>(args: T): ZodFunction<T, ZodUnknown>;
545
+ static create<T extends AnyZodTuple, U extends ZodTypeAny>(args: T, returns: U): ZodFunction<T, U>;
546
+ static create<T extends AnyZodTuple = ZodTuple<[], ZodUnknown>, U extends ZodTypeAny = ZodUnknown>(args: T, returns: U, params?: RawCreateParams): ZodFunction<T, U>;
540
547
  }
541
548
  export interface ZodLazyDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef {
542
549
  getter: () => T;
@@ -741,7 +748,7 @@ declare const tupleType: <T extends [] | [ZodTypeAny, ...ZodTypeAny[]]>(schemas:
741
748
  declare const recordType: typeof ZodRecord.create;
742
749
  declare const mapType: <Key extends ZodTypeAny = ZodTypeAny, Value extends ZodTypeAny = ZodTypeAny>(keyType: Key, valueType: Value, params?: RawCreateParams) => ZodMap<Key, Value>;
743
750
  declare const setType: <Value extends ZodTypeAny = ZodTypeAny>(valueType: Value, params?: RawCreateParams) => ZodSet<Value>;
744
- declare const functionType: <T extends ZodTuple<any, any> = ZodTuple<[], ZodUnknown>, U extends ZodTypeAny = ZodUnknown>(args?: T | undefined, returns?: U | undefined, params?: RawCreateParams) => ZodFunction<T, U>;
751
+ declare const functionType: typeof ZodFunction.create;
745
752
  declare const lazyType: <T extends ZodTypeAny>(getter: () => T, params?: RawCreateParams) => ZodLazy<T>;
746
753
  declare const literalType: <T extends string | number | bigint | boolean | null | undefined>(value: T, params?: RawCreateParams) => ZodLiteral<T>;
747
754
  declare const enumType: typeof createZodEnum;
@@ -755,3 +762,4 @@ declare const ostring: () => ZodOptional<ZodString>;
755
762
  declare const onumber: () => ZodOptional<ZodNumber>;
756
763
  declare const oboolean: () => ZodOptional<ZodBoolean>;
757
764
  export { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };
765
+ export declare const NEVER: never;
package/lib/types.js CHANGED
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.function = exports.enum = exports.effect = exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.objectUtil = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;
4
- exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = void 0;
4
+ exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = void 0;
5
+ const errors_1 = require("./errors");
5
6
  const errorUtil_1 = require("./helpers/errorUtil");
6
7
  const parseUtil_1 = require("./helpers/parseUtil");
7
8
  const util_1 = require("./helpers/util");
@@ -34,7 +35,7 @@ function processCreateParams(params) {
34
35
  return {};
35
36
  const { errorMap, invalid_type_error, required_error, description } = params;
36
37
  if (errorMap && (invalid_type_error || required_error)) {
37
- throw new Error(`Can't use "invalid" or "required" in conjunction with custom error map.`);
38
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
38
39
  }
39
40
  if (errorMap)
40
41
  return { errorMap: errorMap, description };
@@ -1746,6 +1747,9 @@ class ZodTuple extends ZodType {
1746
1747
  }
1747
1748
  exports.ZodTuple = ZodTuple;
1748
1749
  ZodTuple.create = (schemas, params) => {
1750
+ if (!Array.isArray(schemas)) {
1751
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
1752
+ }
1749
1753
  return new ZodTuple({
1750
1754
  items: schemas,
1751
1755
  typeName: ZodFirstPartyTypeKind.ZodTuple,
@@ -1976,8 +1980,8 @@ class ZodFunction extends ZodType {
1976
1980
  errorMaps: [
1977
1981
  ctx.common.contextualErrorMap,
1978
1982
  ctx.schemaErrorMap,
1979
- ZodError_1.getErrorMap(),
1980
- ZodError_1.defaultErrorMap,
1983
+ errors_1.getErrorMap(),
1984
+ errors_1.defaultErrorMap,
1981
1985
  ].filter((x) => !!x),
1982
1986
  issueData: {
1983
1987
  code: ZodError_1.ZodIssueCode.invalid_arguments,
@@ -1992,8 +1996,8 @@ class ZodFunction extends ZodType {
1992
1996
  errorMaps: [
1993
1997
  ctx.common.contextualErrorMap,
1994
1998
  ctx.schemaErrorMap,
1995
- ZodError_1.getErrorMap(),
1996
- ZodError_1.defaultErrorMap,
1999
+ errors_1.getErrorMap(),
2000
+ errors_1.defaultErrorMap,
1997
2001
  ].filter((x) => !!x),
1998
2002
  issueData: {
1999
2003
  code: ZodError_1.ZodIssueCode.invalid_return_type,
@@ -2063,18 +2067,18 @@ class ZodFunction extends ZodType {
2063
2067
  const validatedFunc = this.parse(func);
2064
2068
  return validatedFunc;
2065
2069
  }
2070
+ static create(args, returns, params) {
2071
+ return new ZodFunction({
2072
+ args: (args
2073
+ ? args
2074
+ : ZodTuple.create([]).rest(ZodUnknown.create())),
2075
+ returns: returns || ZodUnknown.create(),
2076
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
2077
+ ...processCreateParams(params),
2078
+ });
2079
+ }
2066
2080
  }
2067
2081
  exports.ZodFunction = ZodFunction;
2068
- ZodFunction.create = (args, returns, params) => {
2069
- return new ZodFunction({
2070
- args: (args
2071
- ? args.rest(ZodUnknown.create())
2072
- : ZodTuple.create([]).rest(ZodUnknown.create())),
2073
- returns: returns || ZodUnknown.create(),
2074
- typeName: ZodFirstPartyTypeKind.ZodFunction,
2075
- ...processCreateParams(params),
2076
- });
2077
- };
2078
2082
  class ZodLazy extends ZodType {
2079
2083
  get schema() {
2080
2084
  return this._def.getter();
@@ -2532,6 +2536,12 @@ var ZodFirstPartyTypeKind;
2532
2536
  ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
2533
2537
  ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
2534
2538
  })(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {}));
2539
+ // new approach that works for abstract classes
2540
+ // but required TS 4.4+
2541
+ // abstract class Class {
2542
+ // constructor(..._: any[]) {}
2543
+ // }
2544
+ // const instanceOfType = <T extends typeof Class>(
2535
2545
  const instanceOfType = (cls, params = {
2536
2546
  message: `Input not instance of ${cls.name}`,
2537
2547
  }) => exports.custom((data) => data instanceof cls, params, true);
@@ -2607,3 +2617,4 @@ const onumber = () => numberType().optional();
2607
2617
  exports.onumber = onumber;
2608
2618
  const oboolean = () => booleanType().optional();
2609
2619
  exports.oboolean = oboolean;
2620
+ exports.NEVER = parseUtil_1.INVALID;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zod",
3
- "version": "3.18.0",
3
+ "version": "3.19.0-beta.0",
4
4
  "description": "TypeScript-first schema declaration and validation library with static type inference",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./index.d.ts",
@@ -12,7 +12,8 @@
12
12
  "import": "./lib/index.mjs",
13
13
  "types": "./index.d.ts"
14
14
  },
15
- "./package.json": "./package.json"
15
+ "./package.json": "./package.json",
16
+ "./locales/*": "./lib/locales/*"
16
17
  },
17
18
  "files": [
18
19
  "/lib",