Socket
Socket
Sign inDemoInstall

zod

Package Overview
Dependencies
Maintainers
1
Versions
361
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

zod - npm Package Compare versions

Comparing version 1.0.10 to 1.0.11

lib/ZodError.d.ts

5

lib/index.d.ts

@@ -16,3 +16,4 @@ import { ZodString, ZodStringDef } from './types/string';

import { TypeOf, ZodType, ZodAny } from './types/base';
export declare type ZodDef = ZodStringDef | ZodNumberDef | ZodBooleanDef | ZodUndefinedDef | ZodNullDef | ZodArrayDef | ZodObjectDef | ZodUnionDef | ZodIntersectionDef | ZodTupleDef | ZodFunctionDef | ZodLazyDef | ZodLiteralDef | ZodEnumDef;
import { ZodError } from './ZodError';
declare type ZodDef = ZodStringDef | ZodNumberDef | ZodBooleanDef | ZodUndefinedDef | ZodNullDef | ZodArrayDef | ZodObjectDef | ZodUnionDef | ZodIntersectionDef | ZodTupleDef | ZodFunctionDef | ZodLazyDef | ZodLiteralDef | ZodEnumDef;
declare const stringType: () => ZodString;

@@ -36,3 +37,3 @@ declare const numberType: () => ZodNumber;

export { stringType as string, numberType as number, booleanType as boolean, undefinedType as undefined, nullType as null, arrayType as array, objectType as object, unionType as union, intersectionType as intersection, tupleType as tuple, functionType as function, lazyType as lazy, literalType as literal, enumType as enum, ostring, onumber, oboolean, };
export { ZodString, ZodNumber, ZodBoolean, ZodUndefined, ZodNull, ZodArray, ZodObject, ZodUnion, ZodIntersection, ZodTuple, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodType, ZodAny, };
export { ZodString, ZodNumber, ZodBoolean, ZodUndefined, ZodNull, ZodArray, ZodObject, ZodUnion, ZodIntersection, ZodTuple, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodType, ZodAny, ZodDef, ZodError, };
export { TypeOf, TypeOf as Infer };

2

lib/index.js

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

exports.ZodType = base_1.ZodType;
var ZodError_1 = require("./ZodError");
exports.ZodError = ZodError_1.ZodError;
var stringType = string_1.ZodString.create;

@@ -36,0 +38,0 @@ exports.string = stringType;

@@ -11,7 +11,6 @@ "use strict";

