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.1.1 to 1.1.2

lib/src/types/record.d.ts

8

lib/src/index.d.ts

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

import { ZodTuple, ZodTupleDef } from './types/tuple';
import { ZodRecord, ZodRecordDef } from './types/record';
import { ZodFunction } from './types/function';

@@ -18,3 +19,3 @@ import { ZodLazy, ZodLazyDef } from './types/lazy';

import { ZodError } from './ZodError';
declare type ZodDef = ZodStringDef | ZodNumberDef | ZodBooleanDef | ZodUndefinedDef | ZodNullDef | ZodArrayDef | ZodObjectDef | ZodUnionDef | ZodIntersectionDef | ZodTupleDef | ZodLazyDef | ZodLiteralDef | ZodEnumDef;
declare type ZodDef = ZodStringDef | ZodNumberDef | ZodBooleanDef | ZodUndefinedDef | ZodNullDef | ZodArrayDef | ZodObjectDef | ZodUnionDef | ZodIntersectionDef | ZodTupleDef | ZodRecordDef | ZodLazyDef | ZodLiteralDef | ZodEnumDef;
declare const stringType: () => ZodString;

@@ -32,2 +33,3 @@ declare const numberType: () => ZodNumber;

declare const tupleType: <T extends [ZodType<any, import("./types/base").ZodTypeDef>, ...ZodType<any, import("./types/base").ZodTypeDef>[]] | []>(schemas: T) => ZodTuple<T>;
declare const recordType: <Value extends ZodType<any, import("./types/base").ZodTypeDef> = ZodType<any, import("./types/base").ZodTypeDef>>(valueType: Value) => ZodRecord<Value>;
declare const functionType: <T extends ZodTuple<any>, U extends ZodType<any, import("./types/base").ZodTypeDef>>(args: T, returns: U) => ZodFunction<T, U>;

@@ -40,4 +42,4 @@ declare const lazyType: <T extends ZodType<any, import("./types/base").ZodTypeDef>>(getter: () => T) => ZodLazy<T>;

declare const oboolean: () => ZodUnion<[ZodBoolean, ZodUndefined]>;
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, ZodDef, ZodError, };
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, recordType as record, 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, ZodRecord, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodType, ZodAny, ZodDef, ZodError, };
export { TypeOf, TypeOf as Infer };

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

exports.ZodTuple = tuple_1.ZodTuple;
var record_1 = require("./types/record");
exports.ZodRecord = record_1.ZodRecord;
var function_1 = require("./types/function");

@@ -57,2 +59,4 @@ exports.ZodFunction = function_1.ZodFunction;

exports.tuple = tupleType;
var recordType = record_1.ZodRecord.create;
exports.record = recordType;
var functionType = function_1.ZodFunction.create;

@@ -59,0 +63,0 @@ exports.function = functionType;

@@ -56,7 +56,7 @@ "use strict";

throw ZodError_1.ZodError.fromString("Non-undefined type:Found: " + typeof obj);
return obj;
return undefined;
case z.ZodTypes.null:
if (obj !== null)
throw ZodError_1.ZodError.fromString("Non-null type: " + typeof obj);
return obj;
return null;
case z.ZodTypes.array:

@@ -75,11 +75,3 @@ if (!Array.isArray(obj))

catch (err) {
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));
return null;
}
arrayError_1.mergeChild(i, err);
}

@@ -106,14 +98,11 @@ });

}
var parsedObject = {};
var objectError = ZodError_1.ZodError.create([]);
for (var key in shape) {
try {
def.shape[key].parse(obj[key], params);
var parsedEntry = def.shape[key].parse(obj[key], params);
parsedObject[key] = parsedEntry;
}
catch (err) {
if (err instanceof ZodError_1.ZodError) {
objectError.mergeChild(key, err);
}
else {
objectError.mergeChild(key, ZodError_1.ZodError.fromString(err.message));
}
objectError.mergeChild(key, err);
}

@@ -124,3 +113,3 @@ }

}
return obj;
return parsedObject;
case z.ZodTypes.union:

@@ -174,9 +163,3 @@ for (var _i = 0, _a = def.options; _i < _a.length; _i++) {

catch (err) {
if (err instanceof ZodError_1.ZodError) {
tupleError.mergeChild(index, err);
// throw err.bubbleUp(index);
}
else {
throw ZodError_1.ZodError.fromString(err.message);
}
tupleError.mergeChild(index, err);
}

@@ -206,2 +189,20 @@ }

// return obj;
case z.ZodTypes.record:
if (typeof obj !== 'object')
throw ZodError_1.ZodError.fromString("Non-object type: " + typeof obj);
if (Array.isArray(obj))
throw ZodError_1.ZodError.fromString("Non-object type: array");
var parsedRecord = {};
var recordError = new ZodError_1.ZodError();
for (var key in obj) {
try {
parsedRecord[key] = def.valueType.parse(obj[key]);
}
catch (err) {
recordError.mergeChild(key, err);
}
}
if (!recordError.empty)
throw recordError;
return parsedRecord;
default:

@@ -208,0 +209,0 @@ // function

"use strict";
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("."));
z.union([z.literal('Salmon'), z.literal('Tuna'), z.literal('Trout')]);
// const A = z
// .object({
// val: z.number(),
// // b: B,
// })
// .relations<A>({
// b: z.lazy((): any => B),
// });
// const B = z
// .object({
// val: z.number(),
// // a: z.lazy(() => A),
// })
// .relations<B>({
// a: z.lazy((): any => A),
// });
// const A = z.recursion<A>()(
// z.object({
// val: z.number(),
// b: z.lazy(() => B),
// }),
// );
// const B = z.recursion<B>()(
// z.object({
// val: z.number(),
// a: z.lazy(() => A),
// }),
// );
// const a: any = { val: 1 };
// const b: any = { val: 2 };
// a.b = b;
// b.a = a;
// const parsedA = A.parse(a);
// console.log(parsedA);
// const Test = z.object({
// f1: z.number(),
// f2: z.string().optional(),
// f3: z.string().nullable(),
// f4: z.array(z.object({ t: z.union([z.string(), z.boolean()]) })),
// f5: z.array(A),
// });
// type Test = typeof Test['_type'];
// type b = undefined extends string | undefined ? true : false;
// export const maskedA = Test.mask({
// f1: true,
// f2: true,
// f3: true,
// f4: true,
// f5: {
// val: true,
// },
// });
// // type u = typeof maskedA['f5'];
// const BaseCategory = z.object({
// name: z.string(),
// });
// interface Category extends z.Infer<typeof BaseCategory> {
// subcategories: Category[];
// }
// const Category: z.ZodType<Category> = BaseCategory.merge(
// z.object({
// subcategories: z.lazy(() => z.array(Category)),
// }),
// );
// .relations<Category>({
// subcategories: z.lazy(()=> z.array(Category))
// })
// const untypedCategory: any = {
// name: 'Category A',
// };
// // creating a cycle
// untypedCategory.subcategories = [untypedCategory];
// const parsedCategory = Category.parse(untypedCategory); // parses successfully
// parsedCategory.subcategories[0].subcategories[0].subcategories[0];
// // => parsedCategory;
// export const cat = z.object({
// name: z.string(),
// // subcategories: z.array(Category),
// });
// export type Cat = z.TypeOf<z.ZodObject<{ t: z.ZodString }>>;
// const dogSchema = z
// .object({
// name: z.string(),
// neutered: z.boolean(),
// })
// .merge(
// z.object({
// age: z.number(),
// }),
// )
// .nonstrict();
// const dog = dogSchema.parse({
// name: 'Spot',
// neutered: true,
// age: 12,
// color: 'brown',
// });
// console.log(JSON.stringify(dog, null, 2));
// type Dog = z.TypeOf<typeof dogSchema>;
// const spot: Dog = {
// name: 'Spot',
// age: 8,
// neutered: true,
// color: 'brown', //
// };
// 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> = 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
// export const inferLiteral = <U extends Primitive, T extends Json<U>>(arg: T): T => {
// return arg;
// };
// // 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]);
// // enum Key {
// // One,
// // Two
// // }
// // abstract class BaseClass{
// // abstract key: Key
// // }
// // class Class1 extends BaseClass {
// // readonly key = Key.One;
// // one: string = 'one :)';
// // }
// // class Class2 extends BaseClass {
// // readonly key = Key.Two;
// // two: string = 'two!';
// // }
// // type SomeSubclass = Class1 | Class2;
// // const run = ()=>{
// // const qwer: SomeSubclass = "asdf" as any;
// // switch (qwer.key) {
// // case Key.One:
// // // const asdf = qwer.one;
// // break;
// // case Key.Two:
// // break
// // default:
// // break
// // }
// // }
// // run()
// // const qwer = z.literal([{
// // asdf: Infinity,
// // qwer:1234
// // }]);
// const obj1 = z
// .object({
// str: z.string(),
// })
// type obj1 = z.TypeOf<typeof obj1>;
// const obj1lax = obj1.nonstrict();
// type obj1lax = z.TypeOf<typeof obj1lax>;
// type obj2p = (typeof obj1lax)['_params']
// const obj2 = z.object({ num: z.number() });
// const obj3 = obj1.merge(obj2).nonstrict();
// type obj3 = z.TypeOf<typeof obj3>;
// type obj3p = typeof obj3['_params'];
// // type obj3params = (typeof obj3)['_params'];
// obj1.parse({
// str: 'qwer',
// lkjf: 1234,
// });
// obj3.parse({
// str: 'asdf',
// num: 234,
// });
// // type dfgfg = z.Infer<typeof dfgfg>
// // const q: dfgfg = {
// // asdf: 'asdf',
// // qwer: 234,
// // };
// // console.log(qwer.);
// // const y:any = "asdf";
// // person.assert(y);
// 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);
// // const MyEnum = z.enum([z.literal('Hello'), z.literal('There'), z.literal('Bobby')]);
// // MyEnum.parse('Bobby');
// // type MyEnum = z.Infer<typeof MyEnum>;
// // const CellText = z.object({
// // kind: z.literal('text'),
// // body: z.string(),
// // });
// // const CellCode = z.object({
// // kind: z.literal('code'),
// // code: z.string(),
// // });
// // const Schema = z.array(
// // z.object({
// // category: z.string(),
// // cells: z.array(z.union([CellText, CellCode])).nonempty(),
// // }),
// // );
// // // const y: ['asdf', 'qwer'] = ['asdf', 'qwer'];
// // type U = ['asdf', 'qwer']
// // type Tail<Tuple extends any[]> = ((...args: Tuple) => any) extends (_: any, ..._1: infer Rest) => any
// // ? Rest extends any[] ? Rest : never
// // : never;
// // export type ArrayKeys = keyof any[];
// // export type Indices<T> = Exclude<keyof T, ArrayKeys>;
// // type UM<T extends string[]> = {[k in Indices<T>]: T[k] extends string ? z.ZodLiteral<T[k]> : never};
// // type UMU = UM<U>
// // type p = UMU[0]
// // type Ad = Tail<string[]>
// // type Mapper<T extends string[]> = {
// // empty: T,
// // single: T,
// // many: [T[0], ...ForceArray<Mapper<T>>],
// // never: never
// // }[T extends [] ? 'empty' : T extends [any] ? 'single' : T extends any[] ? 'many' : 'never'];
// // type ForceArray<T extends any[]> = T extends (infer U) ? U extends any[] ? U : never : never;
// // type MapRest<T extends string[]> = { 0: Mapper<Tail<T>> extends any[] ? Mapper<Tail<T>> : never, 1: never }[true ? 0 : 1]
// // type MU = MapRest<["wer", "asdf"]>
// // // if (!Schema.is(y)) {
// // // y[0].cells[0].kind; // => "text" | "code"
// // // throw new Error("adsf")
// // // }
//# sourceMappingURL=playground.js.map

