Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Standard Schema spec #3850

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions deno/lib/__tests__/standard-schema.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// @ts-ignore TS6133
import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts";
const test = Deno.test;
import { util } from "../helpers/util.ts";

import * as z from "../index.ts";

import type { v1 } from "../standard-schema.ts";

test("assignability", () => {
const _s1: v1.StandardSchema = z.string();
const _s2: v1.StandardSchema<string> = z.string();
const _s3: v1.StandardSchema<string, string> = z.string();
const _s4: v1.StandardSchema<unknown, string> = z.string();
[_s1, _s2, _s3, _s4];
});

test("type inference", () => {
const stringToNumber = z.string().transform((x) => x.length);
type input = v1.InferInput<typeof stringToNumber>;
util.assertEqual<input, string>(true);
type output = v1.InferOutput<typeof stringToNumber>;
util.assertEqual<output, number>(true);
});

test("valid parse", () => {
const schema = z.string();
const result = schema["~standard"]["validate"]("hello");
if (result instanceof Promise) {
throw new Error("Expected sync result");
}
expect(result.issues).toEqual(undefined);
if (result.issues) {
throw new Error("Expected no issues");
} else {
expect(result.value).toEqual("hello");
}
});

test("invalid parse", () => {
const schema = z.string();
const result = schema["~standard"]["validate"](1234);
if (result instanceof Promise) {
throw new Error("Expected sync result");
}
expect(result.issues).toBeDefined();
if (!result.issues) {
throw new Error("Expected issues");
}
expect(result.issues.length).toEqual(1);
expect(result.issues[0].path).toEqual([]);
});

test("valid parse async", async () => {
const schema = z.string().refine(async () => true);
const _result = schema["~standard"]["validate"]("hello");
if (_result instanceof Promise) {
const result = await _result;
expect(result.issues).toEqual(undefined);
if (result.issues) {
throw new Error("Expected no issues");
} else {
expect(result.value).toEqual("hello");
}
} else {
throw new Error("Expected async result");
}
});

test("invalid parse async", async () => {
const schema = z.string().refine(async () => false);
const _result = schema["~standard"]["validate"]("hello");
if (_result instanceof Promise) {
const result = await _result;
expect(result.issues).toBeDefined();
if (!result.issues) {
throw new Error("Expected issues");
}
expect(result.issues.length).toEqual(1);
expect(result.issues[0].path).toEqual([]);
} else {
throw new Error("Expected async result");
}
});
113 changes: 113 additions & 0 deletions deno/lib/standard-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
declare namespace v1 {
/**
* The Standard Schema interface.
*/
interface StandardSchema<Input = unknown, Output = Input> {
/**
* The Standard Schema properties.
*/
readonly "~standard": StandardSchemaProps<Input, Output>;
}
/**
* The Standard Schema properties interface.
*/
interface StandardSchemaProps<Input = unknown, Output = Input> {
/**
* The version number of the standard.
*/
readonly version: 1;
/**
* The vendor name of the schema library.
*/
readonly vendor: string;
/**
* Validates unknown input values.
*/
readonly validate: (
value: unknown
) => StandardResult<Output> | Promise<StandardResult<Output>>;
/**
* Inferred types associated with the schema.
*/
readonly types?: StandardTypes<Input, Output> | undefined;
}
/**
* The result interface of the validate function.
*/
type StandardResult<Output> =
| StandardSuccessResult<Output>
| StandardFailureResult;
/**
* The result interface if validation succeeds.
*/
interface StandardSuccessResult<Output> {
/**
* The typed output value.
*/
readonly value: Output;
/**
* The non-existent issues.
*/
readonly issues?: undefined;
}
/**
* The result interface if validation fails.
*/
interface StandardFailureResult {
/**
* The issues of failed validation.
*/
readonly issues: ReadonlyArray<StandardIssue>;
}
/**
* The issue interface of the failure output.
*/
interface StandardIssue {
/**
* The error message of the issue.
*/
readonly message: string;
/**
* The path of the issue, if any.
*/
readonly path?:
| ReadonlyArray<PropertyKey | StandardPathSegment>
| undefined;
}
/**
* The path segment interface of the issue.
*/
interface StandardPathSegment {
/**
* The key representing a path segment.
*/
readonly key: PropertyKey;
}
/**
* The base types interface of Standard Schema.
*/
interface StandardTypes<Input, Output> {
/**
* The input type of the schema.
*/
readonly input: Input;
/**
* The output type of the schema.
*/
readonly output: Output;
}
/**
* Infers the input type of a Standard Schema.
*/
type InferInput<Schema extends StandardSchema> = NonNullable<
Schema["~standard"]["types"]
>["input"];
/**
* Infers the output type of a Standard Schema.
*/
type InferOutput<Schema extends StandardSchema> = NonNullable<
Schema["~standard"]["types"]
>["output"];
}