var z = __importStar(require("./types/base"));
var ZodError_1 = require("./ZodError");
function assertNever(x) {
throw new Error('Unexpected object: ' + x);
throw ZodError_1.ZodError.fromString('Unexpected object: ' + x);
}
// export class ZodError extends Error{
// }
exports.ZodParser = function (schemaDef) { return function (obj) {

@@ -22,9 +21,9 @@ var def = schemaDef;

if (typeof obj !== 'string')
throw new Error("Non-string type: " + typeof obj);
throw ZodError_1.ZodError.fromString("Non-string type: " + typeof obj);
return obj;
case z.ZodTypes.number:
if (typeof obj !== 'number')
throw new Error("Non-number type: " + typeof obj);
throw ZodError_1.ZodError.fromString("Non-number type: " + typeof obj);
if (Number.isNaN(obj)) {
throw new Error("Non-number type: NaN");
throw ZodError_1.ZodError.fromString("Non-number type: NaN");
}

@@ -34,18 +33,18 @@ return obj;

if (typeof obj !== 'boolean')
throw new Error("Non-boolean type: " + typeof obj);
throw ZodError_1.ZodError.fromString("Non-boolean type: " + typeof obj);
return obj;
case z.ZodTypes.undefined:
if (obj !== undefined)
throw new Error("Non-undefined type:Found: " + typeof obj);
throw ZodError_1.ZodError.fromString("Non-undefined type:Found: " + typeof obj);
return obj;
case z.ZodTypes.null:
if (obj !== null)
throw new Error("Non-null type: " + typeof obj);
throw ZodError_1.ZodError.fromString("Non-null type: " + typeof obj);
return obj;
case z.ZodTypes.array:
if (!Array.isArray(obj))
throw new Error("Non-array type: " + typeof obj);
var arrayErrors_1 = [];
throw ZodError_1.ZodError.fromString("Non-array type: " + typeof obj);
var arrayError_1 = ZodError_1.ZodError.create([]);
if (def.nonempty === true && obj.length === 0) {
throw new Error('Array cannot be empty');
throw ZodError_1.ZodError.fromString('Array cannot be empty');
}

@@ -58,9 +57,17 @@ var parsedArray = obj.map(function (item, i) {

catch (err) {
arrayErrors_1.push("[" + i + "]: " + err.message);
return null;
if (err instanceof ZodError_1.ZodError) {
arrayError_1.mergeChild(i, err);
// arrayErrors.push(`[${i}]: ${err.message}`);
return null;
}
else {
arrayError_1.mergeChild(i, ZodError_1.ZodError.fromString(err.message));
// arrayErrors.push(`[${i}]: ${err.message}`);
return null;
}
}
});
if (arrayErrors_1.length > 0) {
// throw new Error(arrayErrors.join('\n\n'));
throw new Error(arrayErrors_1.join('\n'));
if (!arrayError_1.empty) {
// throw ZodError.fromString(arrayErrors.join('\n\n'));
throw arrayError_1;
}

@@ -70,7 +77,7 @@ return parsedArray;

if (typeof obj !== 'object')
throw new Error("Non-object type: " + typeof obj);
throw ZodError_1.ZodError.fromString("Non-object type: " + typeof obj);
if (Array.isArray(obj))
throw new Error("Non-object type: array");
throw ZodError_1.ZodError.fromString("Non-object type: array");
var shape = def.shape;
var objectErrors = [];
var objectError = ZodError_1.ZodError.create([]);
for (var key in shape) {

@@ -81,7 +88,12 @@ try {

catch (err) {
objectErrors.push(key + ": " + err.message);
if (err instanceof ZodError_1.ZodError) {
objectError.mergeChild(key, err);
}
else {
objectError.mergeChild(key, ZodError_1.ZodError.fromString(err.message));
}
}
}
if (Object.keys(objectErrors).length > 0) {
throw new Error(objectErrors.join('\n'));
if (!objectError.empty) {
throw objectError; //ZodError.fromString(objectErrors.join('\n'));
}

@@ -98,3 +110,3 @@ return obj;

}
throw new Error("Type mismatch in union.\nReceived: " + JSON.stringify(obj, null, 2) + "\n\nExpected: " + def.options
throw ZodError_1.ZodError.fromString("Type mismatch in union.\nReceived: " + JSON.stringify(obj, null, 2) + "\n\nExpected: " + def.options
.map(function (x) { return x._def.t; })

@@ -119,9 +131,9 @@ .join(' OR '));

}
throw new Error(errors.join('\n'));
throw ZodError_1.ZodError.fromString(errors.join('\n'));
case z.ZodTypes.tuple:
if (!Array.isArray(obj)) {
throw new Error('Non-array type detected; invalid tuple.');
throw ZodError_1.ZodError.fromString('Non-array type detected; invalid tuple.');
}
if (def.items.length !== obj.length) {
throw new Error("Incorrect number of elements in tuple: expected " + def.items.length + ", got " + obj.length);
throw ZodError_1.ZodError.fromString("Incorrect number of elements in tuple: expected " + def.items.length + ", got " + obj.length);
}

@@ -131,3 +143,14 @@ var parsedTuple = [];

var item = obj[index];
parsedTuple.push(def.items[index].parse(item));
var itemParser = def.items[index];
try {
parsedTuple.push(itemParser.parse(item));
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
throw err.bubbleUp(index);
}
else {
throw ZodError_1.ZodError.fromString(err.message);
}
}
}

@@ -142,3 +165,3 @@ return parsedTuple;

return obj;
throw new Error(obj + " !== Literal<" + def.value + ">");
throw ZodError_1.ZodError.fromString(obj + " !== Literal<" + def.value + ">");
case z.ZodTypes.enum:

@@ -153,3 +176,3 @@ for (var _b = 0, _c = def.values; _b < _c.length; _b++) {

}
throw new Error("\"" + obj + "\" does not match any value in enum");
throw ZodError_1.ZodError.fromString("\"" + obj + "\" does not match any value in enum");
case z.ZodTypes.function:

@@ -156,0 +179,0 @@ return obj;

"use strict";
// import * as z from '.';
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var z = __importStar(require("."));
// import { ZodError } from './ZodError';
// const asdf = z.object({
// arrstring: z.array(z.object({ str: z.string() })),
// tupletest: z.tuple([z.string(), z.number()]),
// objarr: z.array(
// z.object({
// inner: z.boolean(),
// }),
// ),
// });
// z.array(z.string()).parse([1234, 567]);
var person = z.object({
name: z.object({
first: z.string(),
last: z.string(),
}),
age: z.number(),
address: z.array(z.string()),
});
try {
// asdf.parse({
// arrstring: [{ str: 'sdjfksd' }],
// tupletest: ['colin', 2.5],
// objarr: [
// {
// inner: true,
// },
// ],
// wrwerwr: 1234,
// });
person.parse({
name: { first: 'Dave', last: 42 },
age: 'threeve',
address: ['123 Maple Street', {}],
});
console.log('successful parse!');
}
catch (err) {
// console.log(JSON.stringify(err.errors, null, 2));
console.log(err.message);
}
// type Primitive = string | number | boolean | null | undefined;
// type Compound<U extends Primitive = Primitive> =
// | U
// | { [name: string]: Compound<U> }
// | []
// | [Compound<U>]
// | [Compound<U>, ...Compound<U>[]];
// type Json<U extends Primitive = Primitive> = U | Compound<U>;
// this function infers the EXACT type of the value passed into it
// and returns it as a const will full type information
// const infer1 = <T extends Json>(arg: T): T => {
// return arg;
// };
// const infer2 = <U extends Json<Primitive>>(arg: U): U extends Json<infer T> ? Json<T> : never => {
// return arg as Json<T>;
// };
// const inferLiteral = infer1;
// const test1 = inferLiteral('asdf'); // typeof test1 => "asdf"
// const test2 = inferLiteral(341); // typeof test2 => 341
// const test3 = inferLiteral(false); // typeof test3 => false
// const test4 = inferLiteral(null); // typeof test4 => null
// const test5 = inferLiteral(undefined); // typeof test5 => undefined
// const test6 = inferLiteral([]); // typeof test6 => []
// const test7 = inferLiteral(['asdf']); // typeof test6 => []
// const test8 = inferLiteral([{ asdf: 'qer' }]); // typeof test7 => [{ asdf: 'qer' }]
// const test9 = inferLiteral({
// asdf: [
// {
// asdf: 'qwer',
// asdfn: 12,
// asdfb: false,
// wer: {},
// lkulk: [false, 'asdf', 1234],
// empt: [],
// emptr: ['asdf'],
// },
// ],
// });
// const und = z.literal(undefined);

@@ -4,0 +91,0 @@ // const MyEnum = z.enum([z.literal('Hello'), z.literal('There'), z.literal('Bobby')]);

@@ -5,3 +5,4 @@ import * as z from './base';

import { ZodUnion } from './union';
declare type LiteralValue = string | number | boolean | undefined | null;
declare type Primitive = string | number | boolean | null | undefined;
declare type LiteralValue = Primitive;
export interface ZodLiteralDef<T extends LiteralValue = LiteralValue> extends z.ZodTypeDef {

@@ -15,4 +16,4 @@ t: z.ZodTypes.literal;

toJSON: () => ZodLiteralDef<T>;
static create: <T_1 extends LiteralValue>(value: T_1) => ZodLiteral<T_1>;
static create: <T_1 extends Primitive>(value: T_1) => ZodLiteral<T_1>;
}
export {};

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

declare type RequiredKeys<T extends z.ZodRawShape> = Exclude<keyof T, OptionalKeys<T>>;
declare type ObjectType<T extends z.ZodRawShape> = {
declare type ObjectIntersection<T extends z.ZodRawShape> = {
[k in OptionalKeys<T>]?: T[k]['_type'];

@@ -19,2 +19,6 @@ } & {

};
declare type Flatten<T extends z.ZodRawShape> = {
[k in keyof T]: T[k];
};
declare type ObjectType<T extends z.ZodRawShape> = Flatten<ObjectIntersection<T>>;
export declare class ZodObject<T extends z.ZodRawShape> extends z.ZodType<ObjectType<T>, // { [k in keyof T]: T[k]['_type'] },

@@ -21,0 +25,0 @@ ZodObjectDef<T>> {

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

@@ -5,0 +5,0 @@ "main": "./lib/index.js",

@@ -23,2 +23,3 @@ # Zod

- [Function schemas](#function-schemas)
- [Errors](#errors)
- [Comparison](#comparison)

@@ -103,3 +104,3 @@

The same method can be used to check a _lack_ of
You can use the same method to check for invalid data:

@@ -119,2 +120,4 @@ ```ts

To learn more about error handling with Zod, jump to [Errors](#errors).
## Type inference

@@ -174,5 +177,7 @@

dogsList.parse([]); // passes
```
// Non-empty lists
### Non-empty lists
```ts
const nonEmptyDogsList = z.array(dogSchema).nonempty();

@@ -437,2 +442,67 @@ nonEmptyDogsList.parse([]); // throws Error("Array cannot be empty")

## Errors
Zod includes a custom `Error` subclass called `ZodError`. All validation errors thrown by Zod are instances of `ZodError`.
A `ZodError` instance has an `errors` property of type
```ts
// ZodError#errors
{
path: (string | number)[],
message: string
}[]
```
This array represents all errors Zod encounters when attempting to parse a value.
```ts
const person = z.object({
name: {
first: z.string(),
last: z.string(),
},
age: z.number(),
address: z.array(z.string()),
});
try {
person.parse({
name: { first: 'Dave', last: 42 },
age: 'threeve',
address: ['123 Maple Street', {}],
});
} catch (err) {
if (err instanceof ZodError) {
console.log(JSON.stringify(err.errors));
/*
[
{
"path": [ "name", "last" ],
"message": "Non-string type: number"
},
{
"path": [ "age" ],
"message": "Non-number type: string"
},
{
"path": [ "address", 1 ],
"message": "Non-string type: object"
}
]
*/
// err.message returns a formatted error message
console.log(err.message);
/*
`name.last`: Non-string type: number
`age`: Non-number type: string
`address.1`: Non-string type: object
*/
} else {
// should never happen
}
}
```
# Comparison

@@ -442,2 +512,40 @@

The table below summarizes the feature differences. Below the table there are more involved discussions of certain alternatives, where necessary.
| Feature | [Zod](https://github.com/vriad) | [Joi](https://github.com/hapijs/joi) | [Yup](https://github.com/jquense/yup) | [io-ts](https://github.com/gcanti/io-ts) | [Runtypes](https://github.com/pelotom/runtypes) | [ow](https://github.com/sindresorhus/ow) | [class-validator](https://github.com/typestack/class-validator) |
| ---------------------------------------------------------------------------------------------------------------------- | :-----------------------------: | :----------------------------------: | :-----------------------------------: | :--------------------------------------: | :---------------------------------------------: | :--------------------------------------: | :-------------------------------------------------------------: |
| <abbr title='Any ability to extract a TypeScript type from a validator instance counts.'>Type inference</abbr> | 🟢 | 🔴 | 🟢 | 🟢 | 🟢 | 🟢 | 🟢 |
| <abbr title="Yup's inferred types are incorrect in certain cases, see discussion below.">Correct type inference</abbr> | 🟢 | 🔴 | 🔴 | 🟢 | 🟢 | 🟢 | 🟢 |
<abbr title="number, string, boolean, null, undefined">Primitive Types</abbr>
<abbr title="Includes any checks beyond 'Is this a string?', e.g. min/max length, isEmail, isURL, case checking, etc.">String Validation</abbr>
<abbr title="Includes any checks beyond 'Is this a number?', e.g. min/max, isPositive, integer vs float, etc.">Number Validation</abbr>
Dates
Primitive Literals
Object Literals
Tuple Literals
Objects
Arrays
Non-empty arrays
Unions
Optionals
Nullable
Enums
Enum Autocomplete
Intersections
Object Merging
Tuples
Recursive Types
Function Schemas
<abbr title="For instance, Yup allows custmo error messages with the syntax yup.number().min(5, 'Number must be more than 5!')">Validation Messages</abbr>
Immutable instances
Type Guards
Validity Checking
Casting
Default Values
Rich Errors
Branded
### Joi

@@ -444,0 +552,0 @@

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
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc