Socket
Socket
Sign inDemoInstall

zod

Package Overview
Dependencies
0
Maintainers
1
Versions
360
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.6.2 to 1.7.0

1

lib/src/helpers/objectUtil.js

@@ -35,2 +35,3 @@ "use strict";

t: base_1.ZodTypes.object,
checks: (first._def.checks || []).concat((second._def.checks || [])),
// strict: first.params.strict && second.params.strict,

@@ -37,0 +38,0 @@ params: {

30

lib/src/playground.js
"use strict";
// import * as z from '.';
// // const stringSchema = z.string();
// // try {
// // stringSchema.parse(12);
// // } catch (err) {
// // const zerr: z.ZodError = err;
// // zerr.stack;
// // console.log(err instanceof z.ZodError);
// // if (err instanceof z.ZodError) {
// // // handle
// // // err.
// // }
// // }
// const myObject = z
// .object({
// first: z.string(),
// second: z.string(),
// })
// .partial()
// .refine(data => data.first || data.second, 'Either first or second should be filled in.');
// myObject.parse({
// first: 'asdf',
// });
// myObject.parse({
// second: 'asdf',
// });
// myObject.parse({
// first: 'wqewdscsdf',
// second: 'asdf',
// });
// myObject.parse({});
//# sourceMappingURL=playground.js.map

@@ -18,2 +18,5 @@ import * as z from './base';

nullable: () => ZodUnion<[this, ZodNull]>;
min: (minLength: number, msg?: string | undefined) => this;
max: (maxLength: number, msg?: string | undefined) => this;
length: (len: number, msg?: string | undefined) => this;
nonempty: () => ZodNonEmptyArray<T>;

@@ -20,0 +23,0 @@ static create: <T_1 extends z.ZodType<any, z.ZodTypeDef>>(schema: T_1) => ZodArray<T_1>;

@@ -51,2 +51,11 @@ "use strict";

_this.nullable = function () { return union_1.ZodUnion.create([_this, null_1.ZodNull.create()]); };
_this.min = function (minLength, msg) {
return _this.refine(function (data) { return data.length >= minLength; }, msg || "Array must contain " + minLength + " or more items.");
};
_this.max = function (maxLength, msg) {
return _this.refine(function (data) { return data.length <= maxLength; }, msg || "Array must contain " + maxLength + " or fewer items.");
};
_this.length = function (len, msg) {
return _this.refine(function (data) { return data.length == len; }, msg || "Array must contain " + len + " items.");
};
_this.nonempty = function () {

@@ -53,0 +62,0 @@ return new ZodNonEmptyArray(__assign({}, _this._def, { nonempty: true }));

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -44,5 +55,6 @@ var parser_1 = require("../parser");

if (message === void 0) { message = 'Invalid value.'; }
_this._def.checks = _this._def.checks || [];
_this._def.checks.push({ check: check, message: message });
return _this;
// const newChecks = [...this._def.checks || [], { check, message }];
// console.log((this as any).constructor);
return new _this.constructor(__assign({}, _this._def, { checks: (_this._def.checks || []).concat([{ check: check, message: message }]) }));
// return this;
};

@@ -49,0 +61,0 @@ this.parse = parser_1.ZodParser(def);

@@ -13,2 +13,9 @@ import * as z from './base';

static create: () => ZodNumber;
min: (minimum: number, msg?: string | undefined) => this;
max: (maximum: number, msg?: string | undefined) => this;
int: (msg?: string | undefined) => this;
positive: (msg?: string | undefined) => this;
negative: (msg?: string | undefined) => this;
nonpositive: (msg?: string | undefined) => this;
nonnegative: (msg?: string | undefined) => this;
}

@@ -34,2 +34,9 @@ "use strict";