export type { v1 };
58 changes: 57 additions & 1 deletion deno/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
import { partialUtil } from "./helpers/partialUtil.ts";
import { Primitive } from "./helpers/typeAliases.ts";
import { getParsedType, objectUtil, util, ZodParsedType } from "./helpers/util.ts";
import { v1 } from "./standard-schema.ts";
import {
IssueData,
StringValidation,
Expand Down Expand Up @@ -169,7 +170,8 @@ export abstract class ZodType<
Output = any,
Def extends ZodTypeDef = ZodTypeDef,
Input = Output
> {
> implements v1.StandardSchema<Input, Output>
{
readonly _type!: Output;
readonly _output!: Output;
readonly _input!: Input;
Expand All @@ -179,6 +181,8 @@ export abstract class ZodType<
return this._def.description;
}

"~standard": v1.StandardSchemaProps<Input, Output>;

abstract _parse(input: ParseInput): ParseReturnType<Output>;

_getType(input: ParseInput): string {
Expand Down Expand Up @@ -262,6 +266,53 @@ export abstract class ZodType<
return handleResult(ctx, result);
}

"~validate"(
data: unknown
): v1.StandardResult<Output> | Promise<v1.StandardResult<Output>> {
const ctx: ParseContext = {
common: {
issues: [],
async: !!(this["~standard"] as any).async,
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data),
};

if (!(this["~standard"] as any).async) {
try {
const result = this._parseSync({ data, path: [], parent: ctx });
return isValid(result)
? {
value: result.value,
}
: {
issues: ctx.common.issues,
};
} catch (err: any) {
if ((err as Error)?.message?.toLowerCase()?.includes("encountered")) {
(this["~standard"] as any).async = true;
}
(ctx as any).common = {
issues: [],
async: true,
};
}
}

return this._parseAsync({ data, path: [], parent: ctx }).then((result) =>
isValid(result)
? {
value: result.value,
}
: {
issues: ctx.common.issues,
}
);
}

async parseAsync(
data: unknown,
params?: Partial<ParseParams>
Expand Down Expand Up @@ -422,6 +473,11 @@ export abstract class ZodType<
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data) => this["~validate"](data),
};
}

optional(): ZodOptional<this> {
Expand Down
22 changes: 18 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,28 @@
"url": "https://github.com/colinhacks/zod/issues"
},
"description": "TypeScript-first schema declaration and validation library with static type inference",
"files": ["/lib", "/index.d.ts"],
"files": [
"/lib",
"/index.d.ts"
],
"funding": "https://github.com/sponsors/colinhacks",
"homepage": "https://zod.dev",
"keywords": ["typescript", "schema", "validation", "type", "inference"],
"keywords": [
"typescript",
"schema",
"validation",
"type",
"inference"
],
"license": "MIT",
"lint-staged": {
"src/*.ts": ["eslint --cache --fix", "prettier --ignore-unknown --write"],
"*.md": ["prettier --ignore-unknown --write"]
"src/*.ts": [
"eslint --cache --fix",
"prettier --ignore-unknown --write"
],
"*.md": [
"prettier --ignore-unknown --write"
]
},
"scripts": {
"prettier:check": "prettier --check src/**/*.ts deno/lib/**/*.ts *.md --no-error-on-unmatched-pattern",
Expand Down
13 changes: 13 additions & 0 deletions playground.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
import { z } from "./src";

z;

const schema = z
.string()
.transform((input) => input || undefined)
.optional()
.default("default");

type Input = z.input<typeof schema>; // string | undefined
type Output = z.output<typeof schema>; // string

const result = schema.safeParse("");

console.log(result); // { success: true, data: undefined }
Loading