@@ -14,2 +14,3 @@ import { ParseParams } from '../parser';

tuple = "tuple",
record = "record",
function = "function",

@@ -16,0 +17,0 @@ lazy = "lazy",

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

ZodTypes["tuple"] = "tuple";
ZodTypes["record"] = "record";
ZodTypes["function"] = "function";

@@ -20,0 +21,0 @@ ZodTypes["lazy"] = "lazy";

@@ -15,3 +15,3 @@ declare type ZodErrorArray = {

static fromString: (message: string) => ZodError;
mergeChild: (pathElement: string | number, child: ZodError) => void;
mergeChild: (pathElement: string | number, child: Error) => void;
bubbleUp: (pathElement: string | number) => ZodError;

@@ -18,0 +18,0 @@ addError: (path: string | number, message: string) => void;

@@ -23,3 +23,8 @@ "use strict";

_this.mergeChild = function (pathElement, child) {
_this.merge(child.bubbleUp(pathElement));
if (child instanceof ZodError) {
_this.merge(child.bubbleUp(pathElement));
}
else {
_this.merge(ZodError.fromString(child.message).bubbleUp(pathElement));
}
};

@@ -26,0 +31,0 @@ _this.bubbleUp = function (pathElement) {

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

@@ -48,3 +48,4 @@ "main": "./lib/src/index.js",

"lint": "tslint -p tsconfig.json",
"test": "jest --config jestconfig.json --coverage",
"test": "jest --config jestconfig.json --coverage && yarn run badge",
"badge": "make-coverage-badge --output-path ./coverage.svg",
"prepare": "npm run build",

@@ -56,2 +57,3 @@ "play": "nodemon -e ts -w . -x ts-node src/playground.ts"

"jest": "^25.1.0",
"make-coverage-badge": "^1.2.0",
"nodemon": "^2.0.2",

@@ -58,0 +60,0 @@ "prettier": "^1.19.1",

@@ -6,2 +6,9 @@ <p align="center">

[![License][license-image]][license-url]
[![npm](https://img.shields.io/npm/dw/jest-coverage-badges.svg)](https://www.npmjs.com/package/jest-coverage-badges)
![coverage](coverage/badge.svg)
[license-url]: https://opensource.org/licenses/MIT
[license-image]: https://img.shields.io/npm/l/make-coverage-badge.svg
Created and maintained by [@vriad](https://twitter.com/vriad).

@@ -8,0 +15,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