_this.toJSON = function () { return _this._def; };
_this.min = function (minimum, msg) { return _this.refine(function (data) { return data >= minimum; }, msg || "Value must be >= " + minimum); };
_this.max = function (maximum, msg) { return _this.refine(function (data) { return data <= maximum; }, msg || "Value must be <= " + maximum); };
_this.int = function (msg) { return _this.refine(function (data) { return Number.isInteger(data); }, msg || 'Value must be an integer.'); };
_this.positive = function (msg) { return _this.refine(function (data) { return data > 0; }, msg || "Value must be positive"); };
_this.negative = function (msg) { return _this.refine(function (data) { return data < 0; }, msg || "Value must be negative"); };
_this.nonpositive = function (msg) { return _this.refine(function (data) { return data <= 0; }, msg || "Value must be non-positive"); };
_this.nonnegative = function (msg) { return _this.refine(function (data) { return data >= 0; }, msg || "Value must be non-negative"); };
return _this;

@@ -36,0 +43,0 @@ }

@@ -16,3 +16,9 @@ import * as z from './base';

toJSON: () => ZodStringDef;
min: (minLength: number, msg?: string | undefined) => this;
max: (maxLength: number, msg?: string | undefined) => this;
length: (len: number, msg?: string | undefined) => this;
email: (msg?: string | undefined) => this;
url: (msg?: string | undefined) => this;
nonempty: (msg?: string | undefined) => this;
static create: () => ZodString;
}

@@ -27,2 +27,6 @@ "use strict";

var union_1 = require("./union");
// eslint-disable-next-line
var emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
// eslint-disable-next-line
var urlRegex = /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
var ZodString = /** @class */ (function (_super) {

@@ -35,2 +39,14 @@ __extends(ZodString, _super);

_this.toJSON = function () { return _this._def; };
_this.min = function (minLength, msg) {
return _this.refine(function (data) { return data.length >= minLength; }, msg || "Value must be " + minLength + " or more characters long");
};
_this.max = function (maxLength, msg) {
return _this.refine(function (data) { return data.length <= maxLength; }, msg || "Value must be " + maxLength + " or fewer characters long");
};
_this.length = function (len, msg) {
return _this.refine(function (data) { return data.length == len; }, msg || "Value must be " + len + " characters long.");
};
_this.email = function (msg) { return _this.refine(function (data) { return emailRegex.test(data); }, msg || 'Invalid email address.'); };
_this.url = function (msg) { return _this.refine(function (data) { return urlRegex.test(data); }, msg || 'Invalid URL.'); };
_this.nonempty = function (msg) { return _this.refine(function (data) { return data.length > 0; }, msg || 'Value cannot be empty string'); };
return _this;

@@ -37,0 +53,0 @@ }

{
"name": "zod",
"version": "1.6.2",
"version": "1.7.0",
"description": "TypeScript-first schema declaration and validation library with static type inference",

@@ -49,2 +49,3 @@ "main": "./lib/src/index.js",

"test": "jest --config jestconfig.json --coverage && yarn run badge",
"testone": "jest --config jestconfig.json ",
"badge": "make-coverage-badge --output-path ./coverage.svg",

@@ -65,2 +66,2 @@ "prepare": "npm run build",

}
}
}

@@ -78,3 +78,3 @@ <p align="center">

You must use strict mode for Zod to correctly infer the types of your schemas! Add `"strict": true` inside "compilerOptions" in your `tsconfig.json`.
> You must use strict mode for Zod to correctly infer the types of your schemas! Add `"strict": true` inside "compilerOptions" in your `tsconfig.json`.

@@ -85,29 +85,35 @@ # Usage

- It takes advantage of TypeScript generic inference to statically infer the types of your schemas, eliminating the need to define static types and runtime validators separately.
<!-- - It infers the statically types of your schemas
- Eliminates the need to keep static types and runtime validators in sync by hand
- It has a composable, declarative API that makes it easy to define complex types concisely.
- Schemas are immutable. All methods return a new schema instance.
- Schemas are immutable. All methods return a new schema instance. -->
Zod was also designed with some core principles designed to make all declarations as non-magical and developer-friendly as possible:
<!-- Zod was also designed with some core principles designed to make all declarations as non-magical and developer-friendly as possible: -->
- All fields are required unless explicitly marked as optional (just like TypeScript!)
- Schemas are immutable; methods (i.e. `.optional()` return a new instance.
- Zod schemas operate on a ["Parse, don't validate!"](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/) basis!
- Zero dependencies (5kb compressed)
- Immutability; methods (i.e. `.optional()` return a new instance
- Concise, chainable interface
- Functional approach (["Parse, don't validate!"](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/))
## Primitives
You can create a Zod schema for any TypeScript primitive.
```ts
import * as z from 'zod';
const stringSchema = z.string(); // => ZodType<string>
const numberSchema = z.number(); // => ZodType<number>
const bigintSchema = z.bigint(); // => ZodType<bigint>
const booleanSchema = z.boolean(); // => ZodType<boolean>
const dateSchema = z.date(); // => ZodType<Date>
// primitive values
z.string();
z.number();
z.bigint();
z.boolean();
z.date();
const undefinedSchema = z.undefined(); // => ZodType<undefined>
const nullSchema = z.null(); // => ZodType<null>
// empty types
z.undefined();
z.null();
const anySchema = z.any(); // => ZodType<any>
const unknownSchema = z.unknown(); // => ZodType<unknown>
// catch-all types
z.any();
z.unknown();
```

@@ -118,20 +124,22 @@

```ts
const tuna = z.literal('tuna'); // => ZodType<'tuna'>
const twelve = z.literal(12); // => ZodType<12>
const tru = z.literal(true); // => ZodType<true>
const tuna = z.literal('tuna');
const twelve = z.literal(12);
const tru = z.literal(true);
```
Currently there is no support for Date literals in Zod. If you have a use case for this feature, please file an issue.
> Currently there is no support for Date or bigint literals in Zod. If you have a use case for this feature, please file an issue.
## Parsing and validation
## Validation
### Parsing
Given a Zod schema, you can call its `.parse(data)` method to check `data` is valid. If it is, a value is returned with full type information! Otherwise, an error is thrown.
`.parse(data:unknown)`
IMPORTANT: As of Zod 1.4, the value returned by `.parse` is _the same variable you passed in_. Previously it returned a deep clone. One exception: "parsing" a `Promise` schemas returns a new Promise for reasons explained in the documentation.
Given any Zod schema, you can call its `.parse` method to check `data` is valid. If it is, a value is returned with full type information! Otherwise, an error is thrown.
> IMPORTANT: As of Zod 1.4, the value returned by `.parse` is _the same variable you passed in_. Previously it returned a deep clone. The only exception to this is `Promise` schemas, which return a new Promise for reasons explained in the documentation.
```ts
const stringSchema = z.string();
stringSchema.parse('fish'); // => "fish"
stringSchema.parse('fish'); // => returns "fish"
stringSchema.parse(12); // throws Error('Non-string type: number');

@@ -142,2 +150,4 @@ ```

`.check(data:unknown)`
You can also use a Zod schema as a type guard using the schema's `.check()` method, like so:

@@ -173,6 +183,8 @@

Every Zod schema has a `.refine` method that lets you define custom validation checks. Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an Int or that a string is a valid email address.
`.refine(validator: (data:T)=>any, err?: string)`
In these cases, you would use the `.refine` method.
Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an Int or that a string is a valid email address.
For this instances, you can define custom a validation check on _any_ Zod schema with `.refine`:
```ts

@@ -182,4 +194,9 @@ const myString = z.string().refine(val => val.length <= 255, "String can't be more than 255 characters");

As you can see, `.refine` takes two arguments. The first is the validation function, and the second is a custom error message . The argument to the validation function (`val` in the example above) is statically typed to be the inferred type of the schema.
Here is the type signature for `.refine`:
As you can see, `.refine` takes two arguments.
1. The first is the validation function. This function takes one input (of type `T` — the inferred type of the schema) and returns `any`. Any truthy value will pass validation. (Prior to zod@1.6.2 the validation function had to return a boolean.)
2. The second argument is a custom error message. Read more about error handling in Zod [here](#errors)
Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of useful string validation functions.

@@ -189,3 +206,3 @@

You can extract the TypeScript type of any schema with `z.infer<typeof [schema]>`.
You can extract the TypeScript type of any schema with `z.infer<typeof mySchema>`.

@@ -202,2 +219,48 @@ ```ts

## Strings
There are a handful of string-specific validations.
All of these validations allow you to _optionally_ specify a custom error message.
```ts
z.string().min(5);
z.string().max(5);
z.string().length(5);
z.string().email();
z.string().url();
```
### Custom error messages
Like `.refine`, the final argument accepts a custom error message.
```ts
z.string().min(5, 'Must be 5 or more characters long');
z.string().max(5, 'Must be 5 or fewer characters long');
z.string().length(5, 'Must be exactly 5 characters long');
z.string().email('Invalid email address.');
z.string().url('Invalid url');
```
> To see the email and url regexes, check out [this file](https://github.com/vriad/zod/blob/master/src/types/string.ts). To use a more advanced method, use a custom refinement.
## Numbers
There are a handful of number-specific validations.
All of these validations allow you to _optionally_ specify a custom error message as a final `string` argument.
```ts
z.number().min(5);
z.number().max(5);
z.number().int(5); // value must be an integer
z.number().positive(); // > 0
z.number().nonnegative(); // >= 0
z.number().negative(); // < 0
z.number().nonpositive(); // <= 0
```
## Objects

@@ -233,4 +296,9 @@

Use `.shape` to access an object schema's property schemas.
```ts
const Location = z.object({ latitude: z.number(), longitude: z.number() });
const Location = z.object({
latitude: z.number(),
longitude: z.number(),
});

@@ -267,3 +335,3 @@ const Business = z.object({

IMPORTANT: the schema returned by `.merge` is the _intersection_ of the two schemas. The schema passed into `.merge` does not "overwrite" properties of the original schema. To demonstrate:
> IMPORTANT: the schema returned by `.merge` is the _intersection_ of the two schemas. The schema passed into `.merge` does not "overwrite" properties of the original schema. To demonstrate:

@@ -538,2 +606,15 @@ ```ts

#### Length validations
```ts
// must contain 5 or more items
z.array(z.string()).min(5);
// must contain 5 or fewer items
z.array(z.string()).max(5);
// must contain exactly 5 items
z.array(z.string()).length(5);
```
## Unions

@@ -1180,16 +1261,17 @@

| zod version | release notes |
| ----------- | ------------------------------------------------------------------- |
| zod@1.5 | Any and unknown types |
| zod@1.4 | Refinement types (`.refine`), `.parse` no longer returns deep clone |
| zod@1.3 | Promise schemas |
| zod@1.2.6 | `.parse` accepts `unknown`, `bigint` schemas |
| zod@1.2.5 | `.partial` and `.deepPartial` on object schemas |
| zod@1.2.3 | Date schemas |
| zod@1.2.0 | `.pick`, `.omit`, and `.augment` on object schemas |
| zod@1.1.0 | Records |
| zod@1.0.11 | `.nonstrict` |
| zod@1.0.10 | Type assertions with `.check` |
| zod@1.0.4 | Empty tuples |
| zod@1.0.0 | Type assertions, literals, enums, detailed error reporting |
| zod@1.0.0 | Initial release |
| zod version | release notes |
| ----------- | ------------------------------------------------------------------------------------------------------------------- |
| zod@1.7 | Added several built-in validators to string, number, and array schemas. Calls to `.refine` now return new instance. |
| zod@1.5 | Any and unknown types |
| zod@1.4 | Refinement types (`.refine`), `.parse` no longer returns deep clone |
| zod@1.3 | Promise schemas |
| zod@1.2.6 | `.parse` accepts `unknown`, `bigint` schemas |
| zod@1.2.5 | `.partial` and `.deepPartial` on object schemas |
| zod@1.2.3 | Date schemas |
| zod@1.2.0 | `.pick`, `.omit`, and `.augment` on object schemas |
| zod@1.1.0 | Records |
| zod@1.0.11 | `.nonstrict` |
| zod@1.0.10 | Type assertions with `.check` |
| zod@1.0.4 | Empty tuples |
| zod@1.0.0 | Type assertions, literals, enums, detailed error reporting |
| zod@1.0.0 | Initial release |

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc