From 761ecc623bf316e4c1d63eb2d89057d7d6cb86e9 Mon Sep 17 00:00:00 2001 From: Charles Catta <charles.catta@botpress.com> Date: Wed, 3 Apr 2024 15:45:37 -0400 Subject: [PATCH 1/3] Remove Deno --- .github/workflows/release.yml | 46 +- .github/workflows/test.yml | 28 - .gitignore | 1 - .husky/pre-commit | 2 - deno-build.mjs | 99 - deno/lib/README.md | 3139 ---------- deno/lib/ZodError.ts | 366 -- deno/lib/__tests__/Mocker.ts | 54 - deno/lib/__tests__/all-errors.test.ts | 177 - deno/lib/__tests__/anyunknown.test.ts | 29 - deno/lib/__tests__/array.test.ts | 72 - deno/lib/__tests__/async-parsing.test.ts | 392 -- deno/lib/__tests__/async-refinements.test.ts | 47 - deno/lib/__tests__/base.test.ts | 30 - deno/lib/__tests__/bigint.test.ts | 58 - deno/lib/__tests__/branded.test.ts | 62 - deno/lib/__tests__/catch.test.ts | 229 - deno/lib/__tests__/coerce.test.ts | 156 - deno/lib/__tests__/complex.test.ts | 22 - deno/lib/__tests__/crazySchema.ts | 42 - deno/lib/__tests__/custom.test.ts | 19 - deno/lib/__tests__/date.test.ts | 35 - deno/lib/__tests__/deepmasking.test.ts | 187 - deno/lib/__tests__/default.test.ts | 119 - deno/lib/__tests__/description.test.ts | 28 - .../__tests__/discriminated-unions.test.ts | 310 - deno/lib/__tests__/enum.test.ts | 85 - deno/lib/__tests__/error.test.ts | 542 -- deno/lib/__tests__/firstparty.test.ts | 90 - .../__tests__/firstpartyschematypes.test.ts | 25 - deno/lib/__tests__/function.test.ts | 272 - deno/lib/__tests__/generics.test.ts | 41 - deno/lib/__tests__/instanceof.test.ts | 42 - deno/lib/__tests__/intersection.test.ts | 121 - deno/lib/__tests__/literal.test.ts | 37 - deno/lib/__tests__/map.test.ts | 111 - deno/lib/__tests__/masking.test.ts | 23 - deno/lib/__tests__/mocker.test.ts | 20 - deno/lib/__tests__/nan.test.ts | 22 - deno/lib/__tests__/nativeEnum.test.ts | 88 - deno/lib/__tests__/nullable.test.ts | 43 - deno/lib/__tests__/number.test.ts | 177 - .../lib/__tests__/object-augmentation.test.ts | 30 - deno/lib/__tests__/object.test.ts | 473 -- deno/lib/__tests__/optional.test.ts | 43 - deno/lib/__tests__/parseUtil.test.ts | 29 - deno/lib/__tests__/parser.test.ts | 48 - deno/lib/__tests__/partials.test.ts | 253 - deno/lib/__tests__/pickomit.test.ts | 96 - deno/lib/__tests__/pipeline.test.ts | 30 - deno/lib/__tests__/preprocess.test.ts | 192 - deno/lib/__tests__/primitive.test.ts | 455 -- deno/lib/__tests__/promise.test.ts | 95 - deno/lib/__tests__/readonly.test.ts | 205 - deno/lib/__tests__/record.test.ts | 173 - deno/lib/__tests__/recursive.test.ts | 198 - deno/lib/__tests__/refine.test.ts | 307 - deno/lib/__tests__/safeparse.test.ts | 28 - deno/lib/__tests__/set.test.ts | 143 - deno/lib/__tests__/string.test.ts | 512 -- deno/lib/__tests__/template-literal.test.ts | 699 --- deno/lib/__tests__/transformer.test.ts | 234 - deno/lib/__tests__/tuple.test.ts | 101 - deno/lib/__tests__/unions.test.ts | 65 - deno/lib/__tests__/validations.test.ts | 162 - deno/lib/__tests__/void.test.ts | 16 - deno/lib/benchmarks/discriminatedUnion.ts | 80 - deno/lib/benchmarks/index.ts | 45 - deno/lib/benchmarks/object.ts | 69 - deno/lib/benchmarks/primitives.ts | 138 - deno/lib/benchmarks/realworld.ts | 63 - deno/lib/benchmarks/string.ts | 55 - deno/lib/benchmarks/union.ts | 80 - deno/lib/errors.ts | 13 - deno/lib/external.ts | 6 - deno/lib/helpers/enumUtil.ts | 19 - deno/lib/helpers/errorUtil.ts | 7 - deno/lib/helpers/parseUtil.ts | 181 - deno/lib/helpers/partialUtil.ts | 78 - deno/lib/helpers/typeAliases.ts | 9 - deno/lib/helpers/util.ts | 221 - deno/lib/index.ts | 4 - deno/lib/locales/en.ts | 150 - deno/lib/mod.ts | 2 - deno/lib/types.ts | 5572 ----------------- package.json | 4 +- 86 files changed, 2 insertions(+), 18869 deletions(-) delete mode 100644 deno-build.mjs delete mode 100644 deno/lib/README.md delete mode 100644 deno/lib/ZodError.ts delete mode 100644 deno/lib/__tests__/Mocker.ts delete mode 100644 deno/lib/__tests__/all-errors.test.ts delete mode 100644 deno/lib/__tests__/anyunknown.test.ts delete mode 100644 deno/lib/__tests__/array.test.ts delete mode 100644 deno/lib/__tests__/async-parsing.test.ts delete mode 100644 deno/lib/__tests__/async-refinements.test.ts delete mode 100644 deno/lib/__tests__/base.test.ts delete mode 100644 deno/lib/__tests__/bigint.test.ts delete mode 100644 deno/lib/__tests__/branded.test.ts delete mode 100644 deno/lib/__tests__/catch.test.ts delete mode 100644 deno/lib/__tests__/coerce.test.ts delete mode 100644 deno/lib/__tests__/complex.test.ts delete mode 100644 deno/lib/__tests__/crazySchema.ts delete mode 100644 deno/lib/__tests__/custom.test.ts delete mode 100644 deno/lib/__tests__/date.test.ts delete mode 100644 deno/lib/__tests__/deepmasking.test.ts delete mode 100644 deno/lib/__tests__/default.test.ts delete mode 100644 deno/lib/__tests__/description.test.ts delete mode 100644 deno/lib/__tests__/discriminated-unions.test.ts delete mode 100644 deno/lib/__tests__/enum.test.ts delete mode 100644 deno/lib/__tests__/error.test.ts delete mode 100644 deno/lib/__tests__/firstparty.test.ts delete mode 100644 deno/lib/__tests__/firstpartyschematypes.test.ts delete mode 100644 deno/lib/__tests__/function.test.ts delete mode 100644 deno/lib/__tests__/generics.test.ts delete mode 100644 deno/lib/__tests__/instanceof.test.ts delete mode 100644 deno/lib/__tests__/intersection.test.ts delete mode 100644 deno/lib/__tests__/literal.test.ts delete mode 100644 deno/lib/__tests__/map.test.ts delete mode 100644 deno/lib/__tests__/masking.test.ts delete mode 100644 deno/lib/__tests__/mocker.test.ts delete mode 100644 deno/lib/__tests__/nan.test.ts delete mode 100644 deno/lib/__tests__/nativeEnum.test.ts delete mode 100644 deno/lib/__tests__/nullable.test.ts delete mode 100644 deno/lib/__tests__/number.test.ts delete mode 100644 deno/lib/__tests__/object-augmentation.test.ts delete mode 100644 deno/lib/__tests__/object.test.ts delete mode 100644 deno/lib/__tests__/optional.test.ts delete mode 100644 deno/lib/__tests__/parseUtil.test.ts delete mode 100644 deno/lib/__tests__/parser.test.ts delete mode 100644 deno/lib/__tests__/partials.test.ts delete mode 100644 deno/lib/__tests__/pickomit.test.ts delete mode 100644 deno/lib/__tests__/pipeline.test.ts delete mode 100644 deno/lib/__tests__/preprocess.test.ts delete mode 100644 deno/lib/__tests__/primitive.test.ts delete mode 100644 deno/lib/__tests__/promise.test.ts delete mode 100644 deno/lib/__tests__/readonly.test.ts delete mode 100644 deno/lib/__tests__/record.test.ts delete mode 100644 deno/lib/__tests__/recursive.test.ts delete mode 100644 deno/lib/__tests__/refine.test.ts delete mode 100644 deno/lib/__tests__/safeparse.test.ts delete mode 100644 deno/lib/__tests__/set.test.ts delete mode 100644 deno/lib/__tests__/string.test.ts delete mode 100644 deno/lib/__tests__/template-literal.test.ts delete mode 100644 deno/lib/__tests__/transformer.test.ts delete mode 100644 deno/lib/__tests__/tuple.test.ts delete mode 100644 deno/lib/__tests__/unions.test.ts delete mode 100644 deno/lib/__tests__/validations.test.ts delete mode 100644 deno/lib/__tests__/void.test.ts delete mode 100644 deno/lib/benchmarks/discriminatedUnion.ts delete mode 100644 deno/lib/benchmarks/index.ts delete mode 100644 deno/lib/benchmarks/object.ts delete mode 100644 deno/lib/benchmarks/primitives.ts delete mode 100644 deno/lib/benchmarks/realworld.ts delete mode 100644 deno/lib/benchmarks/string.ts delete mode 100644 deno/lib/benchmarks/union.ts delete mode 100644 deno/lib/errors.ts delete mode 100644 deno/lib/external.ts delete mode 100644 deno/lib/helpers/enumUtil.ts delete mode 100644 deno/lib/helpers/errorUtil.ts delete mode 100644 deno/lib/helpers/parseUtil.ts delete mode 100644 deno/lib/helpers/partialUtil.ts delete mode 100644 deno/lib/helpers/typeAliases.ts delete mode 100644 deno/lib/helpers/util.ts delete mode 100644 deno/lib/index.ts delete mode 100644 deno/lib/locales/en.ts delete mode 100644 deno/lib/mod.ts delete mode 100644 deno/lib/types.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b0cb37e6e..a85caaeee 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,24 +21,6 @@ jobs: uses: actions/setup-node@v1 with: node-version: 16 - - - name: Checkout zod-deno - uses: actions/checkout@v2 - with: - token: ${{ secrets.ZOD_BOT_TOKEN }} - repository: colinhacks/zod-deno - path: deno/lib - - - name: Install dependencies - run: | - yarn install - - - name: Build - run: | - yarn clean - yarn build - cp logo.svg deno/lib - cp README.md deno/lib - id: publish name: Publish to NPM @@ -58,16 +40,6 @@ jobs: echo "Version in package.json has not changed. Skipping." exit 0 - - name: Push to Deno - if: steps.publish.outputs.type != 'none' - working-directory: deno/lib - run: | - git config --global user.email "zodbot@colinhacks.com" - git config --global user.name "Zod Bot" - git add . -f - git commit -m "Build from zod $GITHUB_SHA" --allow-empty - git push - - name: Configure changelog if: steps.publish.outputs.type != 'none' run: | @@ -100,20 +72,4 @@ jobs: commitish: ${{ github.ref }} body: ${{steps.github_release.outputs.changelog}} draft: false - prerelease: false - - - name: Create Deno release - if: steps.publish.outputs.type != 'none' - id: create_deno_release - uses: actions/create-release@latest - env: - GITHUB_TOKEN: ${{ secrets.ZOD_BOT_TOKEN }} - with: - tag_name: v${{ steps.publish.outputs.version }} - release_name: v${{ steps.publish.outputs.version }} - commitish: refs/heads/main - body: ${{steps.github_release.outputs.changelog}} - draft: false - prerelease: false - owner: colinhacks - repo: zod-deno + prerelease: false \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1a36dbd51..c420239b8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -26,34 +26,6 @@ jobs: - run: yarn build - run: yarn test - test-deno: - runs-on: ubuntu-latest - strategy: - matrix: - deno: ["v1.x"] - name: Test with Deno ${{ matrix.deno }} - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-node@v1 - with: - node-version: 16 - - uses: denolib/setup-deno@v2 - with: - deno-version: ${{ matrix.deno }} - - run: yarn install - - run: yarn build:deno - - run: deno --version - - run: deno test - working-directory: ./deno/lib - - run: deno run ./index.ts - working-directory: ./deno/lib - - run: deno run ./mod.ts - working-directory: ./deno/lib - - run: | - deno bundle ./mod.ts ./bundle.js - deno run ./bundle.js - working-directory: ./deno/lib - lint: runs-on: ubuntu-latest strategy: diff --git a/.gitignore b/.gitignore index 943316dea..1aeb4999b 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,6 @@ coverage .idea *.log playground.ts -deno/lib/playground.ts .eslintcache workspace.code-workspace .netlify diff --git a/.husky/pre-commit b/.husky/pre-commit index fb5a5ac13..36af21989 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -2,5 +2,3 @@ . "$(dirname "$0")/_/husky.sh" npx lint-staged -yarn build:deno -git add deno diff --git a/deno-build.mjs b/deno-build.mjs deleted file mode 100644 index ca10670a8..000000000 --- a/deno-build.mjs +++ /dev/null @@ -1,99 +0,0 @@ -// This script expects to be run via `yarn build:deno`. -// -// Although this script generates code for use in Deno, this script itself is -// written for Node so that contributors do not need to install Deno to build. -// -// @ts-check - -import { - mkdirSync, - readdirSync, - readFileSync, - statSync, - writeFileSync, -} from "fs"; -import { dirname } from "path"; - -// Node's path.join() normalize explicitly-relative paths like "./index.ts" to -// paths like "index.ts" which don't work as relative ES imports, so we do this. -const join = (/** @type string[] */ ...parts) => - parts.join("/").replace(/\/\//g, "/"); - -const projectRoot = process.cwd(); -const nodeSrcRoot = join(projectRoot, "src"); -const denoLibRoot = join(projectRoot, "deno", "lib"); - -const skipList = [ - join(nodeSrcRoot, "__tests__", "object-in-es5-env.test.ts"), - join(nodeSrcRoot, "__tests__", "language-server.test.ts"), - join(nodeSrcRoot, "__tests__", "language-server.source.ts"), -]; -const walkAndBuild = (/** @type string */ dir) => { - for (const entry of readdirSync(join(nodeSrcRoot, dir), { - withFileTypes: true, - encoding: "utf-8", - })) { - if (entry.isDirectory()) { - walkAndBuild(join(dir, entry.name)); - } else if (entry.isFile() && entry.name.endsWith(".ts")) { - const nodePath = join(nodeSrcRoot, dir, entry.name); - const denoPath = join(denoLibRoot, dir, entry.name); - - if (skipList.includes(nodePath)) { - // console.log(`Skipping ${nodePath}`); - continue; - } - - const nodeSource = readFileSync(nodePath, { encoding: "utf-8" }); - - const denoSource = nodeSource.replace( - /^(?:import|export)[\s\S]*?from\s*['"]([^'"]*)['"];$/gm, - (line, target) => { - if (target === "@jest/globals") { - return `import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts";\nconst test = Deno.test;`; - } - - const targetNodePath = join(dirname(nodePath), target); - const targetNodePathIfFile = targetNodePath + ".ts"; - const targetNodePathIfDir = join(targetNodePath, "index.ts"); - - try { - if (statSync(targetNodePathIfFile)?.isFile()) { - return line.replace(target, target + ".ts"); - } - } catch (error) { - if (error?.code !== "ENOENT") { - throw error; - } - } - - try { - if (statSync(targetNodePathIfDir)?.isFile()) { - return line.replace(target, join(target, "index.ts")); - } - } catch (error) { - if (error?.code !== "ENOENT") { - throw error; - } - } - - // console.warn(`Skipping non-resolvable import:\n ${line}`); - return line; - } - ); - - mkdirSync(dirname(denoPath), { recursive: true }); - writeFileSync(denoPath, denoSource, { encoding: "utf-8" }); - } - } -}; - -walkAndBuild(""); - -writeFileSync( - join(denoLibRoot, "mod.ts"), - `export * from "./index.ts";\nexport { default as default } from "./index.ts";\n`, - { - encoding: "utf-8", - } -); diff --git a/deno/lib/README.md b/deno/lib/README.md deleted file mode 100644 index d892d799c..000000000 --- a/deno/lib/README.md +++ /dev/null @@ -1,3139 +0,0 @@ -<p align="center"> - <img src="logo.svg" width="200px" align="center" alt="Zod logo" /> - <h1 align="center">Zod</h1> - <p align="center"> - ✨ <a href="https://zod.dev">https://zod.dev</a> ✨ - <br/> - TypeScript-first schema validation with static type inference - </p> -</p> -<br/> -<p align="center"> -<a href="https://github.com/colinhacks/zod/actions?query=branch%3Amaster"><img src="https://github.com/colinhacks/zod/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Zod CI status" /></a> -<a href="https://twitter.com/colinhacks" rel="nofollow"><img src="https://img.shields.io/badge/created%20by-@colinhacks-4BBAAB.svg" alt="Created by Colin McDonnell"></a> -<a href="https://opensource.org/licenses/MIT" rel="nofollow"><img src="https://img.shields.io/github/license/colinhacks/zod" alt="License"></a> -<a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/npm/dw/zod.svg" alt="npm"></a> -<a href="https://www.npmjs.com/package/zod" rel="nofollow"><img src="https://img.shields.io/github/stars/colinhacks/zod" alt="stars"></a> -<a href="https://discord.gg/KaSRdyX2vc" rel="nofollow"><img src="https://img.shields.io/discord/893487829802418277?label=Discord&logo=discord&logoColor=white" alt="discord server"></a> -</p> - -<div align="center"> - <a href="https://zod.dev">Documentation</a> - <span> • </span> - <a href="https://discord.gg/RcG33DQJdf">Discord</a> - <span> • </span> - <a href="https://www.npmjs.com/package/zod">npm</a> - <span> • </span> - <a href="https://deno.land/x/zod">deno</a> - <span> • </span> - <a href="https://github.com/colinhacks/zod/issues/new">Issues</a> - <span> • </span> - <a href="https://twitter.com/colinhacks">@colinhacks</a> - <span> • </span> - <a href="https://trpc.io">tRPC</a> - <br /> -</div> - -<br/> -<br/> - -> These docs have been translated into [Chinese](./README_ZH.md). - -## Table of contents - -<!-- The full documentation is available both on the [official documentation site](https://zod.js.org/) (recommended) and in `README.md`. - -#### Go to [zod.js.org](https://zod.js.org) >> --> - -- [Table of contents](#table-of-contents) -- [Introduction](#introduction) - - [Sponsors](#sponsors) - - [Gold](#gold) - - [Silver](#silver) - - [Bronze](#bronze) - - [Ecosystem](#ecosystem) - - [Resources](#resources) - - [API libraries](#api-libraries) - - [Form integrations](#form-integrations) - - [Zod to X](#zod-to-x) - - [X to Zod](#x-to-zod) - - [Mocking](#mocking) - - [Powered by Zod](#powered-by-zod) - - [Utilities for Zod](#utilities-for-zod) -- [Installation](#installation) - - [Requirements](#requirements) - - [From `npm` (Node/Bun)](#from-npm-nodebun) - - [From `deno.land/x` (Deno)](#from-denolandx-deno) -- [Basic usage](#basic-usage) -- [Primitives](#primitives) -- [Coercion for primitives](#coercion-for-primitives) -- [Literals](#literals) -- [Strings](#strings) - - [ISO datetimes](#iso-datetimes) - - [IP addresses](#ip-addresses) -- [Numbers](#numbers) -- [BigInts](#bigints) -- [NaNs](#nans) -- [Booleans](#booleans) -- [Dates](#dates) -- [Zod enums](#zod-enums) -- [Native enums](#native-enums) -- [Optionals](#optionals) -- [Nullables](#nullables) -- [Objects](#objects) - - [`.shape`](#shape) - - [`.keyof`](#keyof) - - [`.extend`](#extend) - - [`.merge`](#merge) - - [`.pick/.omit`](#pickomit) - - [`.partial`](#partial) - - [`.deepPartial`](#deeppartial) - - [`.required`](#required) - - [`.passthrough`](#passthrough) - - [`.strict`](#strict) - - [`.strip`](#strip) - - [`.catchall`](#catchall) -- [Arrays](#arrays) - - [`.element`](#element) - - [`.nonempty`](#nonempty) - - [`.min/.max/.length`](#minmaxlength) -- [Tuples](#tuples) -- [Unions](#unions) -- [Discriminated unions](#discriminated-unions) -- [Records](#records) - - [Record key type](#record-key-type) -- [Maps](#maps) -- [Sets](#sets) -- [Intersections](#intersections) -- [Recursive types](#recursive-types) - - [ZodType with ZodEffects](#zodtype-with-zodeffects) - - [JSON type](#json-type) - - [Cyclical objects](#cyclical-objects) -- [Promises](#promises) -- [Instanceof](#instanceof) -- [Functions](#functions) -- [Template Literals](#template-literals) -- [Preprocess](#preprocess) -- [Custom schemas](#custom-schemas) -- [Schema methods](#schema-methods) - - [`.parse`](#parse) - - [`.parseAsync`](#parseasync) - - [`.safeParse`](#safeparse) - - [`.safeParseAsync`](#safeparseasync) - - [`.refine`](#refine) - - [Arguments](#arguments) - - [Customize error path](#customize-error-path) - - [Asynchronous refinements](#asynchronous-refinements) - - [Relationship to transforms](#relationship-to-transforms) - - [`.superRefine`](#superrefine) - - [Abort early](#abort-early) - - [Type refinements](#type-refinements) - - [`.transform`](#transform) - - [Chaining order](#chaining-order) - - [Validating during transform](#validating-during-transform) - - [Relationship to refinements](#relationship-to-refinements) - - [Async transforms](#async-transforms) - - [`.default`](#default) - - [`.describe`](#describe) - - [`.catch`](#catch) - - [`.optional`](#optional) - - [`.nullable`](#nullable) - - [`.nullish`](#nullish) - - [`.array`](#array) - - [`.promise`](#promise) - - [`.or`](#or) - - [`.and`](#and) - - [`.brand`](#brand) - - [`.readonly`](#readonly) - - [`.pipe`](#pipe) - - [You can use `.pipe()` to fix common issues with `z.coerce`.](#you-can-use-pipe-to-fix-common-issues-with-zcoerce) -- [Guides and concepts](#guides-and-concepts) - - [Type inference](#type-inference) - - [Writing generic functions](#writing-generic-functions) - - [Constraining allowable inputs](#constraining-allowable-inputs) - - [Error handling](#error-handling) - - [Error formatting](#error-formatting) -- [Comparison](#comparison) - - [Joi](#joi) - - [Yup](#yup) - - [io-ts](#io-ts) - - [Runtypes](#runtypes) - - [Ow](#ow) -- [Changelog](#changelog) - -## Introduction - -Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple `string` to a complex nested object. - -Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator _once_ and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into complex data structures. - -Some other great aspects: - -- Zero dependencies -- Works in Node.js and all modern browsers -- Tiny: 8kb minified + zipped -- Immutable: methods (e.g. `.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/) -- Works with plain JavaScript too! You don't need to use TypeScript. - -### Sponsors - -Sponsorship at any level is appreciated and encouraged. For individual developers, consider the [Cup of Coffee tier](https://github.com/sponsors/colinhacks). If you built a paid product using Zod, consider one of the [podium tiers](https://github.com/sponsors/colinhacks). - -#### Gold - -<table> - <tr> - <td align="center"> - <a href="https://speakeasyapi.dev/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/91446104?s=200&v=4" width="200px;" alt="Speakeasy API" /> - </a> - <br /> - <b>Speakeasy</b> - <br /> - <a href="https://speakeasyapi.dev/" target="_blank">speakeasyapi.dev</a> - <br /> - <p width="200px">SDKs, Terraform, Docs.<br/>Your API made enterprise-ready</p> - </td> - <td align="center"> - <a href="https://deletype.com/" target="_blank"> - <img src="https://avatars0.githubusercontent.com/u/15068039?s=200&v=4" width="200px;" alt="Deletype logo" /> - </a> - <br /> - <b>Deletype</b> - <br /> - <a href="https://deletype.com" target="_blank">deletype.com</a> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://trigger.dev/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/95297378?s=200&v=4" width="200px;" alt="Trigger.dev logo" /> - </a> - <br /> - <b>Trigger.dev</b> - <br /> - <a href="https://trigger.dev" target="_blank">trigger.dev</a> - <br/> - <p>Effortless automation for developers</p> - </td> - <td align="center"> - <a href="https://transloadit.com/?utm_source=zod&utm_medium=referral&utm_campaign=sponsorship&utm_content=github" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/125754?s=200&v=4" width="200px;" alt="Transloadit logo" /> - </a> - <br /> - <b>Transloadit</b> - <br /> - <a href="https://transloadit.com/?utm_source=zod&utm_medium=referral&utm_campaign=sponsorship&utm_content=github" target="_blank">transloadit.com</a> - <br/> - <p>Simple file processing for developers</p> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://infisical.com" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/107880645?s=200&v=4" width="200px;" alt="Infisical logo" /> - </a> - <br /> - <b>Infisical</b> - <br /> - <a href="https://infisical.com" target="_blank">infisical.com</a> - <br/> - <p>Open-source platform for secret<br/>management: sync secrets across your<br/>team/infrastructure and prevent secret leaks</p> - </td> - <td align="center"> - <a href="https://whop.com/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/91036480?s=200&v=4" width="200px;" alt="Whop logo" /> - </a> - <br /> - <b>Whop</b> - <br /> - <a href="https://whop.com/" target="_blank">whop.com</a> - <br /> - <p width="200px">A marketplace for really cool internet products</p> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://cryptojobslist.com/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/36402888?s=200&v=4" width="200px;" alt="CryptoJobsList logo" /> - </a> - <br /> - <b>CryptoJobsList</b> - <br /> - <a href="https://cryptojobslist.com/" target="_blank">cryptojobslist.com</a> - <br /> - <p width="200px">The biggest list of crypto, blockchain and Web3 jobs</p> - </td> - <td align="center"> - <a href="https://plain.com/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/70170949?s=200&v=4" width="200px;" alt="Plain logo" /> - </a> - <br /> - <b>Plain.</b> - <br /> - <a href="https://plain.com/" target="_blank">plain.com</a> - <br /> - <p width="200px">How developers support their users</p> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://inngest.com/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/78935958?s=200&v=4" width="200px;" alt="Inngest logo" /> - </a> - <br /> - <b>Inngest</b> - <br /> - <a href="https://inngest.com/" target="_blank">inngest.com</a> - <br /> - <p width="200px">Serverless queues + durable workflows for TypeScript</p> - </td> - <td align="center"> - <a href="https://storyblok.com/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/13880908?s=200&v=4" width="200px;" alt="Storyblok CMS" /> - </a> - <br /> - <b>Storyblok</b> - <br /> - <a href="https://storyblok.com/" target="_blank">storyblok.com</a> - <br /> - <p width="200px">The only headless CMS with a visual editor</p> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://mux.link/zod" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/16199997?s=200&v=4" width="200px;" alt="Mux logo" /> - </a> - <br /> - <b>Mux</b> - <br /> - <a href="https://mux.link/zod" target="_blank">mux.com</a> - <br /> - <p width="200px">The internet's video infrastructure</p> - </td> - </tr> -</table> - -#### Silver - -<table> - <tr> - <td align="center" colspan="2"> - <a href="https://www.numeric.io" target="_blank"> - <img src="https://i.imgur.com/kTiLtZt.png" width="250px;" alt="Numeric logo" /> - </a> - <br /> - <b>Numeric</b> - <br /> - <a href="https://www.numeric.io" target="_blank">numeric.io</a> - </td> - <td align="center"> - <a href="https://marcatopartners.com/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/84106192?s=200&v=4" width="150px;" alt="Marcato Partners" /> - </a> - <br /> - <b>Marcato Partners</b> - <br /> - <a href="https://marcatopartners.com/" target="_blank">marcatopartners.com</a> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://interval.com" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/67802063?s=200&v=4" width="150px;" alt="" /> - </a> - <br /> - <b>Interval</b> - <br /> - <a href="https://interval.com" target="_blank">interval.com</a> - </td> - <td align="center"> - <a href="https://seasoned.cc" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/33913103?s=200&v=4" width="150px;" alt="" /> - </a> - <br /> - <b>Seasoned Software</b> - <br /> - <a href="https://seasoned.cc" target="_blank">seasoned.cc</a> - </td> - <td align="center"> - <a href="https://www.bamboocreative.nz/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/41406870?v=4" width="150px;" alt="Bamboo Creative logo" /> - </a> - <br /> - <b>Bamboo Creative</b> - <br /> - <a href="https://www.bamboocreative.nz" target="_blank">bamboocreative.nz</a> - </td> - </tr> -</table> - -#### Bronze - -<table> - <tr> - <td align="center"> - <a href="https://twitter.com/flybayer" target="_blank"> - <img src="https://avatars2.githubusercontent.com/u/8813276?s=460&u=4ff8beb9a67b173015c4b426a92d89cab960af1b&v=4" width="100px;" alt=""/> - </a> - <br /> - <b>Brandon Bayer</b> - <br/> - <a href="https://twitter.com/flybayer" target="_blank">@flybayer</a>, - <span>creator of <a href="https://blitzjs.com">Blitz.js</a></span> - <br /> - </td> - <td align="center"> - <a href="https://github.com/brabeji" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/2237954?v=4" width="100px;" alt=""/> - </a> - <br /> - <b>Jiří Brabec</b> - <br/> - <a href="https://github.com/brabeji" target="_blank">@brabeji</a> - <br /> - </td> - <td align="center"> - <a href="https://twitter.com/alexdotjs" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/459267?v=4" width="100px;" alt="" /> - </a> - <br /> - <b>Alex Johansson</b> - <br /> - <a href="https://twitter.com/alexdotjs" target="_blank">@alexdotjs</a> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://fungible.systems/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/80220121?s=200&v=4" width="100px;" alt="Fungible Systems logo"/> - </a> - <br /> - <b>Fungible Systems</b> - <br/> - <a href="https://fungible.systems/" target="_blank">fungible.systems</a> - <br /> - </td> - <td align="center"> - <a href="https://adaptable.io/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/60378268?s=200&v=4" width="100px;" alt=""/> - </a> - <br /> - <b>Adaptable</b> - <br/> - <a href="https://adaptable.io/" target="_blank">adaptable.io</a> - <br /> - </td> - <td align="center"> - <a href="https://www.avanawallet.com/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/105452197?s=200&v=4" width="100px;" alt="Avana Wallet logo"/> - </a> - <br /> - <b>Avana Wallet</b> - <br/> - <a href="https://www.avanawallet.com/" target="_blank">avanawallet.com</a><br/> - <span>Solana non-custodial wallet</span> - <br /> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://learnwithjason.dev" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/66575486?s=200&v=4" width="100px;" alt="Learn with Jason logo"/> - </a> - <br /> - <b>Jason Lengstorf</b> - <br/> - <a href="https://learnwithjason.dev/" target="_blank">learnwithjason.dev</a> - <br /> - </td> - <td align="center"> - <a href="https://ill.inc/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/89107581?s=200&v=4" width="100px;" alt="Global Illumination"/> - </a> - <br /> - <b>Global Illumination, Inc.</b> - <br/> - <a href="https://ill.inc/" target="_blank">ill.inc</a> - <br /> - </td> - <td align="center"> - <a href="https://www.masterborn.com/career?utm_source=github&utm_medium=referral&utm_campaign=zodsponsoring" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/48984031?s=200&v=4" width="100px;" alt="MasterBorn logo"/> - </a> - <br /> - <b>MasterBorn</b> - <br/> - <a href="https://www.masterborn.com/career?utm_source=github&utm_medium=referral&utm_campaign=zodsponsoring" target="_blank">masterborn.com</a> - <br /> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://github.com/kronodeus" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/18314366?v=4" width="100px;" alt="Ryan Palmer"/> - </a> - <br /> - <b>Ryan Palmer</b> - <br/> - <a href="https://github.com/kronodeus" target="_blank">@kronodeus</a> - <br /> - </td> - <td align="center"> - <a href="https://github.com/overthemike" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/223509?v=4" width="100px;" alt="Michael Sweeney"/> - </a> - <br /> - <b>Michael Sweeney</b> - <br/> - <a href="https://github.com/overthemike" target="_blank">@overthemike</a> - <br /> - </td> - <td align="center"> - <a href="https://usenextbase.com/" target="_blank"> - <img src="https://pbs.twimg.com/profile_images/1692236063409070080/28yXFtop_400x400.jpg" width="100px;" alt="Nextbase logo"/> - </a> - <br /> - <b>Nextbase</b> - <br/> - <a href="https://usenextbase.com/" target="_blank">usenextbase.com</a> - <br /> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://remotion.dev" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/85344006" width="100px;" alt="Remotion logo"/> - </a> - <br /> - <b>Remotion</b> - <br/> - <a href="https://remotion.dev" target="_blank">remotion.dev</a> - <br /> - </td> - <td align="center"> - <a href="https://github.com/ConnorSinnott" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/12754711?v=4" width="100px;" alt="Connor Sinnott profile"/> - </a> - <br /> - <b>Connor Sinnott</b> - <br/> - <a href="https://github.com/ConnorSinnott" target="_blank">@ConnorSinnott</a> - <br /> - </td> - <td align="center"> - <a href="https://aerabi.com/" target="_blank"> - <img src="https://avatars.githubusercontent.com/u/44623032?v=4" width="100px;" alt="aerabi"/> - </a> - <br /> - <b>Mohammad-Ali A'râbi</b> - <br/> - <a href="https://aerabi.com/" target="_blank">aerabi.com</a> - <br /> - </td> - </tr> - <tr> - <td align="center"> - <a href="https://supatool.io/" target="_blank"> - <img src="https://github.com/colinhacks/zod/assets/3084745/d0ec96c9-bf79-494f-9caa-9233da251f55" width="100px;" alt="Supatool logo"/> - </a> - <br /> - <b>Supatool</b> - <br/> - <a href="https://supatool.io/" target="_blank">supatool.io</a> - <br /> - </td> - </tr> -</table> - -### Ecosystem - -There are a growing number of tools that are built atop or support Zod natively! If you've built a tool or library on top of Zod, tell me about it [on Twitter](https://twitter.com/colinhacks) or [start a Discussion](https://github.com/colinhacks/zod/discussions). I'll add it below and tweet it out. - -#### Resources - -- [Total TypeScript Zod Tutorial](https://www.totaltypescript.com/tutorials/zod) by [@mattpocockuk](https://twitter.com/mattpocockuk) -- [Fixing TypeScript's Blindspot: Runtime Typechecking](https://www.youtube.com/watch?v=rY_XqfSHock) by [@jherr](https://twitter.com/jherr) - -#### API libraries - -- [`tRPC`](https://github.com/trpc/trpc): Build end-to-end typesafe APIs without GraphQL. -- [`@anatine/zod-nestjs`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-nestjs): Helper methods for using Zod in a NestJS project. -- [`zod-endpoints`](https://github.com/flock-community/zod-endpoints): Contract-first strictly typed endpoints with Zod. OpenAPI compatible. -- [`zhttp`](https://github.com/evertdespiegeleer/zhttp): An OpenAPI compatible, strictly typed http library with Zod input and response validation. -- [`domain-functions`](https://github.com/SeasonedSoftware/domain-functions/): Decouple your business logic from your framework using composable functions. With first-class type inference from end to end powered by Zod schemas. -- [`@zodios/core`](https://github.com/ecyrbe/zodios): A typescript API client with runtime and compile time validation backed by axios and zod. -- [`express-zod-api`](https://github.com/RobinTail/express-zod-api): Build Express-based APIs with I/O schema validation and custom middlewares. -- [`tapiduck`](https://github.com/sumukhbarve/monoduck/blob/main/src/tapiduck/README.md): End-to-end typesafe JSON APIs with Zod and Express; a bit like tRPC, but simpler. -- [`koa-zod-router`](https://github.com/JakeFenley/koa-zod-router): Create typesafe routes in Koa with I/O validation using Zod. - -#### Form integrations - -- [`react-hook-form`](https://github.com/react-hook-form/resolvers#zod): A first-party Zod resolver for React Hook Form. -- [`zod-validation-error`](https://github.com/causaly/zod-validation-error): Generate user-friendly error messages from `ZodError`s. -- [`zod-formik-adapter`](https://github.com/robertLichtnow/zod-formik-adapter): A community-maintained Formik adapter for Zod. -- [`react-zorm`](https://github.com/esamattis/react-zorm): Standalone `<form>` generation and validation for React using Zod. -- [`zodix`](https://github.com/rileytomasek/zodix): Zod utilities for FormData and URLSearchParams in Remix loaders and actions. -- [`conform`](https://conform.guide/api/zod/parseWithZod): A typesafe form validation library for progressive enhancement of HTML forms. Works with Remix and Next.js. -- [`remix-params-helper`](https://github.com/kiliman/remix-params-helper): Simplify integration of Zod with standard URLSearchParams and FormData for Remix apps. -- [`formik-validator-zod`](https://github.com/glazy/formik-validator-zod): Formik-compliant validator library that simplifies using Zod with Formik. -- [`zod-i18n-map`](https://github.com/aiji42/zod-i18n): Useful for translating Zod error messages. -- [`@modular-forms/solid`](https://github.com/fabian-hiller/modular-forms): Modular form library for SolidJS that supports Zod for validation. -- [`houseform`](https://github.com/crutchcorn/houseform/): A React form library that uses Zod for validation. -- [`sveltekit-superforms`](https://github.com/ciscoheat/sveltekit-superforms): Supercharged form library for SvelteKit with Zod validation. -- [`mobx-zod-form`](https://github.com/MonoidDev/mobx-zod-form): Data-first form builder based on MobX & Zod. -- [`@vee-validate/zod`](https://github.com/logaretm/vee-validate/tree/main/packages/zod): Form library for Vue.js with Zod schema validation. - -#### Zod to X - -- [`zod-to-ts`](https://github.com/sachinraja/zod-to-ts): Generate TypeScript definitions from Zod schemas. -- [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema): Convert your Zod schemas into [JSON Schemas](https://json-schema.org/). -- [`@anatine/zod-openapi`](https://github.com/anatine/zod-plugins/tree/main/packages/zod-openapi): Converts a Zod schema to an OpenAPI v3.x `SchemaObject`. -- [`zod-fast-check`](https://github.com/DavidTimms/zod-fast-check): Generate `fast-check` arbitraries from Zod schemas. -- [`zod-dto`](https://github.com/kbkk/abitia/tree/master/packages/zod-dto): Generate Nest.js DTOs from a Zod schema. -- [`fastify-type-provider-zod`](https://github.com/turkerdev/fastify-type-provider-zod): Create Fastify type providers from Zod schemas. -- [`zod-to-openapi`](https://github.com/asteasolutions/zod-to-openapi): Generate full OpenAPI (Swagger) docs from Zod, including schemas, endpoints & parameters. -- [`nestjs-graphql-zod`](https://github.com/incetarik/nestjs-graphql-zod): Generates NestJS GraphQL model classes from Zod schemas. Provides GraphQL method decorators working with Zod schemas. -- [`zod-openapi`](https://github.com/samchungy/zod-openapi): Create full OpenAPI v3.x documentation from Zod schemas. -- [`fastify-zod-openapi`](https://github.com/samchungy/fastify-zod-openapi): Fastify type provider, validation, serialization and @fastify/swagger support for Zod schemas. -- [`typeschema`](https://typeschema.com/): Universal adapter for schema validation. - -#### X to Zod - -- [`ts-to-zod`](https://github.com/fabien0102/ts-to-zod): Convert TypeScript definitions into Zod schemas. -- [`@runtyping/zod`](https://github.com/johngeorgewright/runtyping/tree/master/packages/zod): Generate Zod from static types & JSON schema. -- [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod): Convert your [JSON Schemas](https://json-schema.org/) into Zod schemas. [Live demo](https://StefanTerdell.github.io/json-schema-to-zod-react/). -- [`json-to-zod`](https://github.com/rsinohara/json-to-zod): Convert JSON objects into Zod schemas. [Live demo](https://rsinohara.github.io/json-to-zod-react/). -- [`graphql-codegen-typescript-validation-schema`](https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema): GraphQL Code Generator plugin to generate form validation schema from your GraphQL schema. -- [`zod-prisma`](https://github.com/CarterGrimmeisen/zod-prisma): Generate Zod schemas from your Prisma schema. -- [`Supervillain`](https://github.com/Southclaws/supervillain): Generate Zod schemas from your Go structs. -- [`prisma-zod-generator`](https://github.com/omar-dulaimi/prisma-zod-generator): Emit Zod schemas from your Prisma schema. -- [`prisma-trpc-generator`](https://github.com/omar-dulaimi/prisma-trpc-generator): Emit fully implemented tRPC routers and their validation schemas using Zod. -- [`zod-prisma-types`](https://github.com/chrishoermann/zod-prisma-types) Create Zod types from your Prisma models. -- [`quicktype`](https://app.quicktype.io/): Convert JSON objects and JSON schemas into Zod schemas. -- [`@sanity-typed/zod`](https://github.com/saiichihashimoto/sanity-typed/tree/main/packages/zod): Generate Zod Schemas from [Sanity Schemas](https://www.sanity.io/docs/schema-types). - -#### Mocking - -- [`@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/faker-js/faker). -- [`zod-mocking`](https://github.com/dipasqualew/zod-mocking): Generate mock data from your Zod schemas. -- [`zod-fixture`](https://github.com/timdeschryver/zod-fixture): Use your zod schemas to automate the generation of non-relevant test fixtures in a deterministic way. -- [`zocker`](https://zocker.sigrist.dev): Generate plausible mock-data from your schemas. -- [`zodock`](https://github.com/ItMaga/zodock) Generate mock data based on Zod schemas. - -#### Powered by Zod - -- [`freerstore`](https://github.com/JacobWeisenburger/freerstore): Firestore cost optimizer. -- [`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. -- [`soly`](https://github.com/mdbetancourt/soly): Create CLI applications with zod. -- [`pastel`](https://github.com/vadimdemedes/pastel): Create CLI applications with react, zod, and ink. -- [`zod-xlsx`](https://github.com/sidwebworks/zod-xlsx): A xlsx based resource validator using Zod schemas. -- [`znv`](https://github.com/lostfictions/znv): Type-safe environment parsing and validation for Node.js with Zod schemas. -- [`zod-config`](https://github.com/alexmarqs/zod-config): Load configurations across multiple sources with flexible adapters, ensuring type safety with Zod. - -#### Utilities for Zod - -- [`zod_utilz`](https://github.com/JacobWeisenburger/zod_utilz): Framework agnostic utilities for Zod. -- [`zod-sandbox`](https://github.com/nereumelo/zod-sandbox): Controlled environment for testing zod schemas. [Live demo](https://zod-sandbox.vercel.app/). -- [`zod-dev`](https://github.com/schalkventer/zod-dev): Conditionally disables Zod runtime parsing in production. - -## Installation - -### Requirements - -- TypeScript 4.5+! -- You must enable `strict` mode in your `tsconfig.json`. This is a best practice for all TypeScript projects. - - ```ts - // tsconfig.json - { - // ... - "compilerOptions": { - // ... - "strict": true - } - } - ``` - -### From `npm` (Node/Bun) - -```sh -npm install zod # npm -yarn add zod # yarn -bun add zod # bun -pnpm add zod # pnpm -``` - -Zod also publishes a canary version on every commit. To install the canary: - -```sh -npm install zod@canary # npm -yarn add zod@canary # yarn -bun add zod@canary # bun -pnpm add zod@canary # pnpm -``` - -### From `deno.land/x` (Deno) - -Unlike Node, Deno relies on direct URL imports instead of a package manager like NPM. Zod is available on [deno.land/x](https://deno.land/x). The latest version can be imported like so: - -```ts -import { z } from "https://deno.land/x/zod/mod.ts"; -``` - -You can also specify a particular version: - -```ts -import { z } from "https://deno.land/x/zod@v3.16.1/mod.ts"; -``` - -> The rest of this README assumes you are using npm and importing directly from the `"zod"` package. - -## Basic usage - -Creating a simple string schema - -```ts -import { z } from "zod"; - -// creating a schema for strings -const mySchema = z.string(); - -// parsing -mySchema.parse("tuna"); // => "tuna" -mySchema.parse(12); // => throws ZodError - -// "safe" parsing (doesn't throw error if validation fails) -mySchema.safeParse("tuna"); // => { success: true; data: "tuna" } -mySchema.safeParse(12); // => { success: false; error: ZodError } -``` - -Creating an object schema - -```ts -import { z } from "zod"; - -const User = z.object({ - username: z.string(), -}); - -User.parse({ username: "Ludwig" }); - -// extract the inferred type -type User = z.infer<typeof User>; -// { username: string } -``` - -## Primitives - -```ts -import { z } from "zod"; - -// primitive values -z.string(); -z.number(); -z.bigint(); -z.boolean(); -z.date(); -z.symbol(); - -// empty types -z.undefined(); -z.null(); -z.void(); // accepts undefined - -// catch-all types -// allows any value -z.any(); -z.unknown(); - -// never type -// allows no values -z.never(); -``` - -## Coercion for primitives - -Zod now provides a more convenient way to coerce primitive values. - -```ts -const schema = z.coerce.string(); -schema.parse("tuna"); // => "tuna" -schema.parse(12); // => "12" -``` - -During the parsing step, the input is passed through the `String()` function, which is a JavaScript built-in for coercing data into strings. - -The returned schema is a normal `ZodString` instance so you can use all string methods. - -```ts -z.coerce.string().email().min(5); -``` - -**How coercion works** - -All primitive types support coercion. Zod coerces all inputs using the built-in constructors: `String(input)`, `Number(input)`, `new Date(input)`, etc. - -```ts -z.coerce.string(); // String(input) -z.coerce.number(); // Number(input) -z.coerce.boolean(); // Boolean(input) -z.coerce.bigint(); // BigInt(input) -z.coerce.date(); // new Date(input) -``` - -Note that some behavior may not be what you expect. - -```ts -schema.parse(true); // => "true" -schema.parse(undefined); // => "undefined" -schema.parse(null); // => "null" -``` - -For more control over coercion logic, consider using [`z.preprocess`](#preprocess) or [`z.pipe()`](#pipe). - -**Boolean coercion** - -Zod's approach to coercion is very simple! It passes the value into the `Boolean(value)` function, that's it. Any truthy value will resolve to `true`, any falsy value will resolve to `false`. - -```ts -z.coerce.boolean().parse("tuna"); // => true -z.coerce.boolean().parse("true"); // => true -z.coerce.boolean().parse("false"); // => true -z.coerce.boolean().parse(1); // => true -z.coerce.boolean().parse([]); // => true - -z.coerce.boolean().parse(0); // => false -z.coerce.boolean().parse(""); // => false -z.coerce.boolean().parse(undefined); // => false -z.coerce.boolean().parse(null); // => false -``` - -## Literals - -Literal schemas represent a [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types), like `"hello world"` or `5`. - -```ts -const tuna = z.literal("tuna"); -const twelve = z.literal(12); -const twobig = z.literal(2n); // bigint literal -const tru = z.literal(true); - -const terrificSymbol = Symbol("terrific"); -const terrific = z.literal(terrificSymbol); - -// retrieve literal value -tuna.value; // "tuna" -``` - -> Currently there is no support for Date literals in Zod. If you have a use case for this feature, please file an issue. - -## Strings - -Zod includes a handful of string-specific validations. - -```ts -// validations -z.string().max(5); -z.string().min(5); -z.string().length(5); -z.string().email(); -z.string().url(); -z.string().emoji(); -z.string().uuid(); -z.string().cuid(); -z.string().cuid2(); -z.string().ulid(); -z.string().regex(regex); -z.string().includes(string); -z.string().startsWith(string); -z.string().endsWith(string); -z.string().datetime(); // ISO 8601; default is without UTC offset, see below for options -z.string().ip(); // defaults to IPv4 and IPv6, see below for options - -// transformations -z.string().trim(); // trim whitespace -z.string().toLowerCase(); // toLowerCase -z.string().toUpperCase(); // toUpperCase -``` - -> Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of other useful string validation functions that can be used in conjunction with [Refinements](#refine). - -You can customize some common error messages when creating a string schema. - -```ts -const name = z.string({ - required_error: "Name is required", - invalid_type_error: "Name must be a string", -}); -``` - -When using validation methods, you can pass in an additional argument to provide a custom error message. - -```ts -z.string().min(5, { message: "Must be 5 or more characters long" }); -z.string().max(5, { message: "Must be 5 or fewer characters long" }); -z.string().length(5, { message: "Must be exactly 5 characters long" }); -z.string().email({ message: "Invalid email address" }); -z.string().url({ message: "Invalid url" }); -z.string().emoji({ message: "Contains non-emoji characters" }); -z.string().uuid({ message: "Invalid UUID" }); -z.string().includes("tuna", { message: "Must include tuna" }); -z.string().startsWith("https://", { message: "Must provide secure URL" }); -z.string().endsWith(".com", { message: "Only .com domains allowed" }); -z.string().datetime({ message: "Invalid datetime string! Must be UTC." }); -z.string().ip({ message: "Invalid IP address" }); -``` - -### ISO datetimes - -The `z.string().datetime()` method enforces ISO 8601; default is no timezone offsets and arbitrary sub-second decimal precision. - -```ts -const datetime = z.string().datetime(); - -datetime.parse("2020-01-01T00:00:00Z"); // pass -datetime.parse("2020-01-01T00:00:00.123Z"); // pass -datetime.parse("2020-01-01T00:00:00.123456Z"); // pass (arbitrary precision) -datetime.parse("2020-01-01T00:00:00+02:00"); // fail (no offsets allowed) -``` - -Timezone offsets can be allowed by setting the `offset` option to `true`. - -```ts -const datetime = z.string().datetime({ offset: true }); - -datetime.parse("2020-01-01T00:00:00+02:00"); // pass -datetime.parse("2020-01-01T00:00:00.123+02:00"); // pass (millis optional) -datetime.parse("2020-01-01T00:00:00.123+0200"); // pass (millis optional) -datetime.parse("2020-01-01T00:00:00.123+02"); // pass (only offset hours) -datetime.parse("2020-01-01T00:00:00Z"); // pass (Z still supported) -``` - -You can additionally constrain the allowable `precision`. By default, arbitrary sub-second precision is supported (but optional). - -```ts -const datetime = z.string().datetime({ precision: 3 }); - -datetime.parse("2020-01-01T00:00:00.123Z"); // pass -datetime.parse("2020-01-01T00:00:00Z"); // fail -datetime.parse("2020-01-01T00:00:00.123456Z"); // fail -``` - -### IP addresses - -The `z.string().ip()` method by default validate IPv4 and IPv6. - -```ts -const ip = z.string().ip(); - -ip.parse("192.168.1.1"); // pass -ip.parse("84d5:51a0:9114:1855:4cfa:f2d7:1f12:7003"); // pass -ip.parse("84d5:51a0:9114:1855:4cfa:f2d7:1f12:192.168.1.1"); // pass - -ip.parse("256.1.1.1"); // fail -ip.parse("84d5:51a0:9114:gggg:4cfa:f2d7:1f12:7003"); // fail -``` - -You can additionally set the IP `version`. - -```ts -const ipv4 = z.string().ip({ version: "v4" }); -ipv4.parse("84d5:51a0:9114:1855:4cfa:f2d7:1f12:7003"); // fail - -const ipv6 = z.string().ip({ version: "v6" }); -ipv6.parse("192.168.1.1"); // fail -``` - -## Numbers - -You can customize certain error messages when creating a number schema. - -```ts -const age = z.number({ - required_error: "Age is required", - invalid_type_error: "Age must be a number", -}); -``` - -Zod includes a handful of number-specific validations. - -```ts -z.number().gt(5); -z.number().gte(5); // alias .min(5) -z.number().lt(5); -z.number().lte(5); // alias .max(5) - -z.number().int(); // value must be an integer - -z.number().positive(); // > 0 -z.number().nonnegative(); // >= 0 -z.number().negative(); // < 0 -z.number().nonpositive(); // <= 0 - -z.number().multipleOf(5); // Evenly divisible by 5. Alias .step(5) - -z.number().finite(); // value must be finite, not Infinity or -Infinity -z.number().safe(); // value must be between Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER -``` - -Optionally, you can pass in a second argument to provide a custom error message. - -```ts -z.number().lte(5, { message: "this👏is👏too👏big" }); -``` - -## BigInts - -Zod includes a handful of bigint-specific validations. - -```ts -z.bigint().gt(5n); -z.bigint().gte(5n); // alias `.min(5n)` -z.bigint().lt(5n); -z.bigint().lte(5n); // alias `.max(5n)` - -z.bigint().positive(); // > 0n -z.bigint().nonnegative(); // >= 0n -z.bigint().negative(); // < 0n -z.bigint().nonpositive(); // <= 0n - -z.bigint().multipleOf(5n); // Evenly divisible by 5n. -``` - -## NaNs - -You can customize certain error messages when creating a nan schema. - -```ts -const isNaN = z.nan({ - required_error: "isNaN is required", - invalid_type_error: "isNaN must be 'not a number'", -}); -``` - -## Booleans - -You can customize certain error messages when creating a boolean schema. - -```ts -const isActive = z.boolean({ - required_error: "isActive is required", - invalid_type_error: "isActive must be a boolean", -}); -``` - -## Dates - -Use z.date() to validate `Date` instances. - -```ts -z.date().safeParse(new Date()); // success: true -z.date().safeParse("2022-01-12T00:00:00.000Z"); // success: false -``` - -You can customize certain error messages when creating a date schema. - -```ts -const myDateSchema = z.date({ - required_error: "Please select a date and time", - invalid_type_error: "That's not a date!", -}); -``` - -Zod provides a handful of date-specific validations. - -```ts -z.date().min(new Date("1900-01-01"), { message: "Too old" }); -z.date().max(new Date(), { message: "Too young!" }); -``` - -**Coercion to Date** - -Since [zod 3.20](https://github.com/colinhacks/zod/releases/tag/v3.20), use [`z.coerce.date()`](#coercion-for-primitives) to pass the input through `new Date(input)`. - -```ts -const dateSchema = z.coerce.date(); -type DateSchema = z.infer<typeof dateSchema>; -// type DateSchema = Date - -/* valid dates */ -console.log(dateSchema.safeParse("2023-01-10T00:00:00.000Z").success); // true -console.log(dateSchema.safeParse("2023-01-10").success); // true -console.log(dateSchema.safeParse("1/10/23").success); // true -console.log(dateSchema.safeParse(new Date("1/10/23")).success); // true - -/* invalid dates */ -console.log(dateSchema.safeParse("2023-13-10").success); // false -console.log(dateSchema.safeParse("0000-00-00").success); // false -``` - -For older zod versions, use [`z.preprocess`](#preprocess) like [described in this thread](https://github.com/colinhacks/zod/discussions/879#discussioncomment-2036276). - -## Zod enums - -```ts -const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]); -type FishEnum = z.infer<typeof FishEnum>; -// 'Salmon' | 'Tuna' | 'Trout' -``` - -`z.enum` is a Zod-native way to declare a schema with a fixed set of allowable _string_ values. Pass the array of values directly into `z.enum()`. Alternatively, use `as const` to define your enum values as a tuple of strings. See the [const assertion docs](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) for details. - -```ts -const VALUES = ["Salmon", "Tuna", "Trout"] as const; -const FishEnum = z.enum(VALUES); -``` - -This is not allowed, since Zod isn't able to infer the exact values of each element. - -```ts -const fish = ["Salmon", "Tuna", "Trout"]; -const FishEnum = z.enum(fish); -``` - -**`.enum`** - -To get autocompletion with a Zod enum, use the `.enum` property of your schema: - -```ts -FishEnum.enum.Salmon; // => autocompletes - -FishEnum.enum; -/* -=> { - Salmon: "Salmon", - Tuna: "Tuna", - Trout: "Trout", -} -*/ -``` - -You can also retrieve the list of options as a tuple with the `.options` property: - -```ts -FishEnum.options; // ["Salmon", "Tuna", "Trout"]; -``` - -**`.exclude/.extract()`** - -You can create subsets of a Zod enum with the `.exclude` and `.extract` methods. - -```ts -const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]); -const SalmonAndTrout = FishEnum.extract(["Salmon", "Trout"]); -const TunaOnly = FishEnum.exclude(["Salmon", "Trout"]); -``` - -## Native enums - -Zod enums are the recommended approach to defining and validating enums. But if you need to validate against an enum from a third-party library (or you don't want to rewrite your existing enums) you can use `z.nativeEnum()`. - -**Numeric enums** - -```ts -enum Fruits { - Apple, - Banana, -} - -const FruitEnum = z.nativeEnum(Fruits); -type FruitEnum = z.infer<typeof FruitEnum>; // Fruits - -FruitEnum.parse(Fruits.Apple); // passes -FruitEnum.parse(Fruits.Banana); // passes -FruitEnum.parse(0); // passes -FruitEnum.parse(1); // passes -FruitEnum.parse(3); // fails -``` - -**String enums** - -```ts -enum Fruits { - Apple = "apple", - Banana = "banana", - Cantaloupe, // you can mix numerical and string enums -} - -const FruitEnum = z.nativeEnum(Fruits); -type FruitEnum = z.infer<typeof FruitEnum>; // Fruits - -FruitEnum.parse(Fruits.Apple); // passes -FruitEnum.parse(Fruits.Cantaloupe); // passes -FruitEnum.parse("apple"); // passes -FruitEnum.parse("banana"); // passes -FruitEnum.parse(0); // passes -FruitEnum.parse("Cantaloupe"); // fails -``` - -**Const enums** - -The `.nativeEnum()` function works for `as const` objects as well. ⚠️ `as const` requires TypeScript 3.4+! - -```ts -const Fruits = { - Apple: "apple", - Banana: "banana", - Cantaloupe: 3, -} as const; - -const FruitEnum = z.nativeEnum(Fruits); -type FruitEnum = z.infer<typeof FruitEnum>; // "apple" | "banana" | 3 - -FruitEnum.parse("apple"); // passes -FruitEnum.parse("banana"); // passes -FruitEnum.parse(3); // passes -FruitEnum.parse("Cantaloupe"); // fails -``` - -You can access the underlying object with the `.enum` property: - -```ts -FruitEnum.enum.Apple; // "apple" -``` - -## Optionals - -You can make any schema optional with `z.optional()`. This wraps the schema in a `ZodOptional` instance and returns the result. - -```ts -const schema = z.optional(z.string()); - -schema.parse(undefined); // => returns undefined -type A = z.infer<typeof schema>; // string | undefined -``` - -For convenience, you can also call the `.optional()` method on an existing schema. - -```ts -const user = z.object({ - username: z.string().optional(), -}); -type C = z.infer<typeof user>; // { username?: string | undefined }; -``` - -You can extract the wrapped schema from a `ZodOptional` instance with `.unwrap()`. - -```ts -const stringSchema = z.string(); -const optionalString = stringSchema.optional(); -optionalString.unwrap() === stringSchema; // true -``` - -## Nullables - -Similarly, you can create nullable types with `z.nullable()`. - -```ts -const nullableString = z.nullable(z.string()); -nullableString.parse("asdf"); // => "asdf" -nullableString.parse(null); // => null -``` - -Or use the `.nullable()` method. - -```ts -const E = z.string().nullable(); // equivalent to nullableString -type E = z.infer<typeof E>; // string | null -``` - -Extract the inner schema with `.unwrap()`. - -```ts -const stringSchema = z.string(); -const nullableString = stringSchema.nullable(); -nullableString.unwrap() === stringSchema; // true -``` - -## Objects - -```ts -// all properties are required by default -const Dog = z.object({ - name: z.string(), - age: z.number(), -}); - -// extract the inferred type like this -type Dog = z.infer<typeof Dog>; - -// equivalent to: -type Dog = { - name: string; - age: number; -}; -``` - -### `.shape` - -Use `.shape` to access the schemas for a particular key. - -```ts -Dog.shape.name; // => string schema -Dog.shape.age; // => number schema -``` - -### `.keyof` - -Use `.keyof` to create a `ZodEnum` schema from the keys of an object schema. - -```ts -const keySchema = Dog.keyof(); -keySchema; // ZodEnum<["name", "age"]> -``` - -### `.extend` - -You can add additional fields to an object schema with the `.extend` method. - -```ts -const DogWithBreed = Dog.extend({ - breed: z.string(), -}); -``` - -You can use `.extend` to overwrite fields! Be careful with this power! - -### `.merge` - -Equivalent to `A.extend(B.shape)`. - -```ts -const BaseTeacher = z.object({ students: z.array(z.string()) }); -const HasID = z.object({ id: z.string() }); - -const Teacher = BaseTeacher.merge(HasID); -type Teacher = z.infer<typeof Teacher>; // => { students: string[], id: string } -``` - -> If the two schemas share keys, the properties of B overrides the property of A. The returned schema also inherits the "unknownKeys" policy (strip/strict/passthrough) and the catchall schema of B. - -### `.pick/.omit` - -Inspired by TypeScript's built-in `Pick` and `Omit` utility types, all Zod object schemas have `.pick` and `.omit` methods that return a modified version. Consider this Recipe schema: - -```ts -const Recipe = z.object({ - id: z.string(), - name: z.string(), - ingredients: z.array(z.string()), -}); -``` - -To only keep certain keys, use `.pick` . - -```ts -const JustTheName = Recipe.pick({ name: true }); -type JustTheName = z.infer<typeof JustTheName>; -// => { name: string } -``` - -To remove certain keys, use `.omit` . - -```ts -const NoIDRecipe = Recipe.omit({ id: true }); - -type NoIDRecipe = z.infer<typeof NoIDRecipe>; -// => { name: string, ingredients: string[] } -``` - -### `.partial` - -Inspired by the built-in TypeScript utility type [Partial](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype), the `.partial` method makes all properties optional. - -Starting from this object: - -```ts -const user = z.object({ - email: z.string(), - username: z.string(), -}); -// { email: string; username: string } -``` - -We can create a partial version: - -```ts -const partialUser = user.partial(); -// { email?: string | undefined; username?: string | undefined } -``` - -You can also specify which properties to make optional: - -```ts -const optionalEmail = user.partial({ - email: true, -}); -/* -{ - email?: string | undefined; - username: string -} -*/ -``` - -### `.deepPartial` - -The `.partial` method is shallow — it only applies one level deep. There is also a "deep" version: - -```ts -const user = z.object({ - username: z.string(), - location: z.object({ - latitude: z.number(), - longitude: z.number(), - }), - strings: z.array(z.object({ value: z.string() })), -}); - -const deepPartialUser = user.deepPartial(); - -/* -{ - username?: string | undefined, - location?: { - latitude?: number | undefined; - longitude?: number | undefined; - } | undefined, - strings?: { value?: string}[] -} -*/ -``` - -> Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples. - -### `.required` - -Contrary to the `.partial` method, the `.required` method makes all properties required. - -Starting from this object: - -```ts -const user = z - .object({ - email: z.string(), - username: z.string(), - }) - .partial(); -// { email?: string | undefined; username?: string | undefined } -``` - -We can create a required version: - -```ts -const requiredUser = user.required(); -// { email: string; username: string } -``` - -You can also specify which properties to make required: - -```ts -const requiredEmail = user.required({ - email: true, -}); -/* -{ - email: string; - username?: string | undefined; -} -*/ -``` - -### `.passthrough` - -By default Zod object schemas strip out unrecognized keys during parsing. - -```ts -const person = z.object({ - name: z.string(), -}); - -person.parse({ - name: "bob dylan", - extraKey: 61, -}); -// => { name: "bob dylan" } -// extraKey has been stripped -``` - -Instead, if you want to pass through unknown keys, use `.passthrough()` . - -```ts -person.passthrough().parse({ - name: "bob dylan", - extraKey: 61, -}); -// => { name: "bob dylan", extraKey: 61 } -``` - -### `.strict` - -By default Zod object schemas strip out unrecognized keys during parsing. You can _disallow_ unknown keys with `.strict()` . If there are any unknown keys in the input, Zod will throw an error. - -```ts -const person = z - .object({ - name: z.string(), - }) - .strict(); - -person.parse({ - name: "bob dylan", - extraKey: 61, -}); -// => throws ZodError -``` - -### `.strip` - -You can use the `.strip` method to reset an object schema to the default behavior (stripping unrecognized keys). - -### `.catchall` - -You can pass a "catchall" schema into an object schema. All unknown keys will be validated against it. - -```ts -const person = z - .object({ - name: z.string(), - }) - .catchall(z.number()); - -person.parse({ - name: "bob dylan", - validExtraKey: 61, // works fine -}); - -person.parse({ - name: "bob dylan", - validExtraKey: false, // fails -}); -// => throws ZodError -``` - -Using `.catchall()` obviates `.passthrough()` , `.strip()` , or `.strict()`. All keys are now considered "known". - -## Arrays - -```ts -const stringArray = z.array(z.string()); - -// equivalent -const stringArray = z.string().array(); -``` - -Be careful with the `.array()` method. It returns a new `ZodArray` instance. This means the _order_ in which you call methods matters. For instance: - -```ts -z.string().optional().array(); // (string | undefined)[] -z.string().array().optional(); // string[] | undefined -``` - -### `.element` - -Use `.element` to access the schema for an element of the array. - -```ts -stringArray.element; // => string schema -``` - -### `.nonempty` - -If you want to ensure that an array contains at least one element, use `.nonempty()`. - -```ts -const nonEmptyStrings = z.string().array().nonempty(); -// the inferred type is now -// [string, ...string[]] - -nonEmptyStrings.parse([]); // throws: "Array cannot be empty" -nonEmptyStrings.parse(["Ariana Grande"]); // passes -``` - -You can optionally specify a custom error message: - -```ts -// optional custom error message -const nonEmptyStrings = z.string().array().nonempty({ - message: "Can't be empty!", -}); -``` - -### `.min/.max/.length` - -```ts -z.string().array().min(5); // must contain 5 or more items -z.string().array().max(5); // must contain 5 or fewer items -z.string().array().length(5); // must contain 5 items exactly -``` - -Unlike `.nonempty()` these methods do not change the inferred type. - -## Tuples - -Unlike arrays, tuples have a fixed number of elements and each element can have a different type. - -```ts -const athleteSchema = z.tuple([ - z.string(), // name - z.number(), // jersey number - z.object({ - pointsScored: z.number(), - }), // statistics -]); - -type Athlete = z.infer<typeof athleteSchema>; -// type Athlete = [string, number, { pointsScored: number }] -``` - -A variadic ("rest") argument can be added with the `.rest` method. - -```ts -const variadicTuple = z.tuple([z.string()]).rest(z.number()); -const result = variadicTuple.parse(["hello", 1, 2, 3]); -// => [string, ...number[]]; -``` - -## Unions - -Zod includes a built-in `z.union` method for composing "OR" types. - -```ts -const stringOrNumber = z.union([z.string(), z.number()]); - -stringOrNumber.parse("foo"); // passes -stringOrNumber.parse(14); // passes -``` - -Zod will test the input against each of the "options" in order and return the first value that validates successfully. - -For convenience, you can also use the [`.or` method](#or): - -```ts -const stringOrNumber = z.string().or(z.number()); -``` - -**Optional string validation:** - -To validate an optional form input, you can union the desired string validation with an empty string [literal](#literals). - -This example validates an input that is optional but needs to contain a [valid URL](#strings): - -```ts -const optionalUrl = z.union([z.string().url().nullish(), z.literal("")]); - -console.log(optionalUrl.safeParse(undefined).success); // true -console.log(optionalUrl.safeParse(null).success); // true -console.log(optionalUrl.safeParse("").success); // true -console.log(optionalUrl.safeParse("https://zod.dev").success); // true -console.log(optionalUrl.safeParse("not a valid url").success); // false -``` - -## Discriminated unions - -A discriminated union is a union of object schemas that all share a particular key. - -```ts -type MyUnion = - | { status: "success"; data: string } - | { status: "failed"; error: Error }; -``` - -Such unions can be represented with the `z.discriminatedUnion` method. This enables faster evaluation, because Zod can check the _discriminator key_ (`status` in the example above) to determine which schema should be used to parse the input. This makes parsing more efficient and lets Zod report friendlier errors. - -With the basic union method, the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option". - -```ts -const myUnion = z.discriminatedUnion("status", [ - z.object({ status: z.literal("success"), data: z.string() }), - z.object({ status: z.literal("failed"), error: z.instanceof(Error) }), -]); - -myUnion.parse({ status: "success", data: "yippie ki yay" }); -``` - -You can extract a reference to the array of schemas with the `.options` property. - -```ts -myUnion.options; // [ZodObject<...>, ZodObject<...>] -``` - -To merge two or more discriminated unions, use `.options` with destructuring. - -```ts -const A = z.discriminatedUnion("status", [ - /* options */ -]); -const B = z.discriminatedUnion("status", [ - /* options */ -]); - -const AB = z.discriminatedUnion("status", [...A.options, ...B.options]); -``` - -## Records - -Record schemas are used to validate types such as `Record<string, number>`. This is particularly useful for storing or caching items by ID. - -<!-- If you want to validate the _values_ of an object against some schema but don't care about the keys, use `z.record(valueType)`: - -```ts -const NumberCache = z.record(z.number()); - -type NumberCache = z.infer<typeof NumberCache>; -// => { [k: string]: number } -``` --> - -```ts -const User = z.object({ name: z.string() }); - -const UserStore = z.record(z.string(), User); -type UserStore = z.infer<typeof UserStore>; -// => Record<string, { name: string }> -``` - -The schema and inferred type can be used like so: - -```ts -const userStore: UserStore = {}; - -userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = { - name: "Carlotta", -}; // passes - -userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = { - whatever: "Ice cream sundae", -}; // TypeError -``` - -**A note on numerical keys** - -While `z.record(keyType, valueType)` is able to accept numerical key types and TypeScript's built-in Record type is `Record<KeyType, ValueType>`, it's hard to represent the TypeScript type `Record<number, any>` in Zod. - -As it turns out, TypeScript's behavior surrounding `[k: number]` is a little unintuitive: - -```ts -const testMap: { [k: number]: string } = { - 1: "one", -}; - -for (const key in testMap) { - console.log(`${key}: ${typeof key}`); -} -// prints: `1: string` -``` - -As you can see, JavaScript automatically casts all object keys to strings under the hood. Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript. - -## Maps - -```ts -const stringNumberMap = z.map(z.string(), z.number()); - -type StringNumberMap = z.infer<typeof stringNumberMap>; -// type StringNumberMap = Map<string, number> -``` - -## Sets - -```ts -const numberSet = z.set(z.number()); -type NumberSet = z.infer<typeof numberSet>; -// type NumberSet = Set<number> -``` - -Set schemas can be further constrained with the following utility methods. - -```ts -z.set(z.string()).nonempty(); // must contain at least one item -z.set(z.string()).min(5); // must contain 5 or more items -z.set(z.string()).max(5); // must contain 5 or fewer items -z.set(z.string()).size(5); // must contain 5 items exactly -``` - -## Intersections - -Intersections are useful for creating "logical AND" types. This is useful for intersecting two object types. - -```ts -const Person = z.object({ - name: z.string(), -}); - -const Employee = z.object({ - role: z.string(), -}); - -const EmployedPerson = z.intersection(Person, Employee); - -// equivalent to: -const EmployedPerson = Person.and(Employee); -``` - -Though in many cases, it is recommended to use `A.merge(B)` to merge two objects. The `.merge` method returns a new `ZodObject` instance, whereas `A.and(B)` returns a less useful `ZodIntersection` instance that lacks common object methods like `pick` and `omit`. - -```ts -const a = z.union([z.number(), z.string()]); -const b = z.union([z.number(), z.boolean()]); -const c = z.intersection(a, b); - -type c = z.infer<typeof c>; // => number -``` - -<!-- Intersections in Zod are not smart. Whatever data you pass into `.parse()` gets passed into the two intersected schemas. Because Zod object schemas don't allow any unknown keys by default, there are some unintuitive behavior surrounding intersections of object schemas. --> - -<!-- - -``` ts -const A = z.object({ - a: z.string(), -}); - -const B = z.object({ - b: z.string(), -}); - -const AB = z.intersection(A, B); - -type Teacher = z.infer<typeof Teacher>; -// { id:string; name:string }; -``` --> - -## Recursive types - -You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint". - -```ts -const baseCategorySchema = z.object({ - name: z.string(), -}); - -type Category = z.infer<typeof baseCategorySchema> & { - subcategories: Category[]; -}; - -const categorySchema: z.ZodType<Category> = baseCategorySchema.extend({ - subcategories: z.lazy(() => categorySchema.array()), -}); - -categorySchema.parse({ - name: "People", - subcategories: [ - { - name: "Politicians", - subcategories: [ - { - name: "Presidents", - subcategories: [], - }, - ], - }, - ], -}); // passes -``` - -Thanks to [crasite](https://github.com/crasite) for this example. - -### ZodType with ZodEffects - -When using `z.ZodType` with `z.ZodEffects` ( -[`.refine`](https://github.com/colinhacks/zod#refine), -[`.transform`](https://github.com/colinhacks/zod#transform), -[`preprocess`](https://github.com/colinhacks/zod#preprocess), -etc... -), you will need to define the input and output types of the schema. `z.ZodType<Output, z.ZodTypeDef, Input>` - -```ts -const isValidId = (id: string): id is `${string}/${string}` => - id.split("/").length === 2; - -const baseSchema = z.object({ - id: z.string().refine(isValidId), -}); - -type Input = z.input<typeof baseSchema> & { - children: Input[]; -}; - -type Output = z.output<typeof baseSchema> & { - children: Output[]; -}; - -const schema: z.ZodType<Output, z.ZodTypeDef, Input> = baseSchema.extend({ - children: z.lazy(() => schema.array()), -}); -``` - -Thanks to [marcus13371337](https://github.com/marcus13371337) and [JoelBeeldi](https://github.com/JoelBeeldi) for this example. - -### JSON type - -If you want to validate any JSON value, you can use the snippet below. - -```ts -const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]); -type Literal = z.infer<typeof literalSchema>; -type Json = Literal | { [key: string]: Json } | Json[]; -const jsonSchema: z.ZodType<Json> = z.lazy(() => - z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]) -); - -jsonSchema.parse(data); -``` - -Thanks to [ggoodman](https://github.com/ggoodman) for suggesting this. - -### Cyclical objects - -Despite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop. - -## Promises - -```ts -const numberPromise = z.promise(z.number()); -``` - -"Parsing" works a little differently with promise schemas. Validation happens in two parts: - -1. Zod synchronously checks that the input is an instance of Promise (i.e. an object with `.then` and `.catch` methods.). -2. Zod uses `.then` to attach an additional validation step onto the existing Promise. You'll have to use `.catch` on the returned Promise to handle validation failures. - -```ts -numberPromise.parse("tuna"); -// ZodError: Non-Promise type: string - -numberPromise.parse(Promise.resolve("tuna")); -// => Promise<number> - -const test = async () => { - await numberPromise.parse(Promise.resolve("tuna")); - // ZodError: Non-number type: string - - await numberPromise.parse(Promise.resolve(3.14)); - // => 3.14 -}; -``` - -<!-- #### Non-native promise implementations - -When "parsing" a promise, Zod checks that the passed value is an object with `.then` and `.catch` methods — that's it. So you should be able to pass non-native Promises (Bluebird, etc) into `z.promise(...).parse` with no trouble. One gotcha: the return type of the parse function will be a _native_ `Promise` , so if you have downstream logic that uses non-standard Promise methods, this won't work. --> - -## Instanceof - -You can use `z.instanceof` to check that the input is an instance of a class. This is useful to validate inputs against classes that are exported from third-party libraries. - -```ts -class Test { - name: string; -} - -const TestSchema = z.instanceof(Test); - -const blob: any = "whatever"; -TestSchema.parse(new Test()); // passes -TestSchema.parse(blob); // throws -``` - -## Functions - -Zod also lets you define "function schemas". This makes it easy to validate the inputs and outputs of a function without intermixing your validation code and "business logic". - -You can create a function schema with `z.function(args, returnType)` . - -```ts -const myFunction = z.function(); - -type myFunction = z.infer<typeof myFunction>; -// => ()=>unknown -``` - -Define inputs and outputs. - -```ts -const myFunction = z - .function() - .args(z.string(), z.number()) // accepts an arbitrary number of arguments - .returns(z.boolean()); - -type myFunction = z.infer<typeof myFunction>; -// => (arg0: string, arg1: number)=>boolean -``` - -<!-- - -``` ts -const args = z.tuple([z.string()]); - -const returnType = z.number(); - -const myFunction = z.function(args, returnType); -type myFunction = z.infer<typeof myFunction>; -// => (arg0: string)=>number -``` --> - -Function schemas have an `.implement()` method which accepts a function and returns a new function that automatically validates its inputs and outputs. - -```ts -const trimmedLength = z - .function() - .args(z.string()) // accepts an arbitrary number of arguments - .returns(z.number()) - .implement((x) => { - // TypeScript knows x is a string! - return x.trim().length; - }); - -trimmedLength("sandwich"); // => 8 -trimmedLength(" asdf "); // => 4 -``` - -If you only care about validating inputs, just don't call the `.returns()` method. The output type will be inferred from the implementation. - -> You can use the special `z.void()` option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.) - -```ts -const myFunction = z - .function() - .args(z.string()) - .implement((arg) => { - return [arg.length]; - }); - -myFunction; // (arg: string)=>number[] -``` - -Extract the input and output schemas from a function schema. - -```ts -myFunction.parameters(); -// => ZodTuple<[ZodString, ZodNumber]> - -myFunction.returnType(); -// => ZodBoolean -``` - -<!-- `z.function()` accepts two arguments: - -* `args: ZodTuple` The first argument is a tuple (created with `z.tuple([...])` and defines the schema of the arguments to your function. If the function doesn't accept arguments, you can pass an empty tuple (`z.tuple([])`). -* `returnType: any Zod schema` The second argument is the function's return type. This can be any Zod schema. --> - -## Template Literals - -Building on the knowledge above, Zod supports creating typescript [template literal types](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html) with runtime validation. These types allow for stricter type checking of string inputs, as an alternative to `z.string()` which infers to a string. - -A template literal type consists of [string literal types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) and interpolated positions (typescript types inside `${}` slots, e.g. `${number}`). - -To create a template literal builder: - -```ts -const templateLiteral = z.templateLiteral(); // infers to ``. -``` - -- To add string literal types to an existing template literal: - - ```ts - templateLiteral.literal("Hello"); // infers to `Hello`. - templateLiteral.literal(3.14); // infers to `3.14`. - ``` - - This method accepts strings, numbers, booleans, nulls and undefined. - -- To add interpolated positions to an existing template literal: - - ```ts - templateLiteral.interpolated(z.string()); // infers to `${string}`. - templateLiteral.interpolated(z.number()); // infers to `${number}`. - templateLiteral.interpolated(z.boolean()); // infers to `true` | `false`. - templateLiteral.interpolated(z.literal("foo")); // infers to `foo`. - templateLiteral.interpolated(z.null()); // infers to `null`. - templateLiteral.interpolated(z.undefined()); // infers to `undefined`. - templateLiteral.interpolated(z.bigint()); // infers to `${bigint}`. - templateLiteral.interpolated(z.any()); // infers to `${any}`. - ``` - - Any Zod type (or union) with an underlying type of string, number, boolean, null, - undefined or bigint can be used as an interpolated position (template literals - included!). You can use additional built-in runtime validations (refinements - excluded) in each of these types and the template literal builder will do its - best (within the limitations of regular expressions) to support them when parsing. - -### Examples - -URL: - -```ts -const url = z - .templateLiteral() - .literal("https://") - .interpolated(z.string().min(1)) - .literal(".") - .interpolated(z.enum(["com", "net"])); -// infers to `https://${string}.com` | `https://${string}.net`. - -url.parse("https://google.com"); // passes -url.parse("https://google.net"); // passes -url.parse("http://google.com"); // throws -url.parse("https://.com"); // throws -url.parse("https://google"); // throws -url.parse("https://google."); // throws -url.parse("https://google.gov"); // throws -``` - -Measurement: - -```ts -const measurement = z.coerce - .templateLiteral() - .interpolated(z.number().finite()) - .interpolated( - z.enum(["px", "em", "rem", "vh", "vw", "vmin", "vmax"]).optional() - ); -// infers to `${number}` | `${number}px` | `${number}em` | `${number}rem` | `${number}vh` | `${number}vw` | `${number}vmin` | `${number}vmax -``` - -MongoDB connection string: - -```ts -const connectionString = z - .templateLiteral() - .literal("mongodb://") - .interpolated( - z - .templateLiteral() - .interpolated(z.string().regex(/\w+/).describe("username")) - .literal(":") - .interpolated(z.string().regex(/\w+/).describe("password")) - .literal("@") - .optional() - ) - .interpolated(z.string().regex(/\w+/).describe("host")) - .literal(":") - .interpolated(z.number().finite().int().positive().describe("port")) - .interpolated( - z - .templateLiteral() - .literal("/") - .interpolated( - z.string().regex(/\w+/).optional().describe("defaultauthdb") - ) - .interpolated( - z - .templateLiteral() - .literal("?") - .interpolated(z.string().regex(/^\w+=\w+(&\w+=\w+)*$/)) - .optional() - .describe("options") - ) - .optional() - ); -// infers to: -// | `mongodb://${string}:${number}` -// | `mongodb://${string}:${number}/${string}` -// | `mongodb://${string}:${number}/${string}?${string}` -// | `mongodb://${string}:${string}@${string}:${number}` -// | `mongodb://${string}:${string}@${string}:${number}/${string}` -// | `mongodb://${string}:${string}@${string}:${number}/${string}?${string}` -``` - -## Preprocess - -> Zod now supports primitive coercion without the need for `.preprocess()`. See the [coercion docs](#coercion-for-primitives) for more information. - -Typically Zod operates under a "parse then transform" paradigm. Zod validates the input first, then passes it through a chain of transformation functions. (For more information about transforms, read the [.transform docs](#transform).) - -But sometimes you want to apply some transform to the input _before_ parsing happens. A common use case: type coercion. Zod enables this with the `z.preprocess()`. - -```ts -const castToString = z.preprocess((val) => String(val), z.string()); -``` - -This returns a `ZodEffects` instance. `ZodEffects` is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms. - -## Custom schemas - -You can create a Zod schema for any TypeScript type by using `z.custom()`. This is useful for creating schemas for types that are not supported by Zod out of the box, such as template string literals. - -```ts -const px = z.custom<`${number}px`>((val) => { - return typeof val === "string" ? /^\d+px$/.test(val) : false; -}); - -type px = z.infer<typeof px>; // `${number}px` - -px.parse("42px"); // "42px" -px.parse("42vw"); // throws; -``` - -If you don't provide a validation function, Zod will allow any value. This can be dangerous! - -```ts -z.custom<{ arg: string }>(); // performs no validation -``` - -You can customize the error message and other options by passing a second argument. This parameter works the same way as the params parameter of [`.refine`](#refine). - -```ts -z.custom<...>((val) => ..., "custom error message"); -``` - -## Schema methods - -All Zod schemas contain certain methods. - -### `.parse` - -`.parse(data: unknown): T` - -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: The value returned by `.parse` is a _deep clone_ of the variable you passed in. - -```ts -const stringSchema = z.string(); - -stringSchema.parse("fish"); // => returns "fish" -stringSchema.parse(12); // throws error -``` - -### `.parseAsync` - -`.parseAsync(data:unknown): Promise<T>` - -If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync`. - -```ts -const stringSchema = z.string().refine(async (val) => val.length <= 8); - -await stringSchema.parseAsync("hello"); // => returns "hello" -await stringSchema.parseAsync("hello world"); // => throws error -``` - -### `.safeParse` - -`.safeParse(data:unknown): { success: true; data: T; } | { success: false; error: ZodError; }` - -If you don't want Zod to throw errors when validation fails, use `.safeParse`. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems. - -```ts -stringSchema.safeParse(12); -// => { success: false; error: ZodError } - -stringSchema.safeParse("billie"); -// => { success: true; data: 'billie' } -``` - -The result is a _discriminated union_, so you can handle errors very conveniently: - -```ts -const result = stringSchema.safeParse("billie"); -if (!result.success) { - // handle error then return - result.error; -} else { - // do something - result.data; -} -``` - -### `.safeParseAsync` - -> Alias: `.spa` - -An asynchronous version of `safeParse`. - -```ts -await stringSchema.safeParseAsync("billie"); -``` - -For convenience, this has been aliased to `.spa`: - -```ts -await stringSchema.spa("billie"); -``` - -### `.refine` - -`.refine(validator: (data:T)=>any, params?: RefineParams)` - -Zod lets you provide custom validation logic via _refinements_. (For advanced features like creating multiple issues and customizing error codes, see [`.superRefine`](#superrefine).) - -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 integer or that a string is a valid email address. - -For example, you can define a custom validation check on _any_ Zod schema with `.refine` : - -```ts -const myString = z.string().refine((val) => val.length <= 255, { - message: "String can't be more than 255 characters", -}); -``` - -> ⚠️ Refinement functions should not throw. Instead they should return a falsy value to signal failure. - -#### Arguments - -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 accepts some options. You can use this to customize certain error-handling behavior: - -```ts -type RefineParams = { - // override error message - message?: string; - - // appended to error path - path?: (string | number)[]; - - // params object you can use to customize message - // in error map - params?: object; -}; -``` - -For advanced cases, the second argument can also be a function that returns `RefineParams`. - -```ts -const longString = z.string().refine( - (val) => val.length > 10, - (val) => ({ message: `${val} is not more than 10 characters` }) -); -``` - -#### Customize error path - -```ts -const passwordForm = z - .object({ - password: z.string(), - confirm: z.string(), - }) - .refine((data) => data.password === data.confirm, { - message: "Passwords don't match", - path: ["confirm"], // path of error - }); - -passwordForm.parse({ password: "asdf", confirm: "qwer" }); -``` - -Because you provided a `path` parameter, the resulting error will be: - -```ts -ZodError { - issues: [{ - "code": "custom", - "path": [ "confirm" ], - "message": "Passwords don't match" - }] -} -``` - -#### Asynchronous refinements - -Refinements can also be async: - -```ts -const userId = z.string().refine(async (id) => { - // verify that ID exists in database - return true; -}); -``` - -> ⚠️ If you use async refinements, you must use the `.parseAsync` method to parse data! Otherwise Zod will throw an error. - -#### Relationship to transforms - -Transforms and refinements can be interleaved: - -```ts -z.string() - .transform((val) => val.length) - .refine((val) => val > 25); -``` - -<!-- Note that the `path` is set to `["confirm"]` , so you can easily display this error underneath the "Confirm password" textbox. - -```ts -const allForms = z.object({ passwordForm }).parse({ - passwordForm: { - password: "asdf", - confirm: "qwer", - }, -}); -``` - -would result in - -``` - -ZodError { - issues: [{ - "code": "custom", - "path": [ "passwordForm", "confirm" ], - "message": "Passwords don't match" - }] -} -``` --> - -### `.superRefine` - -The `.refine` method is actually syntactic sugar atop a more versatile (and verbose) method called `superRefine`. Here's an example: - -```ts -const Strings = z.array(z.string()).superRefine((val, ctx) => { - if (val.length > 3) { - ctx.addIssue({ - code: z.ZodIssueCode.too_big, - maximum: 3, - type: "array", - inclusive: true, - message: "Too many items 😡", - }); - } - - if (val.length !== new Set(val).size) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: `No duplicates allowed.`, - }); - } -}); -``` - -You can add as many issues as you like. If `ctx.addIssue` is _not_ called during the execution of the function, validation passes. - -Normally refinements always create issues with a `ZodIssueCode.custom` error code, but with `superRefine` it's possible to throw issues of any `ZodIssueCode`. Each issue code is described in detail in the Error Handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md). - -#### Abort early - -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`. - -```ts -const schema = z.number().superRefine((val, ctx) => { - if (val < 10) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "should be >= 10", - fatal: true, - }); - - return z.NEVER; - } - - if (val !== 12) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "should be twelve", - }); - } -}); -``` - -#### Type refinements - -If you provide a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) to `.refine()` or `.superRefine()`, the resulting type will be narrowed down to your predicate's type. This is useful if you are mixing multiple chained refinements and transformations: - -```ts -const schema = z - .object({ - first: z.string(), - second: z.number(), - }) - .nullable() - .superRefine((arg, ctx): arg is { first: string; second: number } => { - if (!arg) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, // customize your issue - message: "object should exist", - }); - } - - return z.NEVER; // The return value is not used, but we need to return something to satisfy the typing - }) - // here, TS knows that arg is not null - .refine((arg) => arg.first === "bob", "`first` is not `bob`!"); -``` - -> ⚠️ You **must** use `ctx.addIssue()` instead of returning a boolean value to indicate whether the validation passes. If `ctx.addIssue` is _not_ called during the execution of the function, validation passes. - -### `.transform` - -To transform data after parsing, use the `transform` method. - -```ts -const stringToNumber = z.string().transform((val) => val.length); - -stringToNumber.parse("string"); // => 6 -``` - -#### Chaining order - -Note that `stringToNumber` above is an instance of the `ZodEffects` subclass. It is NOT an instance of `ZodString`. If you want to use the built-in methods of `ZodString` (e.g. `.email()`) you must apply those methods _before_ any transforms. - -```ts -const emailToDomain = z - .string() - .email() - .transform((val) => val.split("@")[1]); - -emailToDomain.parse("colinhacks@example.com"); // => example.com -``` - -#### Validating during transform - -The `.transform` method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining `transform` and `refine`. - -As with `.superRefine`, the transform function receives a `ctx` object with an `addIssue` method that can be used to register validation issues. - -```ts -const numberInString = z.string().transform((val, ctx) => { - const parsed = parseInt(val); - if (isNaN(parsed)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "Not a number", - }); - - // This is a special symbol you can use to - // return early from the transform function. - // It has type `never` so it does not affect the - // inferred return type. - return z.NEVER; - } - return parsed; -}); -``` - -#### Relationship to refinements - -Transforms and refinements can be interleaved. These will be executed in the order they are declared. - -```ts -const nameToGreeting = z - .string() - .transform((val) => val.toUpperCase()) - .refine((val) => val.length > 15) - .transform((val) => `Hello ${val}`) - .refine((val) => val.indexOf("!") === -1); -``` - -#### Async transforms - -Transforms can also be async. - -```ts -const IdToUser = z - .string() - .uuid() - .transform(async (id) => { - return await getUserById(id); - }); -``` - -> ⚠️ If your schema contains asynchronous transforms, you must use .parseAsync() or .safeParseAsync() to parse data. Otherwise Zod will throw an error. - -### `.default` - -You can use transforms to implement the concept of "default values" in Zod. - -```ts -const stringWithDefault = z.string().default("tuna"); - -stringWithDefault.parse(undefined); // => "tuna" -``` - -Optionally, you can pass a function into `.default` that will be re-executed whenever a default value needs to be generated: - -```ts -const numberWithRandomDefault = z.number().default(Math.random); - -numberWithRandomDefault.parse(undefined); // => 0.4413456736055323 -numberWithRandomDefault.parse(undefined); // => 0.1871840107401901 -numberWithRandomDefault.parse(undefined); // => 0.7223408162401552 -``` - -Conceptually, this is how Zod processes default values: - -1. If the input is `undefined`, the default value is returned -2. Otherwise, the data is parsed using the base schema - -### `.describe` - -Use `.describe()` to add a `description` property to the resulting schema. - -```ts -const documentedString = z - .string() - .describe("A useful bit of text, if you know what to do with it."); -documentedString.description; // A useful bit of text… -``` - -This can be useful for documenting a field, for example in a JSON Schema using a library like [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema)). - -### `.catch` - -Use `.catch()` to provide a "catch value" to be returned in the event of a parsing error. - -```ts -const numberWithCatch = z.number().catch(42); - -numberWithCatch.parse(5); // => 5 -numberWithCatch.parse("tuna"); // => 42 -``` - -Optionally, you can pass a function into `.catch` that will be re-executed whenever a default value needs to be generated. A `ctx` object containing the caught error will be passed into this function. - -```ts -const numberWithRandomCatch = z.number().catch((ctx) => { - ctx.error; // the caught ZodError - return Math.random(); -}); - -numberWithRandomCatch.parse("sup"); // => 0.4413456736055323 -numberWithRandomCatch.parse("sup"); // => 0.1871840107401901 -numberWithRandomCatch.parse("sup"); // => 0.7223408162401552 -``` - -Conceptually, this is how Zod processes "catch values": - -1. The data is parsed using the base schema -2. If the parsing fails, the "catch value" is returned - -### `.optional` - -A convenience method that returns an optional version of a schema. - -```ts -const optionalString = z.string().optional(); // string | undefined - -// equivalent to -z.optional(z.string()); -``` - -### `.nullable` - -A convenience method that returns a nullable version of a schema. - -```ts -const nullableString = z.string().nullable(); // string | null - -// equivalent to -z.nullable(z.string()); -``` - -### `.nullish` - -A convenience method that returns a "nullish" version of a schema. Nullish schemas will accept both `undefined` and `null`. Read more about the concept of "nullish" [in the TypeScript 3.7 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing). - -```ts -const nullishString = z.string().nullish(); // string | null | undefined - -// equivalent to -z.string().nullable().optional(); -``` - -### `.array` - -A convenience method that returns an array schema for the given type: - -```ts -const stringArray = z.string().array(); // string[] - -// equivalent to -z.array(z.string()); -``` - -### `.promise` - -A convenience method for promise types: - -```ts -const stringPromise = z.string().promise(); // Promise<string> - -// equivalent to -z.promise(z.string()); -``` - -### `.or` - -A convenience method for [union types](#unions). - -```ts -const stringOrNumber = z.string().or(z.number()); // string | number - -// equivalent to -z.union([z.string(), z.number()]); -``` - -### `.and` - -A convenience method for creating intersection types. - -```ts -const nameAndAge = z - .object({ name: z.string() }) - .and(z.object({ age: z.number() })); // { name: string } & { age: number } - -// equivalent to -z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() })); -``` - -### `.brand` - -`.brand<T>() => ZodBranded<this, B>` - -TypeScript's type system is structural, which means that any two types that are structurally equivalent are considered the same. - -```ts -type Cat = { name: string }; -type Dog = { name: string }; - -const petCat = (cat: Cat) => {}; -const fido: Dog = { name: "fido" }; -petCat(fido); // works fine -``` - -In some cases, its can be desirable to simulate _nominal typing_ inside TypeScript. For instance, you may wish to write a function that only accepts an input that has been validated by Zod. This can be achieved with _branded types_ (AKA _opaque types_). - -```ts -const Cat = z.object({ name: z.string() }).brand<"Cat">(); -type Cat = z.infer<typeof Cat>; - -const petCat = (cat: Cat) => {}; - -// this works -const simba = Cat.parse({ name: "simba" }); -petCat(simba); - -// this doesn't -petCat({ name: "fido" }); -``` - -Under the hood, this works by attaching a "brand" to the inferred type using an intersection type. This way, plain/unbranded data structures are no longer assignable to the inferred type of the schema. - -```ts -const Cat = z.object({ name: z.string() }).brand<"Cat">(); -type Cat = z.infer<typeof Cat>; -// {name: string} & {[symbol]: "Cat"} -``` - -Note that branded types do not affect the runtime result of `.parse`. It is a static-only construct. - -### `.readonly` - -`.readonly() => ZodReadonly<this>` - -This method returns a `ZodReadonly` schema instance that parses the input using the base schema, then calls `Object.freeze()` on the result. The inferred type is also marked as `readonly`. - -```ts -const schema = z.object({ name: string }).readonly(); -type schema = z.infer<typeof schema>; -// Readonly<{name: string}> - -const result = schema.parse({ name: "fido" }); -result.name = "simba"; // error -``` - -The inferred type uses TypeScript's built-in readonly types when relevant. - -```ts -z.array(z.string()).readonly(); -// readonly string[] - -z.tuple([z.string(), z.number()]).readonly(); -// readonly [string, number] - -z.map(z.string(), z.date()).readonly(); -// ReadonlyMap<string, Date> - -z.set(z.string()).readonly(); -// ReadonlySet<Promise<string>> -``` - -### `.pipe` - -Schemas can be chained into validation "pipelines". It's useful for easily validating the result after a `.transform()`: - -```ts -z.string() - .transform((val) => val.length) - .pipe(z.number().min(5)); -``` - -The `.pipe()` method returns a `ZodPipeline` instance. - -#### You can use `.pipe()` to fix common issues with `z.coerce`. - -You can constrain the input to types that work well with your chosen coercion. Then use `.pipe()` to apply the coercion. - -without constrained input: - -```ts -const toDate = z.coerce.date(); - -// works intuitively -console.log(toDate.safeParse("2023-01-01").success); // true - -// might not be what you want -console.log(toDate.safeParse(null).success); // true -``` - -with constrained input: - -```ts -const datelike = z.union([z.number(), z.string(), z.date()]); -const datelikeToDate = datelike.pipe(z.coerce.date()); - -// still works intuitively -console.log(datelikeToDate.safeParse("2023-01-01").success); // true - -// more likely what you want -console.log(datelikeToDate.safeParse(null).success); // false -``` - -You can also use this technique to avoid coercions that throw uncaught errors. - -without constrained input: - -```ts -const toBigInt = z.coerce.bigint(); - -// works intuitively -console.log(toBigInt.safeParse("42")); // true - -// probably not what you want -console.log(toBigInt.safeParse(null)); // throws uncaught error -``` - -with constrained input: - -```ts -const toNumber = z.number().or(z.string()).pipe(z.coerce.number()); -const toBigInt = z.bigint().or(toNumber).pipe(z.coerce.bigint()); - -// still works intuitively -console.log(toBigInt.safeParse("42").success); // true - -// error handled by zod, more likely what you want -console.log(toBigInt.safeParse(null).success); // false -``` - -## Guides and concepts - -### Type inference - -You can extract the TypeScript type of any schema with `z.infer<typeof mySchema>` . - -```ts -const A = z.string(); -type A = z.infer<typeof A>; // string - -const u: A = 12; // TypeError -const u: A = "asdf"; // compiles -``` - -**What about transforms?** - -In reality each Zod schema internally tracks **two** types: an input and an output. For most schemas (e.g. `z.string()`) these two are the same. But once you add transforms into the mix, these two values can diverge. For instance `z.string().transform(val => val.length)` has an input of `string` and an output of `number`. - -You can separately extract the input and output types like so: - -```ts -const stringToNumber = z.string().transform((val) => val.length); - -// ⚠️ Important: z.infer returns the OUTPUT type! -type input = z.input<typeof stringToNumber>; // string -type output = z.output<typeof stringToNumber>; // number - -// equivalent to z.output! -type inferred = z.infer<typeof stringToNumber>; // number -``` - -### Writing generic functions - -With TypeScript generics, you can write reusable functions that accept Zod schemas as parameters. This enables you to create custom validation logic, schema transformations, and more, while maintaining type safety and inference. - -When attempting to write a function that accepts a Zod schema as an input, it's tempting to try something like this: - -```ts -function inferSchema<T>(schema: z.ZodType<T>) { - return schema; -} -``` - -This approach is incorrect, and limits TypeScript's ability to properly infer the argument. No matter what you pass in, the type of `schema` will be an instance of `ZodType`. - -```ts -inferSchema(z.string()); -// => ZodType<string> -``` - -This approach loses type information, namely _which subclass_ the input actually is (in this case, `ZodString`). That means you can't call any string-specific methods like `.min()` on the result of `inferSchema`. - -A better approach is to infer _the schema as a whole_ instead of merely its inferred type. You can do this with a utility type called `z.ZodTypeAny`. - -```ts -function inferSchema<T extends z.ZodTypeAny>(schema: T) { - return schema; -} - -inferSchema(z.string()); -// => ZodString -``` - -> `ZodTypeAny` is just a shorthand for `ZodType<any, any, any>`, a type that is broad enough to match any Zod schema. - -The Result is now fully and properly typed, and the type system can infer the specific subclass of the schema. - -#### Inferring the inferred type - -If you follow the best practice of using `z.ZodTypeAny` as the generic parameter for your schema, you may encounter issues with the parsed data being typed as `any` instead of the inferred type of the schema. - -```ts -function parseData<T extends z.ZodTypeAny>(data: unknown, schema: T) { - return schema.parse(data); -} - -parseData("sup", z.string()); -// => any -``` - -Due to how TypeScript inference works, it is treating `schema` like a `ZodTypeAny` instead of the inferred type. You can fix this with a type cast using `z.infer`. - -```ts -function parseData<T extends z.ZodTypeAny>(data: unknown, schema: T) { - return schema.parse(data) as z.infer<T>; - // ^^^^^^^^^^^^^^ <- add this -} - -parseData("sup", z.string()); -// => string -``` - -#### Constraining allowable inputs - -The `ZodType` class has three generic parameters. - -```ts -class ZodType< - Output = any, - Def extends ZodTypeDef = ZodTypeDef, - Input = Output -> { ... } -``` - -By constraining these in your generic input, you can limit what schemas are allowable as inputs to your function: - -```ts -function makeSchemaOptional<T extends z.ZodType<string>>(schema: T) { - return schema.optional(); -} - -makeSchemaOptional(z.string()); -// works fine - -makeSchemaOptional(z.number()); -// Error: 'ZodNumber' is not assignable to parameter of type 'ZodType<string, ZodTypeDef, string>' -``` - -### Error handling - -Zod provides a subclass of Error called `ZodError`. ZodErrors contain an `issues` array containing detailed information about the validation problems. - -```ts -const result = z - .object({ - name: z.string(), - }) - .safeParse({ name: 12 }); - -if (!result.success) { - result.error.issues; - /* [ - { - "code": "invalid_type", - "expected": "string", - "received": "number", - "path": [ "name" ], - "message": "Expected string, received number" - } - ] */ -} -``` - -> For detailed information about the possible error codes and how to customize error messages, check out the dedicated error handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md) - -Zod's error reporting emphasizes _completeness_ and _correctness_. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third-party library like [`zod-validation-error`](https://github.com/causaly/zod-validation-error) - -### Error formatting - -You can use the `.format()` method to convert this error into a nested object. - -```ts -const result = z - .object({ - name: z.string(), - }) - .safeParse({ name: 12 }); - -if (!result.success) { - const formatted = result.error.format(); - /* { - name: { _errors: [ 'Expected string, received number' ] } - } */ - - formatted.name?._errors; - // => ["Expected string, received number"] -} -``` - -## Comparison - -There are a handful of other widely-used validation libraries, but all of them have certain design limitations that make for a non-ideal developer experience. - -<!-- 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/colinhacks) | [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 custom 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 --> - -<!-- - Missing object methods: (pick, omit, partial, deepPartial, merge, extend) - -* Missing nonempty arrays with proper typing (`[T, ...T[]]`) -* Missing lazy/recursive types -* Missing promise schemas -* Missing function schemas -* Missing union & intersection schemas -* Missing support for parsing cyclical data (maybe) -* Missing error customization --> - -### Joi - -[https://github.com/hapijs/joi](https://github.com/hapijs/joi) - -Doesn't support static type inference 😕 - -### Yup - -[https://github.com/jquense/yup](https://github.com/jquense/yup) - -Yup is a full-featured library that was implemented first in vanilla JS, and later rewritten in TypeScript. - -- Supports casting and transforms -- All object fields are optional by default -<!-- - Missing nonempty arrays with proper typing (`[T, ...T[]]`) --> -- Missing promise schemas -- Missing function schemas -- Missing union & intersection schemas - -<!-- ¹Yup has a strange interpretation of the word `required`. Instead of meaning "not undefined", Yup uses it to mean "not empty". So `yup.string().required()` will not accept an empty string, and `yup.array(yup.string()).required()` will not accept an empty array. Instead, Yup us Zod arrays there is a dedicated `.nonempty()` method to indicate this, or you can implement it with a custom refinement. --> - -### io-ts - -[https://github.com/gcanti/io-ts](https://github.com/gcanti/io-ts) - -io-ts is an excellent library by gcanti. The API of io-ts heavily inspired the design of Zod. - -In our experience, io-ts prioritizes functional programming purity over developer experience in many cases. This is a valid and admirable design goal, but it makes io-ts particularly hard to integrate into an existing codebase with a more procedural or object-oriented bias. For instance, consider how to define an object with optional properties in io-ts: - -```ts -import * as t from "io-ts"; - -const A = t.type({ - foo: t.string, -}); - -const B = t.partial({ - bar: t.number, -}); - -const C = t.intersection([A, B]); - -type C = t.TypeOf<typeof C>; -// returns { foo: string; bar?: number | undefined } -``` - -You must define the required and optional props in separate object validators, pass the optionals through `t.partial` (which marks all properties as optional), then combine them with `t.intersection` . - -Consider the equivalent in Zod: - -```ts -const C = z.object({ - foo: z.string(), - bar: z.number().optional(), -}); - -type C = z.infer<typeof C>; -// returns { foo: string; bar?: number | undefined } -``` - -This more declarative API makes schema definitions vastly more concise. - -`io-ts` also requires the use of gcanti's functional programming library `fp-ts` to parse results and handle errors. This is another fantastic resource for developers looking to keep their codebase strictly functional. But depending on `fp-ts` necessarily comes with a lot of intellectual overhead; a developer has to be familiar with functional programming concepts and the `fp-ts` nomenclature to use the library. - -- Supports codecs with serialization & deserialization transforms -- Supports branded types -- Supports advanced functional programming, higher-kinded types, `fp-ts` compatibility -- Missing object methods: (pick, omit, partial, deepPartial, merge, extend) -- Missing nonempty arrays with proper typing (`[T, ...T[]]`) -- Missing promise schemas -- Missing function schemas - -### Runtypes - -[https://github.com/pelotom/runtypes](https://github.com/pelotom/runtypes) - -Good type inference support. - -- Supports "pattern matching": computed properties that distribute over unions -- Missing object methods: (deepPartial, merge) -- Missing nonempty arrays with proper typing (`[T, ...T[]]`) -- Missing promise schemas -- Missing error customization - -### Ow - -[https://github.com/sindresorhus/ow](https://github.com/sindresorhus/ow) - -Ow is focused on function input validation. It's a library that makes it easy to express complicated assert statements, but it doesn't let you parse untyped data. They support a much wider variety of types; Zod has a nearly one-to-one mapping with TypeScript's type system, whereas ow lets you validate several highly-specific types out of the box (e.g. `int32Array` , see full list in their README). - -If you want to validate function inputs, use function schemas in Zod! It's a much simpler approach that lets you reuse a function type declaration without repeating yourself (namely, copy-pasting a bunch of ow assertions at the beginning of every function). Also Zod lets you validate your return types as well, so you can be sure there won't be any unexpected data passed downstream. - -## Changelog - -View the changelog at [CHANGELOG.md](CHANGELOG.md) diff --git a/deno/lib/ZodError.ts b/deno/lib/ZodError.ts deleted file mode 100644 index cfbaeadf0..000000000 --- a/deno/lib/ZodError.ts +++ /dev/null @@ -1,366 +0,0 @@ -import type { TypeOf, ZodFirstPartyTypeKind, ZodType } from "./index.ts"; -import { Primitive } from "./helpers/typeAliases.ts"; -import { util, ZodParsedType } from "./helpers/util.ts"; - -type allKeys<T> = T extends any ? keyof T : never; - -export type inferFlattenedErrors< - T extends ZodType<any, any, any>, - U = string -> = typeToFlattenedError<TypeOf<T>, U>; -export type typeToFlattenedError<T, U = string> = { - formErrors: U[]; - fieldErrors: { - [P in allKeys<T>]?: U[]; - }; -}; - -export const ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite", -]); - -export type ZodIssueCode = keyof typeof ZodIssueCode; - -export type ZodIssueBase = { - path: (string | number)[]; - message?: string; -}; - -export interface ZodInvalidTypeIssue extends ZodIssueBase { - code: typeof ZodIssueCode.invalid_type; - expected: ZodParsedType; - received: ZodParsedType; -} - -export interface ZodInvalidLiteralIssue extends ZodIssueBase { - code: typeof ZodIssueCode.invalid_literal; - expected: unknown; - received: unknown; -} - -export interface ZodUnrecognizedKeysIssue extends ZodIssueBase { - code: typeof ZodIssueCode.unrecognized_keys; - keys: string[]; -} - -export interface ZodInvalidUnionIssue extends ZodIssueBase { - code: typeof ZodIssueCode.invalid_union; - unionErrors: ZodError[]; -} - -export interface ZodInvalidUnionDiscriminatorIssue extends ZodIssueBase { - code: typeof ZodIssueCode.invalid_union_discriminator; - options: Primitive[]; -} - -export interface ZodInvalidEnumValueIssue extends ZodIssueBase { - received: string | number; - code: typeof ZodIssueCode.invalid_enum_value; - options: (string | number)[]; -} - -export interface ZodInvalidArgumentsIssue extends ZodIssueBase { - code: typeof ZodIssueCode.invalid_arguments; - argumentsError: ZodError; -} - -export interface ZodInvalidReturnTypeIssue extends ZodIssueBase { - code: typeof ZodIssueCode.invalid_return_type; - returnTypeError: ZodError; -} - -export interface ZodInvalidDateIssue extends ZodIssueBase { - code: typeof ZodIssueCode.invalid_date; -} - -export type StringValidation = - | "email" - | "url" - | "emoji" - | "uuid" - | "regex" - | "cuid" - | "cuid2" - | "ulid" - | "datetime" - | "ip" - | { includes: string; position?: number } - | { startsWith: string } - | { endsWith: string }; - -export interface ZodInvalidStringIssue extends ZodIssueBase { - code: typeof ZodIssueCode.invalid_string; - validation: StringValidation; -} - -export interface ZodTooSmallIssue extends ZodIssueBase { - code: typeof ZodIssueCode.too_small; - minimum: number | bigint; - inclusive: boolean; - exact?: boolean; - type: "array" | "string" | "number" | "set" | "date" | "bigint"; -} - -export interface ZodTooBigIssue extends ZodIssueBase { - code: typeof ZodIssueCode.too_big; - maximum: number | bigint; - inclusive: boolean; - exact?: boolean; - type: "array" | "string" | "number" | "set" | "date" | "bigint"; -} - -export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase { - code: typeof ZodIssueCode.invalid_intersection_types; -} - -export interface ZodNotMultipleOfIssue extends ZodIssueBase { - code: typeof ZodIssueCode.not_multiple_of; - multipleOf: number | bigint; -} - -export interface ZodNotFiniteIssue extends ZodIssueBase { - code: typeof ZodIssueCode.not_finite; -} - -export interface ZodCustomIssue extends ZodIssueBase { - code: typeof ZodIssueCode.custom; - params?: { [k: string]: any }; -} - -export type DenormalizedError = { [k: string]: DenormalizedError | string[] }; - -export type ZodIssueOptionalMessage = - | ZodInvalidTypeIssue - | ZodInvalidLiteralIssue - | ZodUnrecognizedKeysIssue - | ZodInvalidUnionIssue - | ZodInvalidUnionDiscriminatorIssue - | ZodInvalidEnumValueIssue - | ZodInvalidArgumentsIssue - | ZodInvalidReturnTypeIssue - | ZodInvalidDateIssue - | ZodInvalidStringIssue - | ZodTooSmallIssue - | ZodTooBigIssue - | ZodInvalidIntersectionTypesIssue - | ZodNotMultipleOfIssue - | ZodNotFiniteIssue - | ZodCustomIssue; - -export type ZodIssue = ZodIssueOptionalMessage & { - fatal?: boolean; - message: string; -}; - -export const quotelessJson = (obj: any) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; - -type recursiveZodFormattedError<T> = T extends [any, ...any[]] - ? { [K in keyof T]?: ZodFormattedError<T[K]> } - : T extends any[] - ? { [k: number]: ZodFormattedError<T[number]> } - : T extends object - ? { [K in keyof T]?: ZodFormattedError<T[K]> } - : unknown; - -export type ZodFormattedError<T, U = string> = { - _errors: U[]; -} & recursiveZodFormattedError<NonNullable<T>>; - -export type inferFormattedError< - T extends ZodType<any, any, any>, - U = string -> = ZodFormattedError<TypeOf<T>, U>; - -export class ZodError<T = any> extends Error { - issues: ZodIssue[] = []; - - get errors() { - return this.issues; - } - - constructor(issues: ZodIssue[]) { - super(); - - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - // eslint-disable-next-line ban/ban - Object.setPrototypeOf(this, actualProto); - } else { - (this as any).__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - - format(): ZodFormattedError<T>; - format<U>(mapper: (issue: ZodIssue) => U): ZodFormattedError<T, U>; - format(_mapper?: any) { - const mapper: (issue: ZodIssue) => any = - _mapper || - function (issue: ZodIssue) { - return issue.message; - }; - const fieldErrors: ZodFormattedError<T> = { _errors: [] } as any; - const processError = (error: ZodError) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - (fieldErrors as any)._errors.push(mapper(issue)); - } else { - let curr: any = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - // if (typeof el === "string") { - // curr[el] = curr[el] || { _errors: [] }; - // } else if (typeof el === "number") { - // const errorArray: any = []; - // errorArray._errors = []; - // curr[el] = curr[el] || errorArray; - // } - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - - curr = curr[el]; - i++; - } - } - } - }; - - processError(this); - return fieldErrors; - } - - static create = (issues: ZodIssue[]) => { - const error = new ZodError(issues); - return error; - }; - - static assert(value: unknown): asserts value is ZodError { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); - } - - get isEmpty(): boolean { - return this.issues.length === 0; - } - - addIssue = (sub: ZodIssue) => { - this.issues = [...this.issues, sub]; - }; - - addIssues = (subs: ZodIssue[] = []) => { - this.issues = [...this.issues, ...subs]; - }; - - flatten(): typeToFlattenedError<T>; - flatten<U>(mapper?: (issue: ZodIssue) => U): typeToFlattenedError<T, U>; - flatten<U = string>( - mapper: (issue: ZodIssue) => U = (issue: ZodIssue) => issue.message as any - ): any { - const fieldErrors: any = {}; - const formErrors: U[] = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - - get formErrors() { - return this.flatten(); - } -} - -type stripPath<T extends object> = T extends any - ? util.OmitKeys<T, "path"> - : never; - -export type IssueData = stripPath<ZodIssueOptionalMessage> & { - path?: (string | number)[]; - fatal?: boolean; -}; - -export type ErrorMapCtx = { - defaultError: string; - data: any; -}; - -export type ZodErrorMap = ( - issue: ZodIssueOptionalMessage, - _ctx: ErrorMapCtx -) => { message: string }; - -export class ZodTemplateLiteralUnsupportedTypeError extends Error { - constructor() { - super("Unsupported zod type!"); - - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - // eslint-disable-next-line ban/ban - Object.setPrototypeOf(this, actualProto); - } else { - (this as any).__proto__ = actualProto; - } - this.name = "ZodTemplateLiteralUnsupportedTypeError"; - } -} - -export class ZodTemplateLiteralUnsupportedCheckError extends Error { - constructor(typeKind: ZodFirstPartyTypeKind, check: string) { - super( - `${typeKind}'s "${check}" check is not supported in template literals!` - ); - - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - // eslint-disable-next-line ban/ban - Object.setPrototypeOf(this, actualProto); - } else { - (this as any).__proto__ = actualProto; - } - this.name = "ZodTemplateLiteralUnsupportedCheckError"; - } -} diff --git a/deno/lib/__tests__/Mocker.ts b/deno/lib/__tests__/Mocker.ts deleted file mode 100644 index 5aaf84bcd..000000000 --- a/deno/lib/__tests__/Mocker.ts +++ /dev/null @@ -1,54 +0,0 @@ -function getRandomInt(max: number) { - return Math.floor(Math.random() * Math.floor(max)); -} - -const testSymbol = Symbol("test"); - -export class Mocker { - pick = (...args: any[]) => { - return args[getRandomInt(args.length)]; - }; - - get string() { - return Math.random().toString(36).substring(7); - } - get number() { - return Math.random() * 100; - } - get bigint() { - return BigInt(Math.floor(Math.random() * 10000)); - } - get boolean() { - return Math.random() < 0.5; - } - get date() { - return new Date(Math.floor(Date.now() * Math.random())); - } - get symbol() { - return testSymbol; - } - get null(): null { - return null; - } - get undefined(): undefined { - return undefined; - } - get stringOptional() { - return this.pick(this.string, this.undefined); - } - get stringNullable() { - return this.pick(this.string, this.null); - } - get numberOptional() { - return this.pick(this.number, this.undefined); - } - get numberNullable() { - return this.pick(this.number, this.null); - } - get booleanOptional() { - return this.pick(this.boolean, this.undefined); - } - get booleanNullable() { - return this.pick(this.boolean, this.null); - } -} diff --git a/deno/lib/__tests__/all-errors.test.ts b/deno/lib/__tests__/all-errors.test.ts deleted file mode 100644 index 7e69248ab..000000000 --- a/deno/lib/__tests__/all-errors.test.ts +++ /dev/null @@ -1,177 +0,0 @@ -// @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"; - -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()]) })), -}); -type TestFlattenedErrors = z.inferFlattenedErrors< - typeof Test, - { message: string; code: number } ->; -type TestFormErrors = z.inferFlattenedErrors<typeof Test>; - -test("default flattened errors type inference", () => { - type TestTypeErrors = { - formErrors: string[]; - fieldErrors: { [P in keyof z.TypeOf<typeof Test>]?: string[] | undefined }; - }; - - util.assertEqual<z.inferFlattenedErrors<typeof Test>, TestTypeErrors>(true); - util.assertEqual< - z.inferFlattenedErrors<typeof Test, { message: string }>, - TestTypeErrors - >(false); -}); - -test("custom flattened errors type inference", () => { - type ErrorType = { message: string; code: number }; - type TestTypeErrors = { - formErrors: ErrorType[]; - fieldErrors: { - [P in keyof z.TypeOf<typeof Test>]?: ErrorType[] | undefined; - }; - }; - - util.assertEqual<z.inferFlattenedErrors<typeof Test>, TestTypeErrors>(false); - util.assertEqual< - z.inferFlattenedErrors<typeof Test, { message: string; code: number }>, - TestTypeErrors - >(true); - util.assertEqual< - z.inferFlattenedErrors<typeof Test, { message: string }>, - TestTypeErrors - >(false); -}); - -test("form errors type inference", () => { - type TestTypeErrors = { - formErrors: string[]; - fieldErrors: { [P in keyof z.TypeOf<typeof Test>]?: string[] | undefined }; - }; - - util.assertEqual<z.inferFlattenedErrors<typeof Test>, TestTypeErrors>(true); -}); - -test(".flatten() type assertion", () => { - const parsed = Test.safeParse({}) as z.SafeParseError<void>; - const validFlattenedErrors: TestFlattenedErrors = parsed.error.flatten( - () => ({ message: "", code: 0 }) - ); - // @ts-expect-error should fail assertion between `TestFlattenedErrors` and unmapped `flatten()`. - const invalidFlattenedErrors: TestFlattenedErrors = parsed.error.flatten(); - const validFormErrors: TestFormErrors = parsed.error.flatten(); - // @ts-expect-error should fail assertion between `TestFormErrors` and mapped `flatten()`. - const invalidFormErrors: TestFormErrors = parsed.error.flatten(() => ({ - message: "string", - code: 0, - })); - - [ - validFlattenedErrors, - invalidFlattenedErrors, - validFormErrors, - invalidFormErrors, - ]; -}); - -test(".formErrors type assertion", () => { - const parsed = Test.safeParse({}) as z.SafeParseError<void>; - const validFormErrors: TestFormErrors = parsed.error.formErrors; - // @ts-expect-error should fail assertion between `TestFlattenedErrors` and `.formErrors`. - const invalidFlattenedErrors: TestFlattenedErrors = parsed.error.formErrors; - - [validFormErrors, invalidFlattenedErrors]; -}); - -test("all errors", () => { - const propertySchema = z.string(); - const schema = z - .object({ - a: propertySchema, - b: propertySchema, - }) - .refine( - (val) => { - return val.a === val.b; - }, - { message: "Must be equal" } - ); - - try { - schema.parse({ - a: "asdf", - b: "qwer", - }); - } catch (error) { - if (error instanceof z.ZodError) { - expect(error.flatten()).toEqual({ - formErrors: ["Must be equal"], - fieldErrors: {}, - }); - } - } - - try { - schema.parse({ - a: null, - b: null, - }); - } catch (_error) { - const error = _error as z.ZodError; - expect(error.flatten()).toEqual({ - formErrors: [], - fieldErrors: { - a: ["Expected string, received null"], - b: ["Expected string, received null"], - }, - }); - - expect(error.flatten((iss) => iss.message.toUpperCase())).toEqual({ - formErrors: [], - fieldErrors: { - a: ["EXPECTED STRING, RECEIVED NULL"], - b: ["EXPECTED STRING, RECEIVED NULL"], - }, - }); - // Test identity - - expect(error.flatten((i: z.ZodIssue) => i)).toEqual({ - formErrors: [], - fieldErrors: { - a: [ - { - code: "invalid_type", - expected: "string", - message: "Expected string, received null", - path: ["a"], - received: "null", - }, - ], - b: [ - { - code: "invalid_type", - expected: "string", - message: "Expected string, received null", - path: ["b"], - received: "null", - }, - ], - }, - }); - // Test mapping - expect(error.flatten((i: z.ZodIssue) => i.message.length)).toEqual({ - formErrors: [], - fieldErrors: { - a: ["Expected string, received null".length], - b: ["Expected string, received null".length], - }, - }); - } -}); diff --git a/deno/lib/__tests__/anyunknown.test.ts b/deno/lib/__tests__/anyunknown.test.ts deleted file mode 100644 index 439aa8860..000000000 --- a/deno/lib/__tests__/anyunknown.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -// @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"; - -test("check any inference", () => { - const t1 = z.any(); - t1.optional(); - t1.nullable(); - type t1 = z.infer<typeof t1>; - util.assertEqual<t1, any>(true); -}); - -test("check unknown inference", () => { - const t1 = z.unknown(); - t1.optional(); - t1.nullable(); - type t1 = z.infer<typeof t1>; - util.assertEqual<t1, unknown>(true); -}); - -test("check never inference", () => { - const t1 = z.never(); - expect(() => t1.parse(undefined)).toThrow(); - expect(() => t1.parse("asdf")).toThrow(); - expect(() => t1.parse(null)).toThrow(); -}); diff --git a/deno/lib/__tests__/array.test.ts b/deno/lib/__tests__/array.test.ts deleted file mode 100644 index 8aed9d63f..000000000 --- a/deno/lib/__tests__/array.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -// @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"; - -const minTwo = z.string().array().min(2); -const maxTwo = z.string().array().max(2); -const justTwo = z.string().array().length(2); -const intNum = z.string().array().nonempty(); -const nonEmptyMax = z.string().array().nonempty().max(2); - -type t1 = z.infer<typeof nonEmptyMax>; -util.assertEqual<[string, ...string[]], t1>(true); - -type t2 = z.infer<typeof minTwo>; -util.assertEqual<string[], t2>(true); - -test("passing validations", () => { - minTwo.parse(["a", "a"]); - minTwo.parse(["a", "a", "a"]); - maxTwo.parse(["a", "a"]); - maxTwo.parse(["a"]); - justTwo.parse(["a", "a"]); - intNum.parse(["a"]); - nonEmptyMax.parse(["a"]); -}); - -test("failing validations", () => { - expect(() => minTwo.parse(["a"])).toThrow(); - expect(() => maxTwo.parse(["a", "a", "a"])).toThrow(); - expect(() => justTwo.parse(["a"])).toThrow(); - expect(() => justTwo.parse(["a", "a", "a"])).toThrow(); - expect(() => intNum.parse([])).toThrow(); - expect(() => nonEmptyMax.parse([])).toThrow(); - expect(() => nonEmptyMax.parse(["a", "a", "a"])).toThrow(); -}); - -test("parse empty array in nonempty", () => { - expect(() => - z - .array(z.string()) - .nonempty() - .parse([] as any) - ).toThrow(); -}); - -test("get element", () => { - justTwo.element.parse("asdf"); - expect(() => justTwo.element.parse(12)).toThrow(); -}); - -test("continue parsing despite array size error", () => { - const schema = z.object({ - people: z.string().array().min(2), - }); - - const result = schema.safeParse({ - people: [123], - }); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues.length).toEqual(2); - } -}); - -test("parse should fail given sparse array", () => { - const schema = z.array(z.string()).nonempty().min(1).max(3); - - expect(() => schema.parse(new Array(3))).toThrow(); -}); diff --git a/deno/lib/__tests__/async-parsing.test.ts b/deno/lib/__tests__/async-parsing.test.ts deleted file mode 100644 index 83b4d6242..000000000 --- a/deno/lib/__tests__/async-parsing.test.ts +++ /dev/null @@ -1,392 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -/// string -const stringSchema = z.string(); - -test("string async parse", async () => { - const goodData = "XXX"; - const badData = 12; - - const goodResult = await stringSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await stringSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// number -const numberSchema = z.number(); -test("number async parse", async () => { - const goodData = 1234.2353; - const badData = "1234"; - - const goodResult = await numberSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await numberSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// bigInt -const bigIntSchema = z.bigint(); -test("bigInt async parse", async () => { - const goodData = BigInt(145); - const badData = 134; - - const goodResult = await bigIntSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await bigIntSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// boolean -const booleanSchema = z.boolean(); -test("boolean async parse", async () => { - const goodData = true; - const badData = 1; - - const goodResult = await booleanSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await booleanSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// date -const dateSchema = z.date(); -test("date async parse", async () => { - const goodData = new Date(); - const badData = new Date().toISOString(); - - const goodResult = await dateSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await dateSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// undefined -const undefinedSchema = z.undefined(); -test("undefined async parse", async () => { - const goodData = undefined; - const badData = "XXX"; - - const goodResult = await undefinedSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(undefined); - - const badResult = await undefinedSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// null -const nullSchema = z.null(); -test("null async parse", async () => { - const goodData = null; - const badData = undefined; - - const goodResult = await nullSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await nullSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// any -const anySchema = z.any(); -test("any async parse", async () => { - const goodData = [{}]; - // const badData = 'XXX'; - - const goodResult = await anySchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - // const badResult = await anySchema.safeParseAsync(badData); - // expect(badResult.success).toBe(false); - // if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// unknown -const unknownSchema = z.unknown(); -test("unknown async parse", async () => { - const goodData = ["asdf", 124, () => {}]; - // const badData = 'XXX'; - - const goodResult = await unknownSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - // const badResult = await unknownSchema.safeParseAsync(badData); - // expect(badResult.success).toBe(false); - // if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// void -const voidSchema = z.void(); -test("void async parse", async () => { - const goodData = undefined; - const badData = 0; - - const goodResult = await voidSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await voidSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// array -const arraySchema = z.array(z.string()); -test("array async parse", async () => { - const goodData = ["XXX"]; - const badData = "XXX"; - - const goodResult = await arraySchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await arraySchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// object -const objectSchema = z.object({ string: z.string() }); -test("object async parse", async () => { - const goodData = { string: "XXX" }; - const badData = { string: 12 }; - - const goodResult = await objectSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await objectSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// union -const unionSchema = z.union([z.string(), z.undefined()]); -test("union async parse", async () => { - const goodData = undefined; - const badData = null; - - const goodResult = await unionSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await unionSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// record -const recordSchema = z.record(z.object({})); -test("record async parse", async () => { - const goodData = { adsf: {}, asdf: {} }; - const badData = [{}]; - - const goodResult = await recordSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await recordSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// function -const functionSchema = z.function(); -test("function async parse", async () => { - const goodData = () => {}; - const badData = "XXX"; - - const goodResult = await functionSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(typeof goodResult.data).toEqual("function"); - - const badResult = await functionSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// literal -const literalSchema = z.literal("asdf"); -test("literal async parse", async () => { - const goodData = "asdf"; - const badData = "asdff"; - - const goodResult = await literalSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await literalSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// enum -const enumSchema = z.enum(["fish", "whale"]); -test("enum async parse", async () => { - const goodData = "whale"; - const badData = "leopard"; - - const goodResult = await enumSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await enumSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// nativeEnum -enum nativeEnumTest { - asdf = "qwer", -} -// @ts-ignore -const nativeEnumSchema = z.nativeEnum(nativeEnumTest); -test("nativeEnum async parse", async () => { - const goodData = nativeEnumTest.asdf; - const badData = "asdf"; - - const goodResult = await nativeEnumSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) expect(goodResult.data).toEqual(goodData); - - const badResult = await nativeEnumSchema.safeParseAsync(badData); - expect(badResult.success).toBe(false); - if (!badResult.success) expect(badResult.error).toBeInstanceOf(z.ZodError); -}); - -/// promise -const promiseSchema = z.promise(z.number()); -test("promise async parse good", async () => { - const goodData = Promise.resolve(123); - - const goodResult = await promiseSchema.safeParseAsync(goodData); - expect(goodResult.success).toBe(true); - if (goodResult.success) { - expect(goodResult.data).toBeInstanceOf(Promise); - const data = await goodResult.data; - expect(data).toEqual(123); - // expect(goodResult.data).resolves.toEqual(124); - // return goodResult.data; - } else { - throw new Error("success should be true"); - } -}); - -test("promise async parse bad", async () => { - const badData = Promise.resolve("XXX"); - const badResult = await promiseSchema.safeParseAsync(badData); - expect(badResult.success).toBe(true); - if (badResult.success) { - await expect(badResult.data).rejects.toBeInstanceOf(z.ZodError); - } else { - throw new Error("success should be true"); - } -}); - -test("async validation non-empty strings", async () => { - const base = z.object({ - hello: z.string().refine((x) => x && x.length > 0), - foo: z.string().refine((x) => x && x.length > 0), - }); - - const testval = { hello: "", foo: "" }; - const result1 = base.safeParse(testval); - const result2 = base.safeParseAsync(testval); - - const r1 = result1; - await result2.then((r2) => { - if (r1.success === false && r2.success === false) - expect(r1.error.issues.length).toBe(r2.error.issues.length); // <--- r1 has length 2, r2 has length 1 - }); -}); - -test("async validation multiple errors 1", async () => { - const base = z.object({ - hello: z.string(), - foo: z.number(), - }); - - const testval = { hello: 3, foo: "hello" }; - const result1 = base.safeParse(testval); - const result2 = base.safeParseAsync(testval); - - const r1 = result1; - await result2.then((r2) => { - if (r1.success === false && r2.success === false) - expect(r2.error.issues.length).toBe(r1.error.issues.length); - }); -}); - -test("async validation multiple errors 2", async () => { - const base = (is_async?: boolean) => - z.object({ - hello: z.string(), - foo: z.object({ - bar: z.number().refine(is_async ? async () => false : () => false), - }), - }); - - const testval = { hello: 3, foo: { bar: 4 } }; - const result1 = base().safeParse(testval); - const result2 = base(true).safeParseAsync(testval); - - const r1 = result1; - await result2.then((r2) => { - if (r1.success === false && r2.success === false) - expect(r2.error.issues.length).toBe(r1.error.issues.length); - }); -}); - -test("ensure early async failure prevents follow-up refinement checks", async () => { - let count = 0; - const base = z.object({ - hello: z.string(), - foo: z - .number() - .refine(async () => { - count++; - return true; - }) - .refine(async () => { - count++; - return true; - }, "Good"), - }); - - const testval = { hello: "bye", foo: 3 }; - const result = await base.safeParseAsync(testval); - if (result.success === false) { - expect(result.error.issues.length).toBe(1); - expect(count).toBe(1); - } - - // await result.then((r) => { - // if (r.success === false) expect(r.error.issues.length).toBe(1); - // expect(count).toBe(2); - // }); -}); diff --git a/deno/lib/__tests__/async-refinements.test.ts b/deno/lib/__tests__/async-refinements.test.ts deleted file mode 100644 index 3bf468a8d..000000000 --- a/deno/lib/__tests__/async-refinements.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("parse async test", async () => { - const schema1 = z.string().refine(async (_val) => false); - expect(() => schema1.parse("asdf")).toThrow(); - - const schema2 = z.string().refine((_val) => Promise.resolve(true)); - return await expect(() => schema2.parse("asdf")).toThrow(); -}); - -test("parseAsync async test", async () => { - const schema1 = z.string().refine(async (_val) => true); - await schema1.parseAsync("asdf"); - - const schema2 = z.string().refine(async (_val) => false); - return await expect(schema2.parseAsync("asdf")).rejects.toBeDefined(); - // expect(async () => await schema2.parseAsync('asdf')).toThrow(); -}); - -test("parseAsync async test", async () => { - // expect.assertions(2); - - const schema1 = z.string().refine((_val) => Promise.resolve(true)); - const v1 = await schema1.parseAsync("asdf"); - expect(v1).toEqual("asdf"); - - const schema2 = z.string().refine((_val) => Promise.resolve(false)); - await expect(schema2.parseAsync("asdf")).rejects.toBeDefined(); - - const schema3 = z.string().refine((_val) => Promise.resolve(true)); - await expect(schema3.parseAsync("asdf")).resolves.toEqual("asdf"); - return await expect(schema3.parseAsync("qwer")).resolves.toEqual("qwer"); -}); - -test("parseAsync async with value", async () => { - const schema1 = z.string().refine(async (val) => { - return val.length > 5; - }); - await expect(schema1.parseAsync("asdf")).rejects.toBeDefined(); - - const v = await schema1.parseAsync("asdf123"); - return await expect(v).toEqual("asdf123"); -}); diff --git a/deno/lib/__tests__/base.test.ts b/deno/lib/__tests__/base.test.ts deleted file mode 100644 index beda584d7..000000000 --- a/deno/lib/__tests__/base.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -// @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"; - -test("type guard", () => { - const stringToNumber = z.string().transform((arg) => arg.length); - - const s1 = z.object({ - stringToNumber, - }); - type t1 = z.input<typeof s1>; - - const data = { stringToNumber: "asdf" }; - const parsed = s1.safeParse(data); - if (parsed.success) { - util.assertEqual<typeof data, t1>(true); - } -}); - -test("test this binding", () => { - const callback = (predicate: (val: string) => boolean) => { - return predicate("hello"); - }; - - expect(callback((value) => z.string().safeParse(value).success)).toBe(true); // true - expect(callback((value) => z.string().safeParse(value).success)).toBe(true); // true -}); diff --git a/deno/lib/__tests__/bigint.test.ts b/deno/lib/__tests__/bigint.test.ts deleted file mode 100644 index 549a64819..000000000 --- a/deno/lib/__tests__/bigint.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -const gtFive = z.bigint().gt(BigInt(5)); -const gteFive = z.bigint().gte(BigInt(5)); -const ltFive = z.bigint().lt(BigInt(5)); -const lteFive = z.bigint().lte(BigInt(5)); -const positive = z.bigint().positive(); -const negative = z.bigint().negative(); -const nonnegative = z.bigint().nonnegative(); -const nonpositive = z.bigint().nonpositive(); -const multipleOfFive = z.bigint().multipleOf(BigInt(5)); - -test("passing validations", () => { - z.bigint().parse(BigInt(1)); - z.bigint().parse(BigInt(0)); - z.bigint().parse(BigInt(-1)); - gtFive.parse(BigInt(6)); - gteFive.parse(BigInt(5)); - gteFive.parse(BigInt(6)); - ltFive.parse(BigInt(4)); - lteFive.parse(BigInt(5)); - lteFive.parse(BigInt(4)); - positive.parse(BigInt(3)); - negative.parse(BigInt(-2)); - nonnegative.parse(BigInt(0)); - nonnegative.parse(BigInt(7)); - nonpositive.parse(BigInt(0)); - nonpositive.parse(BigInt(-12)); - multipleOfFive.parse(BigInt(15)); -}); - -test("failing validations", () => { - expect(() => gtFive.parse(BigInt(5))).toThrow(); - expect(() => gteFive.parse(BigInt(4))).toThrow(); - expect(() => ltFive.parse(BigInt(5))).toThrow(); - expect(() => lteFive.parse(BigInt(6))).toThrow(); - expect(() => positive.parse(BigInt(0))).toThrow(); - expect(() => positive.parse(BigInt(-2))).toThrow(); - expect(() => negative.parse(BigInt(0))).toThrow(); - expect(() => negative.parse(BigInt(3))).toThrow(); - expect(() => nonnegative.parse(BigInt(-1))).toThrow(); - expect(() => nonpositive.parse(BigInt(1))).toThrow(); - expect(() => multipleOfFive.parse(BigInt(13))).toThrow(); -}); - -test("min max getters", () => { - expect(z.bigint().min(BigInt(5)).minValue).toEqual(BigInt(5)); - expect(z.bigint().min(BigInt(5)).min(BigInt(10)).minValue).toEqual( - BigInt(10) - ); - - expect(z.bigint().max(BigInt(5)).maxValue).toEqual(BigInt(5)); - expect(z.bigint().max(BigInt(5)).max(BigInt(1)).maxValue).toEqual(BigInt(1)); -}); diff --git a/deno/lib/__tests__/branded.test.ts b/deno/lib/__tests__/branded.test.ts deleted file mode 100644 index ff663ef66..000000000 --- a/deno/lib/__tests__/branded.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -// @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"; - -test("branded types", () => { - const mySchema = z - .object({ - name: z.string(), - }) - .brand<"superschema">(); - - // simple branding - type MySchema = z.infer<typeof mySchema>; - util.assertEqual< - MySchema, - { name: string } & { [z.BRAND]: { superschema: true } } - >(true); - - const doStuff = (arg: MySchema) => arg; - doStuff(mySchema.parse({ name: "hello there" })); - - // inheritance - const extendedSchema = mySchema.brand<"subschema">(); - type ExtendedSchema = z.infer<typeof extendedSchema>; - util.assertEqual< - ExtendedSchema, - { name: string } & z.BRAND<"superschema"> & z.BRAND<"subschema"> - >(true); - - doStuff(extendedSchema.parse({ name: "hello again" })); - - // number branding - const numberSchema = z.number().brand<42>(); - type NumberSchema = z.infer<typeof numberSchema>; - util.assertEqual<NumberSchema, number & { [z.BRAND]: { 42: true } }>(true); - - // symbol branding - const MyBrand: unique symbol = Symbol("hello"); - type MyBrand = typeof MyBrand; - const symbolBrand = z.number().brand<"sup">().brand<typeof MyBrand>(); - type SymbolBrand = z.infer<typeof symbolBrand>; - // number & { [z.BRAND]: { sup: true, [MyBrand]: true } } - util.assertEqual<SymbolBrand, number & z.BRAND<"sup"> & z.BRAND<MyBrand>>( - true - ); - - // keeping brands out of input types - const age = z.number().brand<"age">(); - - type Age = z.infer<typeof age>; - type AgeInput = z.input<typeof age>; - - util.assertEqual<AgeInput, Age>(false); - util.assertEqual<number, AgeInput>(true); - util.assertEqual<number & z.BRAND<"age">, Age>(true); - - // @ts-expect-error - doStuff({ name: "hello there!" }); -}); diff --git a/deno/lib/__tests__/catch.test.ts b/deno/lib/__tests__/catch.test.ts deleted file mode 100644 index f8ea89911..000000000 --- a/deno/lib/__tests__/catch.test.ts +++ /dev/null @@ -1,229 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import { z } from "../index.ts"; -import { util } from "../helpers/util.ts"; - -test("basic catch", () => { - expect(z.string().catch("default").parse(undefined)).toBe("default"); -}); - -test("catch fn does not run when parsing succeeds", () => { - let isCalled = false; - const cb = () => { - isCalled = true; - return "asdf"; - }; - expect(z.string().catch(cb).parse("test")).toBe("test"); - expect(isCalled).toEqual(false); -}); - -test("basic catch async", async () => { - const result = await z.string().catch("default").parseAsync(1243); - expect(result).toBe("default"); -}); - -test("catch replace wrong types", () => { - expect(z.string().catch("default").parse(true)).toBe("default"); - expect(z.string().catch("default").parse(true)).toBe("default"); - expect(z.string().catch("default").parse(15)).toBe("default"); - expect(z.string().catch("default").parse([])).toBe("default"); - expect(z.string().catch("default").parse(new Map())).toBe("default"); - expect(z.string().catch("default").parse(new Set())).toBe("default"); - expect(z.string().catch("default").parse({})).toBe("default"); -}); - -test("catch with transform", () => { - const stringWithDefault = z - .string() - .transform((val) => val.toUpperCase()) - .catch("default"); - expect(stringWithDefault.parse(undefined)).toBe("default"); - expect(stringWithDefault.parse(15)).toBe("default"); - expect(stringWithDefault).toBeInstanceOf(z.ZodCatch); - expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects); - expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf( - z.ZodSchema - ); - - type inp = z.input<typeof stringWithDefault>; - util.assertEqual<inp, unknown>(true); - type out = z.output<typeof stringWithDefault>; - util.assertEqual<out, string>(true); -}); - -test("catch on existing optional", () => { - const stringWithDefault = z.string().optional().catch("asdf"); - expect(stringWithDefault.parse(undefined)).toBe(undefined); - expect(stringWithDefault.parse(15)).toBe("asdf"); - expect(stringWithDefault).toBeInstanceOf(z.ZodCatch); - expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional); - expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf( - z.ZodString - ); - - type inp = z.input<typeof stringWithDefault>; - util.assertEqual<inp, unknown>(true); - type out = z.output<typeof stringWithDefault>; - util.assertEqual<out, string | undefined>(true); -}); - -test("optional on catch", () => { - const stringWithDefault = z.string().catch("asdf").optional(); - - type inp = z.input<typeof stringWithDefault>; - util.assertEqual<inp, unknown>(true); - type out = z.output<typeof stringWithDefault>; - util.assertEqual<out, string | undefined>(true); -}); - -test("complex chain example", () => { - const complex = z - .string() - .catch("asdf") - .transform((val) => val + "!") - .transform((val) => val.toUpperCase()) - .catch("qwer") - .removeCatch() - .optional() - .catch("asdfasdf"); - - expect(complex.parse("qwer")).toBe("QWER!"); - expect(complex.parse(15)).toBe("ASDF!"); - expect(complex.parse(true)).toBe("ASDF!"); -}); - -test("removeCatch", () => { - const stringWithRemovedDefault = z.string().catch("asdf").removeCatch(); - - type out = z.output<typeof stringWithRemovedDefault>; - util.assertEqual<out, string>(true); -}); - -test("nested", () => { - const inner = z.string().catch("asdf"); - const outer = z.object({ inner }).catch({ - inner: "asdf", - }); - type input = z.input<typeof outer>; - util.assertEqual<input, unknown>(true); - type out = z.output<typeof outer>; - util.assertEqual<out, { inner: string }>(true); - expect(outer.parse(undefined)).toEqual({ inner: "asdf" }); - expect(outer.parse({})).toEqual({ inner: "asdf" }); - expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" }); -}); - -test("chained catch", () => { - const stringWithDefault = z.string().catch("inner").catch("outer"); - const result = stringWithDefault.parse(undefined); - expect(result).toEqual("inner"); - const resultDiff = stringWithDefault.parse(5); - expect(resultDiff).toEqual("inner"); -}); - -test("factory", () => { - z.ZodCatch.create(z.string(), { - catch: "asdf", - }).parse(undefined); -}); - -test("native enum", () => { - enum Fruits { - apple = "apple", - orange = "orange", - } - - const schema = z.object({ - fruit: z.nativeEnum(Fruits).catch(Fruits.apple), - }); - - expect(schema.parse({})).toEqual({ fruit: Fruits.apple }); - expect(schema.parse({ fruit: 15 })).toEqual({ fruit: Fruits.apple }); -}); - -test("enum", () => { - const schema = z.object({ - fruit: z.enum(["apple", "orange"]).catch("apple"), - }); - - expect(schema.parse({})).toEqual({ fruit: "apple" }); - expect(schema.parse({ fruit: true })).toEqual({ fruit: "apple" }); - expect(schema.parse({ fruit: 15 })).toEqual({ fruit: "apple" }); -}); - -test("reported issues with nested usage", () => { - const schema = z.object({ - string: z.string(), - obj: z.object({ - sub: z.object({ - lit: z.literal("a"), - subCatch: z.number().catch(23), - }), - midCatch: z.number().catch(42), - }), - number: z.number().catch(0), - bool: z.boolean(), - }); - - try { - schema.parse({ - string: {}, - obj: { - sub: { - lit: "b", - subCatch: "24", - }, - midCatch: 444, - }, - number: "", - bool: "yes", - }); - } catch (error) { - const issues = (error as z.ZodError).issues; - - expect(issues.length).toEqual(3); - expect(issues[0].message).toMatch("string"); - expect(issues[1].message).toMatch("literal"); - expect(issues[2].message).toMatch("boolean"); - } -}); - -test("catch error", () => { - let catchError: z.ZodError | undefined = undefined; - - const schema = z.object({ - age: z.number(), - name: z.string().catch((ctx) => { - catchError = ctx.error; - - return "John Doe"; - }), - }); - - const result = schema.safeParse({ - age: null, - name: null, - }); - - expect(result.success).toEqual(false); - expect(!result.success && result.error.issues.length).toEqual(1); - expect(!result.success && result.error.issues[0].message).toMatch("number"); - - expect(catchError).toBeInstanceOf(z.ZodError); - expect( - catchError !== undefined && (catchError as z.ZodError).issues.length - ).toEqual(1); - expect( - catchError !== undefined && (catchError as z.ZodError).issues[0].message - ).toMatch("string"); -}); - -test("ctx.input", () => { - const schema = z.string().catch((ctx) => { - return String(ctx.input); - }); - - expect(schema.parse(123)).toEqual("123"); -}); diff --git a/deno/lib/__tests__/coerce.test.ts b/deno/lib/__tests__/coerce.test.ts deleted file mode 100644 index adbd86e7e..000000000 --- a/deno/lib/__tests__/coerce.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("string coercion", () => { - const schema = z.coerce.string(); - expect(schema.parse("sup")).toEqual("sup"); - expect(schema.parse("")).toEqual(""); - expect(schema.parse(12)).toEqual("12"); - expect(schema.parse(0)).toEqual("0"); - expect(schema.parse(-12)).toEqual("-12"); - expect(schema.parse(3.14)).toEqual("3.14"); - expect(schema.parse(BigInt(15))).toEqual("15"); - expect(schema.parse(NaN)).toEqual("NaN"); - expect(schema.parse(Infinity)).toEqual("Infinity"); - expect(schema.parse(-Infinity)).toEqual("-Infinity"); - expect(schema.parse(true)).toEqual("true"); - expect(schema.parse(false)).toEqual("false"); - expect(schema.parse(null)).toEqual("null"); - expect(schema.parse(undefined)).toEqual("undefined"); - expect(schema.parse({ hello: "world!" })).toEqual("[object Object]"); - expect(schema.parse(["item", "another_item"])).toEqual("item,another_item"); - expect(schema.parse([])).toEqual(""); - expect(schema.parse(new Date("2022-01-01T00:00:00.000Z"))).toEqual( - new Date("2022-01-01T00:00:00.000Z").toString() - ); -}); - -test("number coercion", () => { - const schema = z.coerce.number(); - expect(schema.parse("12")).toEqual(12); - expect(schema.parse("0")).toEqual(0); - expect(schema.parse("-12")).toEqual(-12); - expect(schema.parse("3.14")).toEqual(3.14); - expect(schema.parse("")).toEqual(0); - expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // z.ZodError - expect(schema.parse(12)).toEqual(12); - expect(schema.parse(0)).toEqual(0); - expect(schema.parse(-12)).toEqual(-12); - expect(schema.parse(3.14)).toEqual(3.14); - expect(schema.parse(BigInt(15))).toEqual(15); - expect(() => schema.parse(NaN)).toThrow(); // z.ZodError - expect(schema.parse(Infinity)).toEqual(Infinity); - expect(schema.parse(-Infinity)).toEqual(-Infinity); - expect(schema.parse(true)).toEqual(1); - expect(schema.parse(false)).toEqual(0); - expect(schema.parse(null)).toEqual(0); - expect(() => schema.parse(undefined)).toThrow(); // z.ZodError - expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError - expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError - expect(schema.parse([])).toEqual(0); - expect(schema.parse(new Date(1670139203496))).toEqual(1670139203496); -}); - -test("boolean coercion", () => { - const schema = z.coerce.boolean(); - expect(schema.parse("true")).toEqual(true); - expect(schema.parse("false")).toEqual(true); - expect(schema.parse("0")).toEqual(true); - expect(schema.parse("1")).toEqual(true); - expect(schema.parse("")).toEqual(false); - expect(schema.parse(1)).toEqual(true); - expect(schema.parse(0)).toEqual(false); - expect(schema.parse(-1)).toEqual(true); - expect(schema.parse(3.14)).toEqual(true); - expect(schema.parse(BigInt(15))).toEqual(true); - expect(schema.parse(NaN)).toEqual(false); - expect(schema.parse(Infinity)).toEqual(true); - expect(schema.parse(-Infinity)).toEqual(true); - expect(schema.parse(true)).toEqual(true); - expect(schema.parse(false)).toEqual(false); - expect(schema.parse(null)).toEqual(false); - expect(schema.parse(undefined)).toEqual(false); - expect(schema.parse({ hello: "world!" })).toEqual(true); - expect(schema.parse(["item", "another_item"])).toEqual(true); - expect(schema.parse([])).toEqual(true); - expect(schema.parse(new Date(1670139203496))).toEqual(true); -}); - -test("bigint coercion", () => { - const schema = z.coerce.bigint(); - expect(schema.parse("5")).toEqual(BigInt(5)); - expect(schema.parse("0")).toEqual(BigInt(0)); - expect(schema.parse("-5")).toEqual(BigInt(-5)); - expect(() => schema.parse("3.14")).toThrow(); // not a z.ZodError! - expect(schema.parse("")).toEqual(BigInt(0)); - expect(() => schema.parse("NOT_A_NUMBER")).toThrow(); // not a z.ZodError! - expect(schema.parse(5)).toEqual(BigInt(5)); - expect(schema.parse(0)).toEqual(BigInt(0)); - expect(schema.parse(-5)).toEqual(BigInt(-5)); - expect(() => schema.parse(3.14)).toThrow(); // not a z.ZodError! - expect(schema.parse(BigInt(5))).toEqual(BigInt(5)); - expect(() => schema.parse(NaN)).toThrow(); // not a z.ZodError! - expect(() => schema.parse(Infinity)).toThrow(); // not a z.ZodError! - expect(() => schema.parse(-Infinity)).toThrow(); // not a z.ZodError! - expect(schema.parse(true)).toEqual(BigInt(1)); - expect(schema.parse(false)).toEqual(BigInt(0)); - expect(() => schema.parse(null)).toThrow(); // not a z.ZodError! - expect(() => schema.parse(undefined)).toThrow(); // not a z.ZodError! - expect(() => schema.parse({ hello: "world!" })).toThrow(); // not a z.ZodError! - expect(() => schema.parse(["item", "another_item"])).toThrow(); // not a z.ZodError! - expect(schema.parse([])).toEqual(BigInt(0)); - expect(schema.parse(new Date(1670139203496))).toEqual(BigInt(1670139203496)); -}); - -test("date coercion", () => { - const schema = z.coerce.date(); - expect(schema.parse(new Date().toDateString())).toBeInstanceOf(Date); - expect(schema.parse(new Date().toISOString())).toBeInstanceOf(Date); - expect(schema.parse(new Date().toUTCString())).toBeInstanceOf(Date); - expect(schema.parse("5")).toBeInstanceOf(Date); - expect(schema.parse("2000-01-01")).toBeInstanceOf(Date); - // expect(schema.parse("0")).toBeInstanceOf(Date); - // expect(schema.parse("-5")).toBeInstanceOf(Date); - // expect(schema.parse("3.14")).toBeInstanceOf(Date); - expect(() => schema.parse("")).toThrow(); // z.ZodError - expect(() => schema.parse("NOT_A_DATE")).toThrow(); // z.ZodError - expect(schema.parse(5)).toBeInstanceOf(Date); - expect(schema.parse(0)).toBeInstanceOf(Date); - expect(schema.parse(-5)).toBeInstanceOf(Date); - expect(schema.parse(3.14)).toBeInstanceOf(Date); - expect(() => schema.parse(BigInt(5))).toThrow(); // not a z.ZodError! - expect(() => schema.parse(NaN)).toThrow(); // z.ZodError - expect(() => schema.parse(Infinity)).toThrow(); // z.ZodError - expect(() => schema.parse(-Infinity)).toThrow(); // z.ZodError - expect(schema.parse(true)).toBeInstanceOf(Date); - expect(schema.parse(false)).toBeInstanceOf(Date); - expect(schema.parse(null)).toBeInstanceOf(Date); - expect(() => schema.parse(undefined)).toThrow(); // z.ZodError - expect(() => schema.parse({ hello: "world!" })).toThrow(); // z.ZodError - expect(() => schema.parse(["item", "another_item"])).toThrow(); // z.ZodError - expect(() => schema.parse([])).toThrow(); // z.ZodError - expect(schema.parse(new Date())).toBeInstanceOf(Date); -}); - -test("template literal coercion", () => { - const schema = z.coerce - .templateLiteral() - .interpolated(z.number().finite()) - .interpolated( - z.enum(["px", "em", "rem", "vh", "vw", "vmin", "vmax"]).optional() - ); - expect(schema.parse(300)).toEqual("300"); - expect(schema.parse(BigInt(300))).toEqual("300"); - expect(schema.parse("300")).toEqual("300"); - expect(schema.parse("300px")).toEqual("300px"); - expect(schema.parse("300em")).toEqual("300em"); - expect(schema.parse("300rem")).toEqual("300rem"); - expect(schema.parse("300vh")).toEqual("300vh"); - expect(schema.parse("300vw")).toEqual("300vw"); - expect(schema.parse("300vmin")).toEqual("300vmin"); - expect(schema.parse("300vmax")).toEqual("300vmax"); - expect(schema.parse(["300px"])).toEqual("300px"); -}); diff --git a/deno/lib/__tests__/complex.test.ts b/deno/lib/__tests__/complex.test.ts deleted file mode 100644 index 0d4b70c97..000000000 --- a/deno/lib/__tests__/complex.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import { crazySchema } from "./crazySchema.ts"; -// import * as z from "../index"; - -test("parse", () => { - crazySchema.parse({ - tuple: ["asdf", 1234, true, null, undefined, "1234"], - merged: { k1: "asdf", k2: 12 }, - union: ["asdf", 12, "asdf", 12, "asdf", 12], - array: [12, 15, 16], - // sumTransformer: [12, 15, 16], - sumMinLength: [12, 15, 16, 98, 24, 63], - intersection: {}, - enum: "one", - nonstrict: { points: 1234 }, - numProm: Promise.resolve(12), - lenfun: (x: string) => x.length, - }); -}); diff --git a/deno/lib/__tests__/crazySchema.ts b/deno/lib/__tests__/crazySchema.ts deleted file mode 100644 index 42725e1db..000000000 --- a/deno/lib/__tests__/crazySchema.ts +++ /dev/null @@ -1,42 +0,0 @@ -import * as z from "../index.ts"; - -export const crazySchema = z.object({ - tuple: z.tuple([ - z.string().nullable().optional(), - z.number().nullable().optional(), - z.boolean().nullable().optional(), - z.null().nullable().optional(), - z.undefined().nullable().optional(), - z.literal("1234").nullable().optional(), - ]), - merged: z - .object({ - k1: z.string().optional(), - }) - .merge(z.object({ k1: z.string().nullable(), k2: z.number() })), - union: z.array(z.union([z.literal("asdf"), z.literal(12)])).nonempty(), - array: z.array(z.number()), - // sumTransformer: z.transformer(z.array(z.number()), z.number(), (arg) => { - // return arg.reduce((a, b) => a + b, 0); - // }), - sumMinLength: z.array(z.number()).refine((arg) => arg.length > 5), - intersection: z.intersection( - z.object({ p1: z.string().optional() }), - z.object({ p1: z.number().optional() }) - ), - enum: z.intersection(z.enum(["zero", "one"]), z.enum(["one", "two"])), - nonstrict: z.object({ points: z.number() }).nonstrict(), - numProm: z.promise(z.number()), - lenfun: z.function(z.tuple([z.string()]), z.boolean()), -}); - -export const asyncCrazySchema = crazySchema.extend({ - // async_transform: z.transformer( - // z.array(z.number()), - // z.number(), - // async (arg) => { - // return arg.reduce((a, b) => a + b, 0); - // } - // ), - async_refine: z.array(z.number()).refine(async (arg) => arg.length > 5), -}); diff --git a/deno/lib/__tests__/custom.test.ts b/deno/lib/__tests__/custom.test.ts deleted file mode 100644 index a19233ecf..000000000 --- a/deno/lib/__tests__/custom.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("passing validations", () => { - const example1 = z.custom<number>((x) => typeof x === "number"); - example1.parse(1234); - expect(() => example1.parse({})).toThrow(); -}); - -test("string params", () => { - const example1 = z.custom<number>((x) => typeof x !== "number", "customerr"); - const result = example1.safeParse(1234); - expect(result.success).toEqual(false); - // @ts-ignore - expect(JSON.stringify(result.error).includes("customerr")).toEqual(true); -}); diff --git a/deno/lib/__tests__/date.test.ts b/deno/lib/__tests__/date.test.ts deleted file mode 100644 index 89f7f3387..000000000 --- a/deno/lib/__tests__/date.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -const beforeBenchmarkDate = new Date(2022, 10, 4); -const benchmarkDate = new Date(2022, 10, 5); -const afterBenchmarkDate = new Date(2022, 10, 6); - -const minCheck = z.date().min(benchmarkDate); -const maxCheck = z.date().max(benchmarkDate); - -test("passing validations", () => { - minCheck.parse(benchmarkDate); - minCheck.parse(afterBenchmarkDate); - - maxCheck.parse(benchmarkDate); - maxCheck.parse(beforeBenchmarkDate); -}); - -test("failing validations", () => { - expect(() => minCheck.parse(beforeBenchmarkDate)).toThrow(); - expect(() => maxCheck.parse(afterBenchmarkDate)).toThrow(); -}); - -test("min max getters", () => { - expect(minCheck.minDate).toEqual(benchmarkDate); - expect(minCheck.min(afterBenchmarkDate).minDate).toEqual(afterBenchmarkDate); - - expect(maxCheck.maxDate).toEqual(benchmarkDate); - expect(maxCheck.max(beforeBenchmarkDate).maxDate).toEqual( - beforeBenchmarkDate - ); -}); diff --git a/deno/lib/__tests__/deepmasking.test.ts b/deno/lib/__tests__/deepmasking.test.ts deleted file mode 100644 index e151ff8c9..000000000 --- a/deno/lib/__tests__/deepmasking.test.ts +++ /dev/null @@ -1,187 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("test", () => { - z; -}); - -// const fish = z.object({ -// name: z.string(), -// props: z.object({ -// color: z.string(), -// numScales: z.number(), -// }), -// }); - -// const nonStrict = z -// .object({ -// name: z.string(), -// color: z.string(), -// }) -// .nonstrict(); - -// test('object pick type', () => { -// const modNonStrictFish = nonStrict.omit({ name: true }); -// modNonStrictFish.parse({ color: 'asdf' }); - -// const bad1 = () => fish.pick({ props: { unknown: true } } as any); -// const bad2 = () => fish.omit({ name: true, props: { unknown: true } } as any); - -// expect(bad1).toThrow(); -// expect(bad2).toThrow(); -// }); - -// test('f1', () => { -// const f1 = fish.pick(true); -// f1.parse({ name: 'a', props: { color: 'b', numScales: 3 } }); -// }); -// test('f2', () => { -// const f2 = fish.pick({ props: true }); -// f2.parse({ props: { color: 'asdf', numScales: 1 } }); -// const badcheck2 = () => f2.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); -// expect(badcheck2).toThrow(); -// }); -// test('f3', () => { -// const f3 = fish.pick({ props: { color: true } }); -// f3.parse({ props: { color: 'b' } }); -// const badcheck3 = () => f3.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); -// expect(badcheck3).toThrow(); -// }); -// test('f4', () => { -// const badcheck4 = () => fish.pick({ props: { color: true, unknown: true } }); -// expect(badcheck4).toThrow(); -// }); -// test('f6', () => { -// const f6 = fish.omit({ props: true }); -// const badcheck6 = () => f6.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); -// f6.parse({ name: 'adsf' }); -// expect(badcheck6).toThrow(); -// }); -// test('f7', () => { -// const f7 = fish.omit({ props: { color: true } }); -// f7.parse({ name: 'a', props: { numScales: 3 } }); -// const badcheck7 = () => f7.parse({ name: 'a', props: { color: 'b', numScales: 3 } } as any); -// expect(badcheck7).toThrow(); -// }); -// test('f8', () => { -// const badcheck8 = () => fish.omit({ props: { color: true, unknown: true } }); -// expect(badcheck8).toThrow(); -// }); -// test('f9', () => { -// const f9 = nonStrict.pick(true); -// f9.parse({ name: 'a', color: 'asdf' }); -// }); -// test('f10', () => { -// const f10 = nonStrict.pick({ name: true }); -// f10.parse({ name: 'a' }); -// const val = f10.parse({ name: 'a', color: 'b' }); -// expect(val).toEqual({ name: 'a' }); -// }); -// test('f12', () => { -// const badfcheck12 = () => nonStrict.omit({ color: true, asdf: true }); -// expect(badfcheck12).toThrow(); -// }); - -// test('array masking', () => { -// const fishArray = z.array(fish); -// const modFishArray = fishArray.pick({ -// name: true, -// props: { -// numScales: true, -// }, -// }); - -// modFishArray.parse([{ name: 'fish', props: { numScales: 12 } }]); -// const bad1 = () => modFishArray.parse([{ name: 'fish', props: { numScales: 12, color: 'asdf' } }] as any); -// expect(bad1).toThrow(); -// }); - -// test('array masking', () => { -// const fishArray = z.array(fish); -// const fail = () => -// fishArray.pick({ -// name: true, -// props: { -// whatever: true, -// }, -// } as any); -// expect(fail).toThrow(); -// }); - -// test('array masking', () => { -// const fishArray = z.array(fish); -// const fail = () => -// fishArray.omit({ -// whateve: true, -// } as any); -// expect(fail).toThrow(); -// }); - -// test('array masking', () => { -// const fishArray = z.array(fish); -// const modFishList = fishArray.omit({ -// name: true, -// props: { -// color: true, -// }, -// }); - -// modFishList.parse([{ props: { numScales: 12 } }]); -// const fail = () => modFishList.parse([{ name: 'hello', props: { numScales: 12 } }] as any); -// expect(fail).toThrow(); -// }); - -// test('primitive array masking', () => { -// const fishArray = z.array(z.number()); -// const fail = () => fishArray.pick({} as any); -// expect(fail).toThrow(); -// }); - -// test('other array masking', () => { -// const fishArray = z.array(z.array(z.number())); -// const fail = () => fishArray.pick({} as any); -// expect(fail).toThrow(); -// }); - -// test('invalid mask #1', () => { -// const fail = () => fish.pick(1 as any); -// expect(fail).toThrow(); -// }); - -// test('invalid mask #2', () => { -// const fail = () => fish.pick([] as any); -// expect(fail).toThrow(); -// }); - -// test('invalid mask #3', () => { -// const fail = () => fish.pick(false as any); -// expect(fail).toThrow(); -// }); - -// test('invalid mask #4', () => { -// const fail = () => fish.pick('asdf' as any); -// expect(fail).toThrow(); -// }); - -// test('invalid mask #5', () => { -// const fail = () => fish.omit(1 as any); -// expect(fail).toThrow(); -// }); - -// test('invalid mask #6', () => { -// const fail = () => fish.omit([] as any); -// expect(fail).toThrow(); -// }); - -// test('invalid mask #7', () => { -// const fail = () => fish.omit(false as any); -// expect(fail).toThrow(); -// }); - -// test('invalid mask #8', () => { -// const fail = () => fish.omit('asdf' as any); -// expect(fail).toThrow(); -// }); diff --git a/deno/lib/__tests__/default.test.ts b/deno/lib/__tests__/default.test.ts deleted file mode 100644 index 6ad12cae7..000000000 --- a/deno/lib/__tests__/default.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import { z } from "../index.ts"; -import { util } from "../helpers/util.ts"; - -test("basic defaults", () => { - expect(z.string().default("default").parse(undefined)).toBe("default"); -}); - -test("default with transform", () => { - const stringWithDefault = z - .string() - .transform((val) => val.toUpperCase()) - .default("default"); - expect(stringWithDefault.parse(undefined)).toBe("DEFAULT"); - expect(stringWithDefault).toBeInstanceOf(z.ZodDefault); - expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodEffects); - expect(stringWithDefault._def.innerType._def.schema).toBeInstanceOf( - z.ZodSchema - ); - - type inp = z.input<typeof stringWithDefault>; - util.assertEqual<inp, string | undefined>(true); - type out = z.output<typeof stringWithDefault>; - util.assertEqual<out, string>(true); -}); - -test("default on existing optional", () => { - const stringWithDefault = z.string().optional().default("asdf"); - expect(stringWithDefault.parse(undefined)).toBe("asdf"); - expect(stringWithDefault).toBeInstanceOf(z.ZodDefault); - expect(stringWithDefault._def.innerType).toBeInstanceOf(z.ZodOptional); - expect(stringWithDefault._def.innerType._def.innerType).toBeInstanceOf( - z.ZodString - ); - - type inp = z.input<typeof stringWithDefault>; - util.assertEqual<inp, string | undefined>(true); - type out = z.output<typeof stringWithDefault>; - util.assertEqual<out, string>(true); -}); - -test("optional on default", () => { - const stringWithDefault = z.string().default("asdf").optional(); - - type inp = z.input<typeof stringWithDefault>; - util.assertEqual<inp, string | undefined>(true); - type out = z.output<typeof stringWithDefault>; - util.assertEqual<out, string | undefined>(true); -}); - -test("complex chain example", () => { - const complex = z - .string() - .default("asdf") - .transform((val) => val.toUpperCase()) - .default("qwer") - .removeDefault() - .optional() - .default("asdfasdf"); - - expect(complex.parse(undefined)).toBe("ASDFASDF"); -}); - -test("removeDefault", () => { - const stringWithRemovedDefault = z.string().default("asdf").removeDefault(); - - type out = z.output<typeof stringWithRemovedDefault>; - util.assertEqual<out, string>(true); -}); - -test("nested", () => { - const inner = z.string().default("asdf"); - const outer = z.object({ inner }).default({ - inner: undefined, - }); - type input = z.input<typeof outer>; - util.assertEqual<input, { inner?: string | undefined } | undefined>(true); - type out = z.output<typeof outer>; - util.assertEqual<out, { inner: string }>(true); - expect(outer.parse(undefined)).toEqual({ inner: "asdf" }); - expect(outer.parse({})).toEqual({ inner: "asdf" }); - expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" }); -}); - -test("chained defaults", () => { - const stringWithDefault = z.string().default("inner").default("outer"); - const result = stringWithDefault.parse(undefined); - expect(result).toEqual("outer"); -}); - -test("factory", () => { - expect( - z.ZodDefault.create(z.string(), { default: "asdf" }).parse(undefined) - ).toEqual("asdf"); -}); - -test("native enum", () => { - enum Fruits { - apple = "apple", - orange = "orange", - } - - const schema = z.object({ - fruit: z.nativeEnum(Fruits).default(Fruits.apple), - }); - - expect(schema.parse({})).toEqual({ fruit: Fruits.apple }); -}); - -test("enum", () => { - const schema = z.object({ - fruit: z.enum(["apple", "orange"]).default("apple"), - }); - - expect(schema.parse({})).toEqual({ fruit: "apple" }); -}); diff --git a/deno/lib/__tests__/description.test.ts b/deno/lib/__tests__/description.test.ts deleted file mode 100644 index 63015eab9..000000000 --- a/deno/lib/__tests__/description.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -const description = "a description"; - -test("passing `description` to schema should add a description", () => { - expect(z.string({ description }).description).toEqual(description); - expect(z.number({ description }).description).toEqual(description); - expect(z.boolean({ description }).description).toEqual(description); -}); - -test("`.describe` should add a description", () => { - expect(z.string().describe(description).description).toEqual(description); - expect(z.number().describe(description).description).toEqual(description); - expect(z.boolean().describe(description).description).toEqual(description); -}); - -test("description should carry over to chained schemas", () => { - const schema = z.string({ description }); - expect(schema.description).toEqual(description); - expect(schema.optional().description).toEqual(description); - expect(schema.optional().nullable().default("default").description).toEqual( - description - ); -}); diff --git a/deno/lib/__tests__/discriminated-unions.test.ts b/deno/lib/__tests__/discriminated-unions.test.ts deleted file mode 100644 index bff0cdac2..000000000 --- a/deno/lib/__tests__/discriminated-unions.test.ts +++ /dev/null @@ -1,310 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("valid", () => { - expect( - z - .discriminatedUnion("type", [ - z.object({ type: z.literal("a"), a: z.string() }), - z.object({ type: z.literal("b"), b: z.string() }), - ]) - .parse({ type: "a", a: "abc" }) - ).toEqual({ type: "a", a: "abc" }); -}); - -test("valid - discriminator value of various primitive types", () => { - const schema = z.discriminatedUnion("type", [ - z.object({ type: z.literal("1"), val: z.literal(1) }), - z.object({ type: z.literal(1), val: z.literal(2) }), - z.object({ type: z.literal(BigInt(1)), val: z.literal(3) }), - z.object({ type: z.literal("true"), val: z.literal(4) }), - z.object({ type: z.literal(true), val: z.literal(5) }), - z.object({ type: z.literal("null"), val: z.literal(6) }), - z.object({ type: z.literal(null), val: z.literal(7) }), - z.object({ type: z.literal("undefined"), val: z.literal(8) }), - z.object({ type: z.literal(undefined), val: z.literal(9) }), - z.object({ type: z.literal("transform"), val: z.literal(10) }), - z.object({ type: z.literal("refine"), val: z.literal(11) }), - z.object({ type: z.literal("superRefine"), val: z.literal(12) }), - ]); - - expect(schema.parse({ type: "1", val: 1 })).toEqual({ type: "1", val: 1 }); - expect(schema.parse({ type: 1, val: 2 })).toEqual({ type: 1, val: 2 }); - expect(schema.parse({ type: BigInt(1), val: 3 })).toEqual({ - type: BigInt(1), - val: 3, - }); - expect(schema.parse({ type: "true", val: 4 })).toEqual({ - type: "true", - val: 4, - }); - expect(schema.parse({ type: true, val: 5 })).toEqual({ - type: true, - val: 5, - }); - expect(schema.parse({ type: "null", val: 6 })).toEqual({ - type: "null", - val: 6, - }); - expect(schema.parse({ type: null, val: 7 })).toEqual({ - type: null, - val: 7, - }); - expect(schema.parse({ type: "undefined", val: 8 })).toEqual({ - type: "undefined", - val: 8, - }); - expect(schema.parse({ type: undefined, val: 9 })).toEqual({ - type: undefined, - val: 9, - }); -}); - -test("invalid - null", () => { - try { - z.discriminatedUnion("type", [ - z.object({ type: z.literal("a"), a: z.string() }), - z.object({ type: z.literal("b"), b: z.string() }), - ]).parse(null); - throw new Error(); - } catch (e: any) { - expect(JSON.parse(e.message)).toEqual([ - { - code: z.ZodIssueCode.invalid_type, - expected: z.ZodParsedType.object, - message: "Expected object, received null", - received: z.ZodParsedType.null, - path: [], - }, - ]); - } -}); - -test("invalid discriminator value", () => { - try { - z.discriminatedUnion("type", [ - z.object({ type: z.literal("a"), a: z.string() }), - z.object({ type: z.literal("b"), b: z.string() }), - ]).parse({ type: "x", a: "abc" }); - throw new Error(); - } catch (e: any) { - expect(JSON.parse(e.message)).toEqual([ - { - code: z.ZodIssueCode.invalid_union_discriminator, - options: ["a", "b"], - message: "Invalid discriminator value. Expected 'a' | 'b'", - path: ["type"], - }, - ]); - } -}); - -test("valid discriminator value, invalid data", () => { - try { - z.discriminatedUnion("type", [ - z.object({ type: z.literal("a"), a: z.string() }), - z.object({ type: z.literal("b"), b: z.string() }), - ]).parse({ type: "a", b: "abc" }); - throw new Error(); - } catch (e: any) { - expect(JSON.parse(e.message)).toEqual([ - { - code: z.ZodIssueCode.invalid_type, - expected: z.ZodParsedType.string, - message: "Required", - path: ["a"], - received: z.ZodParsedType.undefined, - }, - ]); - } -}); - -test("wrong schema - missing discriminator", () => { - try { - z.discriminatedUnion("type", [ - z.object({ type: z.literal("a"), a: z.string() }), - z.object({ b: z.string() }) as any, - ]); - throw new Error(); - } catch (e: any) { - expect(e.message.includes("could not be extracted")).toBe(true); - } -}); - -test("wrong schema - duplicate discriminator values", () => { - try { - z.discriminatedUnion("type", [ - z.object({ type: z.literal("a"), a: z.string() }), - z.object({ type: z.literal("a"), b: z.string() }), - ]); - throw new Error(); - } catch (e: any) { - expect(e.message.includes("has duplicate value")).toEqual(true); - } -}); - -test("async - valid", async () => { - expect( - await z - .discriminatedUnion("type", [ - z.object({ - type: z.literal("a"), - a: z - .string() - .refine(async () => true) - .transform(async (val) => Number(val)), - }), - z.object({ - type: z.literal("b"), - b: z.string(), - }), - ]) - .parseAsync({ type: "a", a: "1" }) - ).toEqual({ type: "a", a: 1 }); -}); - -test("async - invalid", async () => { - try { - await z - .discriminatedUnion("type", [ - z.object({ - type: z.literal("a"), - a: z - .string() - .refine(async () => true) - .transform(async (val) => val), - }), - z.object({ - type: z.literal("b"), - b: z.string(), - }), - ]) - .parseAsync({ type: "a", a: 1 }); - throw new Error(); - } catch (e: any) { - expect(JSON.parse(e.message)).toEqual([ - { - code: "invalid_type", - expected: "string", - received: "number", - path: ["a"], - message: "Expected string, received number", - }, - ]); - } -}); - -test("valid - literals with .default or .preprocess", () => { - const schema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("foo").default("foo"), - a: z.string(), - }), - z.object({ - type: z.literal("custom"), - method: z.string(), - }), - z.object({ - type: z.preprocess((val) => String(val), z.literal("bar")), - c: z.string(), - }), - ]); - expect(schema.parse({ type: "foo", a: "foo" })).toEqual({ - type: "foo", - a: "foo", - }); -}); - -test("enum and nativeEnum", () => { - enum MyEnum { - d, - e = "e", - } - - const schema = z.discriminatedUnion("key", [ - z.object({ - key: z.literal("a"), - // Add other properties specific to this option - }), - z.object({ - key: z.enum(["b", "c"]), - // Add other properties specific to this option - }), - z.object({ - key: z.nativeEnum(MyEnum), - // Add other properties specific to this option - }), - ]); - - type schema = z.infer<typeof schema>; - - schema.parse({ key: "a" }); - schema.parse({ key: "b" }); - schema.parse({ key: "c" }); - schema.parse({ key: MyEnum.d }); - schema.parse({ key: MyEnum.e }); - schema.parse({ key: "e" }); -}); - -test("branded", () => { - const schema = z.discriminatedUnion("key", [ - z.object({ - key: z.literal("a"), - // Add other properties specific to this option - }), - z.object({ - key: z.literal("b").brand("asdfaf"), - // Add other properties specific to this option - }), - ]); - - type schema = z.infer<typeof schema>; - - schema.parse({ key: "a" }); - schema.parse({ key: "b" }); - expect(() => { - schema.parse({ key: "c" }); - }).toThrow(); -}); - -test("optional and nullable", () => { - const schema = z.discriminatedUnion("key", [ - z.object({ - key: z.literal("a").optional(), - a: z.literal(true), - }), - z.object({ - key: z.literal("b").nullable(), - b: z.literal(true), - // Add other properties specific to this option - }), - ]); - - type schema = z.infer<typeof schema>; - z.util.assertEqual< - schema, - { key?: "a" | undefined; a: true } | { key: "b" | null; b: true } - >(true); - - schema.parse({ key: "a", a: true }); - schema.parse({ key: undefined, a: true }); - schema.parse({ key: "b", b: true }); - schema.parse({ key: null, b: true }); - expect(() => { - schema.parse({ key: null, a: true }); - }).toThrow(); - expect(() => { - schema.parse({ key: "b", a: true }); - }).toThrow(); - - const value = schema.parse({ key: null, b: true }); - - if (!("key" in value)) value.a; - if (value.key === undefined) value.a; - if (value.key === "a") value.a; - if (value.key === "b") value.b; - if (value.key === null) value.b; -}); diff --git a/deno/lib/__tests__/enum.test.ts b/deno/lib/__tests__/enum.test.ts deleted file mode 100644 index 819d3264f..000000000 --- a/deno/lib/__tests__/enum.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -// @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"; - -test("create enum", () => { - const MyEnum = z.enum(["Red", "Green", "Blue"]); - expect(MyEnum.Values.Red).toEqual("Red"); - expect(MyEnum.Enum.Red).toEqual("Red"); - expect(MyEnum.enum.Red).toEqual("Red"); -}); - -test("infer enum", () => { - const MyEnum = z.enum(["Red", "Green", "Blue"]); - type MyEnum = z.infer<typeof MyEnum>; - util.assertEqual<MyEnum, "Red" | "Green" | "Blue">(true); -}); - -test("get options", () => { - expect(z.enum(["tuna", "trout"]).options).toEqual(["tuna", "trout"]); -}); - -test("readonly enum", () => { - const HTTP_SUCCESS = ["200", "201"] as const; - const arg = z.enum(HTTP_SUCCESS); - type arg = z.infer<typeof arg>; - util.assertEqual<arg, "200" | "201">(true); - - arg.parse("201"); - expect(() => arg.parse("202")).toThrow(); -}); - -test("error params", () => { - const result = z - .enum(["test"], { required_error: "REQUIRED" }) - .safeParse(undefined); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].message).toEqual("REQUIRED"); - } -}); - -test("extract/exclude", () => { - const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const; - const FoodEnum = z.enum(foods); - const ItalianEnum = FoodEnum.extract(["Pasta", "Pizza"]); - const UnhealthyEnum = FoodEnum.exclude(["Salad"]); - const EmptyFoodEnum = FoodEnum.exclude(foods); - - util.assertEqual<z.infer<typeof ItalianEnum>, "Pasta" | "Pizza">(true); - util.assertEqual< - z.infer<typeof UnhealthyEnum>, - "Pasta" | "Pizza" | "Tacos" | "Burgers" - >(true); - // @ts-expect-error TS2344 - util.assertEqual<typeof EmptyFoodEnum, z.ZodEnum<[]>>(true); - util.assertEqual<z.infer<typeof EmptyFoodEnum>, never>(true); -}); - -test("error map in extract/exclude", () => { - const foods = ["Pasta", "Pizza", "Tacos", "Burgers", "Salad"] as const; - const FoodEnum = z.enum(foods, { - errorMap: () => ({ message: "This is not food!" }), - }); - const ItalianEnum = FoodEnum.extract(["Pasta", "Pizza"]); - const foodsError = FoodEnum.safeParse("Cucumbers"); - const italianError = ItalianEnum.safeParse("Tacos"); - if (!foodsError.success && !italianError.success) { - expect(foodsError.error.issues[0].message).toEqual( - italianError.error.issues[0].message - ); - } - - const UnhealthyEnum = FoodEnum.exclude(["Salad"], { - errorMap: () => ({ message: "This is not healthy food!" }), - }); - const unhealthyError = UnhealthyEnum.safeParse("Salad"); - if (!unhealthyError.success) { - expect(unhealthyError.error.issues[0].message).toEqual( - "This is not healthy food!" - ); - } -}); diff --git a/deno/lib/__tests__/error.test.ts b/deno/lib/__tests__/error.test.ts deleted file mode 100644 index 617379b30..000000000 --- a/deno/lib/__tests__/error.test.ts +++ /dev/null @@ -1,542 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import { ZodParsedType } from "../helpers/util.ts"; -import * as z from "../index.ts"; -import { ZodError, ZodIssueCode } from "../ZodError.ts"; - -test("error creation", () => { - const err1 = ZodError.create([]); - err1.addIssue({ - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ZodParsedType.string, - path: [], - message: "", - fatal: true, - }); - err1.isEmpty; - - const err2 = ZodError.create(err1.issues); - const err3 = new ZodError([]); - err3.addIssues(err1.issues); - err3.addIssue(err1.issues[0]); - err1.message; - err2.message; - err3.message; -}); - -const errorMap: z.ZodErrorMap = (error, ctx) => { - if (error.code === ZodIssueCode.invalid_type) { - if (error.expected === "string") { - return { message: "bad type!" }; - } - } - if (error.code === ZodIssueCode.custom) { - return { message: `less-than-${(error.params || {}).minimum}` }; - } - return { message: ctx.defaultError }; -}; - -test("type error with custom error map", () => { - try { - z.string().parse(234, { errorMap }); - } catch (err) { - const zerr: z.ZodError = err as any; - - expect(zerr.issues[0].code).toEqual(z.ZodIssueCode.invalid_type); - expect(zerr.issues[0].message).toEqual(`bad type!`); - } -}); - -test("refinement fail with params", () => { - try { - z.number() - .refine((val) => val >= 3, { - params: { minimum: 3 }, - }) - .parse(2, { errorMap }); - } catch (err) { - const zerr: z.ZodError = err as any; - expect(zerr.issues[0].code).toEqual(z.ZodIssueCode.custom); - expect(zerr.issues[0].message).toEqual(`less-than-3`); - } -}); - -test("custom error with custom errormap", () => { - try { - z.string() - .refine((val) => val.length > 12, { - params: { minimum: 13 }, - message: "override", - }) - .parse("asdf", { errorMap }); - } catch (err) { - const zerr: z.ZodError = err as any; - expect(zerr.issues[0].message).toEqual("override"); - } -}); - -test("default error message", () => { - try { - z.number() - .refine((x) => x > 3) - .parse(2); - } catch (err) { - const zerr: z.ZodError = err as any; - expect(zerr.issues.length).toEqual(1); - expect(zerr.issues[0].message).toEqual("Invalid input"); - } -}); - -test("override error in refine", () => { - try { - z.number() - .refine((x) => x > 3, "override") - .parse(2); - } catch (err) { - const zerr: z.ZodError = err as any; - expect(zerr.issues.length).toEqual(1); - expect(zerr.issues[0].message).toEqual("override"); - } -}); - -test("override error in refinement", () => { - try { - z.number() - .refine((x) => x > 3, { - message: "override", - }) - .parse(2); - } catch (err) { - const zerr: z.ZodError = err as any; - expect(zerr.issues.length).toEqual(1); - expect(zerr.issues[0].message).toEqual("override"); - } -}); - -test("array minimum", () => { - try { - z.array(z.string()).min(3, "tooshort").parse(["asdf", "qwer"]); - } catch (err) { - const zerr: ZodError = err as any; - expect(zerr.issues[0].code).toEqual(ZodIssueCode.too_small); - expect(zerr.issues[0].message).toEqual("tooshort"); - } - try { - z.array(z.string()).min(3).parse(["asdf", "qwer"]); - } catch (err) { - const zerr: ZodError = err as any; - expect(zerr.issues[0].code).toEqual(ZodIssueCode.too_small); - expect(zerr.issues[0].message).toEqual( - `Array must contain at least 3 element(s)` - ); - } -}); - -// implement test for semi-smart union logic that checks for type error on either left or right -// test("union smart errors", () => { -// // expect.assertions(2); - -// const p1 = z -// .union([z.string(), z.number().refine((x) => x > 0)]) -// .safeParse(-3.2); - -// if (p1.success === true) throw new Error(); -// expect(p1.success).toBe(false); -// expect(p1.error.issues[0].code).toEqual(ZodIssueCode.custom); - -// const p2 = z.union([z.string(), z.number()]).safeParse(false); -// // .catch(err => expect(err.issues[0].code).toEqual(ZodIssueCode.invalid_union)); -// if (p2.success === true) throw new Error(); -// expect(p2.success).toBe(false); -// expect(p2.error.issues[0].code).toEqual(ZodIssueCode.invalid_union); -// }); - -test("custom path in custom error map", () => { - const schema = z.object({ - items: z.array(z.string()).refine((data) => data.length > 3, { - path: ["items-too-few"], - }), - }); - - const errorMap: z.ZodErrorMap = (error) => { - expect(error.path.length).toBe(2); - return { message: "doesnt matter" }; - }; - const result = schema.safeParse({ items: ["first"] }, { errorMap }); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].path).toEqual(["items", "items-too-few"]); - } -}); - -test("error metadata from value", () => { - const dynamicRefine = z.string().refine( - (val) => val === val.toUpperCase(), - (val) => ({ params: { val } }) - ); - - const result = dynamicRefine.safeParse("asdf"); - expect(result.success).toEqual(false); - if (!result.success) { - const sub = result.error.issues[0]; - expect(result.error.issues[0].code).toEqual("custom"); - if (sub.code === "custom") { - expect(sub.params!.val).toEqual("asdf"); - } - } -}); - -// test("don't call refine after validation failed", () => { -// const asdf = z -// .union([ -// z.number(), -// z.string().transform(z.number(), (val) => { -// return parseFloat(val); -// }), -// ]) -// .refine((v) => v >= 1); - -// expect(() => asdf.safeParse("foo")).not.toThrow(); -// }); - -test("root level formatting", () => { - const schema = z.string().email(); - const result = schema.safeParse("asdfsdf"); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.format()._errors).toEqual(["Invalid email"]); - } -}); - -test("custom path", () => { - const schema = z - .object({ - password: z.string(), - confirm: z.string(), - }) - .refine((val) => val.confirm === val.password, { path: ["confirm"] }); - - const result = schema.safeParse({ - password: "peanuts", - confirm: "qeanuts", - }); - - expect(result.success).toEqual(false); - if (!result.success) { - // nested errors - const error = result.error.format(); - expect(error._errors).toEqual([]); - expect(error.password?._errors).toEqual(undefined); - expect(error.confirm?._errors).toEqual(["Invalid input"]); - } -}); - -test("custom path", () => { - const schema = z - .object({ - password: z.string().min(6), - confirm: z.string().min(6), - }) - .refine((val) => val.confirm === val.password); - - const result = schema.safeParse({ - password: "qwer", - confirm: "asdf", - }); - - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues.length).toEqual(3); - } -}); - -const schema = z.object({ - inner: z.object({ - name: z - .string() - .refine((val) => val.length > 5) - .array() - .refine((val) => val.length <= 1), - }), -}); - -test("no abort early on refinements", () => { - const invalidItem = { - inner: { name: ["aasd", "asdfasdfasfd"] }, - }; - - const result1 = schema.safeParse(invalidItem); - expect(result1.success).toEqual(false); - if (!result1.success) { - expect(result1.error.issues.length).toEqual(2); - } -}); -test("formatting", () => { - const invalidItem = { - inner: { name: ["aasd", "asdfasdfasfd"] }, - }; - const invalidArray = { - inner: { name: ["asdfasdf", "asdfasdfasfd"] }, - }; - const result1 = schema.safeParse(invalidItem); - const result2 = schema.safeParse(invalidArray); - - expect(result1.success).toEqual(false); - expect(result2.success).toEqual(false); - if (!result1.success) { - const error = result1.error.format(); - - expect(error._errors).toEqual([]); - expect(error.inner?._errors).toEqual([]); - // expect(error.inner?.name?._errors).toEqual(["Invalid input"]); - // expect(error.inner?.name?.[0]._errors).toEqual(["Invalid input"]); - expect(error.inner?.name?.[1]).toEqual(undefined); - } - if (!result2.success) { - type FormattedError = z.inferFormattedError<typeof schema>; - const error: FormattedError = result2.error.format(); - expect(error._errors).toEqual([]); - expect(error.inner?._errors).toEqual([]); - expect(error.inner?.name?._errors).toEqual(["Invalid input"]); - expect(error.inner?.name?.[0]).toEqual(undefined); - expect(error.inner?.name?.[1]).toEqual(undefined); - expect(error.inner?.name?.[2]).toEqual(undefined); - } - - // test custom mapper - if (!result2.success) { - type FormattedError = z.inferFormattedError<typeof schema, number>; - const error: FormattedError = result2.error.format(() => 5); - expect(error._errors).toEqual([]); - expect(error.inner?._errors).toEqual([]); - expect(error.inner?.name?._errors).toEqual([5]); - } -}); - -test("formatting with nullable and optional fields", () => { - const nameSchema = z.string().refine((val) => val.length > 5); - const schema = z.object({ - nullableObject: z.object({ name: nameSchema }).nullable(), - nullableArray: z.array(nameSchema).nullable(), - nullableTuple: z.tuple([nameSchema, nameSchema, z.number()]).nullable(), - optionalObject: z.object({ name: nameSchema }).optional(), - optionalArray: z.array(nameSchema).optional(), - optionalTuple: z.tuple([nameSchema, nameSchema, z.number()]).optional(), - }); - const invalidItem = { - nullableObject: { name: "abcd" }, - nullableArray: ["abcd"], - nullableTuple: ["abcd", "abcd", 1], - optionalObject: { name: "abcd" }, - optionalArray: ["abcd"], - optionalTuple: ["abcd", "abcd", 1], - }; - const result = schema.safeParse(invalidItem); - expect(result.success).toEqual(false); - if (!result.success) { - type FormattedError = z.inferFormattedError<typeof schema>; - const error: FormattedError = result.error.format(); - expect(error._errors).toEqual([]); - expect(error.nullableObject?._errors).toEqual([]); - expect(error.nullableObject?.name?._errors).toEqual(["Invalid input"]); - expect(error.nullableArray?._errors).toEqual([]); - expect(error.nullableArray?.[0]?._errors).toEqual(["Invalid input"]); - expect(error.nullableTuple?._errors).toEqual([]); - expect(error.nullableTuple?.[0]?._errors).toEqual(["Invalid input"]); - expect(error.nullableTuple?.[1]?._errors).toEqual(["Invalid input"]); - expect(error.optionalObject?._errors).toEqual([]); - expect(error.optionalObject?.name?._errors).toEqual(["Invalid input"]); - expect(error.optionalArray?._errors).toEqual([]); - expect(error.optionalArray?.[0]?._errors).toEqual(["Invalid input"]); - expect(error.optionalTuple?._errors).toEqual([]); - expect(error.optionalTuple?.[0]?._errors).toEqual(["Invalid input"]); - expect(error.optionalTuple?.[1]?._errors).toEqual(["Invalid input"]); - } -}); - -const stringWithCustomError = z.string({ - errorMap: (issue, ctx) => ({ - message: - issue.code === "invalid_type" - ? ctx.data - ? "Invalid name" - : "Name is required" - : ctx.defaultError, - }), -}); - -test("schema-bound error map", () => { - const result = stringWithCustomError.safeParse(1234); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].message).toEqual("Invalid name"); - } - - const result2 = stringWithCustomError.safeParse(undefined); - expect(result2.success).toEqual(false); - if (!result2.success) { - expect(result2.error.issues[0].message).toEqual("Name is required"); - } - - // support contextual override - const result3 = stringWithCustomError.safeParse(undefined, { - errorMap: () => ({ message: "OVERRIDE" }), - }); - expect(result3.success).toEqual(false); - if (!result3.success) { - expect(result3.error.issues[0].message).toEqual("OVERRIDE"); - } -}); - -test("overrideErrorMap", () => { - // support overrideErrorMap - z.setErrorMap(() => ({ message: "OVERRIDE" })); - const result4 = stringWithCustomError.min(10).safeParse("tooshort"); - expect(result4.success).toEqual(false); - if (!result4.success) { - expect(result4.error.issues[0].message).toEqual("OVERRIDE"); - } - z.setErrorMap(z.defaultErrorMap); -}); - -test("invalid and required", () => { - const str = z.string({ - invalid_type_error: "Invalid name", - required_error: "Name is required", - }); - const result1 = str.safeParse(1234); - expect(result1.success).toEqual(false); - if (!result1.success) { - expect(result1.error.issues[0].message).toEqual("Invalid name"); - } - const result2 = str.safeParse(undefined); - expect(result2.success).toEqual(false); - if (!result2.success) { - expect(result2.error.issues[0].message).toEqual("Name is required"); - } -}); - -test("Fallback to default required error", () => { - const str = z.string({ - invalid_type_error: "Invalid name", - // required_error: "Name is required", - }); - - const result2 = str.safeParse(undefined); - expect(result2.success).toEqual(false); - if (!result2.success) { - expect(result2.error.issues[0].message).toEqual("Required"); - } -}); - -test("invalid and required and errorMap", () => { - expect(() => { - return z.string({ - invalid_type_error: "Invalid name", - required_error: "Name is required", - errorMap: () => ({ message: "OVERRIDE" }), - }); - }).toThrow(); -}); - -test("strict error message", () => { - const errorMsg = "Invalid object"; - const obj = z.object({ x: z.string() }).strict(errorMsg); - const result = obj.safeParse({ x: "a", y: "b" }); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].message).toEqual(errorMsg); - } -}); - -test("enum error message, invalid enum elementstring", () => { - try { - z.enum(["Tuna", "Trout"]).parse("Salmon"); - } catch (err) { - const zerr: z.ZodError = err as any; - expect(zerr.issues.length).toEqual(1); - expect(zerr.issues[0].message).toEqual( - "Invalid enum value. Expected 'Tuna' | 'Trout', received 'Salmon'" - ); - } -}); - -test("enum error message, invalid type", () => { - try { - z.enum(["Tuna", "Trout"]).parse(12); - } catch (err) { - const zerr: z.ZodError = err as any; - expect(zerr.issues.length).toEqual(1); - expect(zerr.issues[0].message).toEqual( - "Expected 'Tuna' | 'Trout', received number" - ); - } -}); - -test("nativeEnum default error message", () => { - enum Fish { - Tuna = "Tuna", - Trout = "Trout", - } - try { - z.nativeEnum(Fish).parse("Salmon"); - } catch (err) { - const zerr: z.ZodError = err as any; - expect(zerr.issues.length).toEqual(1); - expect(zerr.issues[0].message).toEqual( - "Invalid enum value. Expected 'Tuna' | 'Trout', received 'Salmon'" - ); - } -}); - -test("literal default error message", () => { - try { - z.literal("Tuna").parse("Trout"); - } catch (err) { - const zerr: z.ZodError = err as any; - expect(zerr.issues.length).toEqual(1); - expect(zerr.issues[0].message).toEqual( - `Invalid literal value, expected "Tuna"` - ); - } -}); - -test("literal bigint default error message", () => { - try { - z.literal(BigInt(12)).parse(BigInt(13)); - } catch (err) { - const zerr: z.ZodError = err as any; - expect(zerr.issues.length).toEqual(1); - expect(zerr.issues[0].message).toEqual( - `Invalid literal value, expected "12"` - ); - } -}); - -test("when the message is falsy, it is used as is provided", () => { - const schema = z.string().max(1, { message: "" }); - const result = schema.safeParse("asdf"); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].message).toEqual(""); - } -}); - -// test("dont short circuit on continuable errors", () => { -// const user = z -// .object({ -// password: z.string().min(6), -// confirm: z.string(), -// }) -// .refine((data) => data.password === data.confirm, { -// message: "Passwords don't match", -// path: ["confirm"], -// }); -// const result = user.safeParse({ password: "asdf", confirm: "qwer" }); -// if (!result.success) { -// expect(result.error.issues.length).toEqual(2); -// } -// }); diff --git a/deno/lib/__tests__/firstparty.test.ts b/deno/lib/__tests__/firstparty.test.ts deleted file mode 100644 index 93cb471b3..000000000 --- a/deno/lib/__tests__/firstparty.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -// @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"; - -test("first party switch", () => { - const myType = z.string() as z.ZodFirstPartySchemaTypes; - const def = myType._def; - - switch (def.typeName) { - case z.ZodFirstPartyTypeKind.ZodString: - break; - case z.ZodFirstPartyTypeKind.ZodNumber: - break; - case z.ZodFirstPartyTypeKind.ZodNaN: - break; - case z.ZodFirstPartyTypeKind.ZodBigInt: - break; - case z.ZodFirstPartyTypeKind.ZodBoolean: - break; - case z.ZodFirstPartyTypeKind.ZodDate: - break; - case z.ZodFirstPartyTypeKind.ZodUndefined: - break; - case z.ZodFirstPartyTypeKind.ZodNull: - break; - case z.ZodFirstPartyTypeKind.ZodAny: - break; - case z.ZodFirstPartyTypeKind.ZodUnknown: - break; - case z.ZodFirstPartyTypeKind.ZodNever: - break; - case z.ZodFirstPartyTypeKind.ZodVoid: - break; - case z.ZodFirstPartyTypeKind.ZodArray: - break; - case z.ZodFirstPartyTypeKind.ZodObject: - break; - case z.ZodFirstPartyTypeKind.ZodUnion: - break; - case z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: - break; - case z.ZodFirstPartyTypeKind.ZodIntersection: - break; - case z.ZodFirstPartyTypeKind.ZodTuple: - break; - case z.ZodFirstPartyTypeKind.ZodRecord: - break; - case z.ZodFirstPartyTypeKind.ZodMap: - break; - case z.ZodFirstPartyTypeKind.ZodSet: - break; - case z.ZodFirstPartyTypeKind.ZodFunction: - break; - case z.ZodFirstPartyTypeKind.ZodLazy: - break; - case z.ZodFirstPartyTypeKind.ZodLiteral: - break; - case z.ZodFirstPartyTypeKind.ZodEnum: - break; - case z.ZodFirstPartyTypeKind.ZodEffects: - break; - case z.ZodFirstPartyTypeKind.ZodNativeEnum: - break; - case z.ZodFirstPartyTypeKind.ZodOptional: - break; - case z.ZodFirstPartyTypeKind.ZodNullable: - break; - case z.ZodFirstPartyTypeKind.ZodDefault: - break; - case z.ZodFirstPartyTypeKind.ZodCatch: - break; - case z.ZodFirstPartyTypeKind.ZodPromise: - break; - case z.ZodFirstPartyTypeKind.ZodBranded: - break; - case z.ZodFirstPartyTypeKind.ZodPipeline: - break; - case z.ZodFirstPartyTypeKind.ZodSymbol: - break; - case z.ZodFirstPartyTypeKind.ZodReadonly: - break; - case z.ZodFirstPartyTypeKind.ZodTemplateLiteral: - break; - default: - util.assertNever(def); - } -}); diff --git a/deno/lib/__tests__/firstpartyschematypes.test.ts b/deno/lib/__tests__/firstpartyschematypes.test.ts deleted file mode 100644 index 96e78d796..000000000 --- a/deno/lib/__tests__/firstpartyschematypes.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import { ZodFirstPartySchemaTypes, ZodFirstPartyTypeKind } from "../index.ts"; -import { util } from "../helpers/util.ts"; - -test("Identify missing [ZodFirstPartySchemaTypes]", () => { - type ZodFirstPartySchemaForType<T extends ZodFirstPartyTypeKind> = - ZodFirstPartySchemaTypes extends infer Schema - ? Schema extends { _def: { typeName: T } } - ? Schema - : never - : never; - type ZodMappedTypes = { - [key in ZodFirstPartyTypeKind]: ZodFirstPartySchemaForType<key>; - }; - type ZodFirstPartySchemaTypesMissingFromUnion = keyof { - [key in keyof ZodMappedTypes as ZodMappedTypes[key] extends { _def: never } - ? key - : never]: unknown; - }; - - util.assertEqual<ZodFirstPartySchemaTypesMissingFromUnion, never>(true); -}); diff --git a/deno/lib/__tests__/function.test.ts b/deno/lib/__tests__/function.test.ts deleted file mode 100644 index 675891e6d..000000000 --- a/deno/lib/__tests__/function.test.ts +++ /dev/null @@ -1,272 +0,0 @@ -// @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"; - -const args1 = z.tuple([z.string()]); -const returns1 = z.number(); -const func1 = z.function(args1, returns1); - -test("function parsing", () => { - const parsed = func1.parse((arg: any) => arg.length); - parsed("asdf"); -}); - -test("parsed function fail 1", () => { - const parsed = func1.parse((x: string) => x); - expect(() => parsed("asdf")).toThrow(); -}); - -test("parsed function fail 2", () => { - const parsed = func1.parse((x: string) => x); - expect(() => parsed(13 as any)).toThrow(); -}); - -test("function inference 1", () => { - type func1 = z.TypeOf<typeof func1>; - util.assertEqual<func1, (k: string) => number>(true); -}); - -test("method parsing", () => { - const methodObject = z.object({ - property: z.number(), - method: z.function().args(z.string()).returns(z.number()), - }); - const methodInstance = { - property: 3, - method: function (s: string) { - return s.length + this.property; - }, - }; - const parsed = methodObject.parse(methodInstance); - expect(parsed.method("length=8")).toBe(11); // 8 length + 3 property -}); - -test("async method parsing", async () => { - const methodObject = z.object({ - property: z.number(), - method: z.function().args(z.string()).returns(z.promise(z.number())), - }); - const methodInstance = { - property: 3, - method: async function (s: string) { - return s.length + this.property; - }, - }; - const parsed = methodObject.parse(methodInstance); - expect(await parsed.method("length=8")).toBe(11); // 8 length + 3 property -}); - -test("args method", () => { - const t1 = z.function(); - type t1 = z.infer<typeof t1>; - util.assertEqual<t1, (...args_1: unknown[]) => unknown>(true); - - const t2 = t1.args(z.string()); - type t2 = z.infer<typeof t2>; - util.assertEqual<t2, (arg: string, ...args_1: unknown[]) => unknown>(true); - - const t3 = t2.returns(z.boolean()); - type t3 = z.infer<typeof t3>; - util.assertEqual<t3, (arg: string, ...args_1: unknown[]) => boolean>(true); -}); - -const args2 = z.tuple([ - z.object({ - f1: z.number(), - f2: z.string().nullable(), - f3: z.array(z.boolean().optional()).optional(), - }), -]); -const returns2 = z.union([z.string(), z.number()]); - -const func2 = z.function(args2, returns2); - -test("function inference 2", () => { - type func2 = z.TypeOf<typeof func2>; - util.assertEqual< - func2, - (arg: { - f1: number; - f2: string | null; - f3?: (boolean | undefined)[] | undefined; - }) => string | number - >(true); -}); - -test("valid function run", () => { - const validFunc2Instance = func2.validate((_x) => { - return "adf" as any; - }); - - const checker = () => { - validFunc2Instance({ - f1: 21, - f2: "asdf", - f3: [true, false], - }); - }; - - checker(); -}); - -test("input validation error", () => { - const invalidFuncInstance = func2.validate((_x) => { - return "adf" as any; - }); - - const checker = () => { - invalidFuncInstance("Invalid_input" as any); - }; - - expect(checker).toThrow(); -}); - -test("output validation error", () => { - const invalidFuncInstance = func2.validate((_x) => { - return ["this", "is", "not", "valid", "output"] as any; - }); - - const checker = () => { - invalidFuncInstance({ - f1: 21, - f2: "asdf", - f3: [true, false], - }); - }; - - expect(checker).toThrow(); -}); - -z.function(z.tuple([z.string()])).args()._def.args; - -test("special function error codes", () => { - const checker = z - .function(z.tuple([z.string()]), z.boolean()) - .implement((arg) => { - return arg.length as any; - }); - try { - checker("12" as any); - } catch (err) { - const zerr = err as z.ZodError; - const first = zerr.issues[0]; - if (first.code !== z.ZodIssueCode.invalid_return_type) throw new Error(); - - expect(first.returnTypeError).toBeInstanceOf(z.ZodError); - } - - try { - checker(12 as any); - } catch (err) { - const zerr = err as z.ZodError; - const first = zerr.issues[0]; - if (first.code !== z.ZodIssueCode.invalid_arguments) throw new Error(); - expect(first.argumentsError).toBeInstanceOf(z.ZodError); - } -}); - -test("function with async refinements", async () => { - const func = z - .function() - .args(z.string().refine(async (val) => val.length > 10)) - .returns(z.promise(z.number().refine(async (val) => val > 10))) - .implement(async (val) => { - return val.length; - }); - const results = []; - try { - await func("asdfasdf"); - results.push("success"); - } catch (err) { - results.push("fail"); - } - try { - await func("asdflkjasdflkjsf"); - results.push("success"); - } catch (err) { - results.push("fail"); - } - - expect(results).toEqual(["fail", "success"]); -}); - -test("non async function with async refinements should fail", async () => { - const func = z - .function() - .args(z.string().refine(async (val) => val.length > 10)) - .returns(z.number().refine(async (val) => val > 10)) - .implement((val) => { - return val.length; - }); - - const results = []; - try { - await func("asdasdfasdffasdf"); - results.push("success"); - } catch (err) { - results.push("fail"); - } - - expect(results).toEqual(["fail"]); -}); - -test("allow extra parameters", () => { - const maxLength5 = z - .function() - .args(z.string()) - .returns(z.boolean()) - .implement((str, _arg, _qewr) => { - return str.length <= 5; - }); - - const filteredList = [ - "apple", - "orange", - "pear", - "banana", - "strawberry", - ].filter(maxLength5); - expect(filteredList.length).toEqual(2); -}); - -test("params and returnType getters", () => { - const func = z.function().args(z.string()).returns(z.string()); - - func.parameters().items[0].parse("asdf"); - func.returnType().parse("asdf"); -}); - -test("inference with transforms", () => { - const funcSchema = z - .function() - .args(z.string().transform((val) => val.length)) - .returns(z.object({ val: z.number() })); - const myFunc = funcSchema.implement((val) => { - return { val, extra: "stuff" }; - }); - myFunc("asdf"); - - util.assertEqual< - typeof myFunc, - (arg: string, ...args_1: unknown[]) => { val: number; extra: string } - >(true); -}); - -test("fallback to OuterTypeOfFunction", () => { - const funcSchema = z - .function() - .args(z.string().transform((val) => val.length)) - .returns(z.object({ arg: z.number() }).transform((val) => val.arg)); - - const myFunc = funcSchema.implement((val) => { - return { arg: val, arg2: false }; - }); - - util.assertEqual< - typeof myFunc, - (arg: string, ...args_1: unknown[]) => number - >(true); -}); diff --git a/deno/lib/__tests__/generics.test.ts b/deno/lib/__tests__/generics.test.ts deleted file mode 100644 index 911b28629..000000000 --- a/deno/lib/__tests__/generics.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -// @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"; - -test("generics", () => { - async function stripOuter<TData extends z.ZodTypeAny>( - schema: TData, - data: unknown - ) { - return z - .object({ - nested: schema, // as z.ZodTypeAny, - }) - .transform((data) => { - return data.nested!; - }) - .parse({ nested: data }); - } - - const result = stripOuter(z.object({ a: z.string() }), { a: "asdf" }); - util.assertEqual<typeof result, Promise<{ a: string }>>(true); -}); - -test("assignability", () => { - const createSchemaAndParse = <K extends string, VS extends z.ZodString>( - key: K, - valueSchema: VS, - data: unknown - ) => { - const schema = z.object({ - [key]: valueSchema, - }); - const parsed = schema.parse(data); - const inferred: z.infer<z.ZodObject<{ [k in K]: VS }>> = parsed; - return inferred; - }; - createSchemaAndParse("foo", z.string(), { foo: "" }); -}); diff --git a/deno/lib/__tests__/instanceof.test.ts b/deno/lib/__tests__/instanceof.test.ts deleted file mode 100644 index 2f1f9187c..000000000 --- a/deno/lib/__tests__/instanceof.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @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"; - -test("instanceof", async () => { - class Test {} - class Subtest extends Test {} - abstract class AbstractBar { - constructor(public val: string) {} - } - class Bar extends AbstractBar {} - - const TestSchema = z.instanceof(Test); - const SubtestSchema = z.instanceof(Subtest); - const AbstractSchema = z.instanceof(AbstractBar); - const BarSchema = z.instanceof(Bar); - - TestSchema.parse(new Test()); - TestSchema.parse(new Subtest()); - SubtestSchema.parse(new Subtest()); - AbstractSchema.parse(new Bar("asdf")); - const bar = BarSchema.parse(new Bar("asdf")); - expect(bar.val).toEqual("asdf"); - - await expect(() => SubtestSchema.parse(new Test())).toThrow( - /Input not instance of Subtest/ - ); - await expect(() => TestSchema.parse(12)).toThrow( - /Input not instance of Test/ - ); - - util.assertEqual<Test, z.infer<typeof TestSchema>>(true); -}); - -test("instanceof fatal", () => { - const schema = z.instanceof(Date).refine((d) => d.toString()); - const res = schema.safeParse(null); - expect(res.success).toBe(false); -}); diff --git a/deno/lib/__tests__/intersection.test.ts b/deno/lib/__tests__/intersection.test.ts deleted file mode 100644 index 9e647ffa0..000000000 --- a/deno/lib/__tests__/intersection.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("object intersection", () => { - const BaseTeacher = z.object({ - subjects: z.array(z.string()), - }); - const HasID = z.object({ id: z.string() }); - - const Teacher = z.intersection(BaseTeacher.passthrough(), HasID); // BaseTeacher.merge(HasID); - const data = { - subjects: ["math"], - id: "asdfasdf", - }; - expect(Teacher.parse(data)).toEqual(data); - expect(() => Teacher.parse({ subject: data.subjects })).toThrow(); - expect(Teacher.parse({ ...data, extra: 12 })).toEqual({ ...data, extra: 12 }); - - expect(() => - z.intersection(BaseTeacher.strict(), HasID).parse({ ...data, extra: 12 }) - ).toThrow(); -}); - -test("deep intersection", () => { - const Animal = z.object({ - properties: z.object({ - is_animal: z.boolean(), - }), - }); - const Cat = z - .object({ - properties: z.object({ - jumped: z.boolean(), - }), - }) - .and(Animal); - - type Cat = z.infer<typeof Cat>; - // const cat:Cat = 'asdf' as any; - const cat = Cat.parse({ properties: { is_animal: true, jumped: true } }); - expect(cat.properties).toEqual({ is_animal: true, jumped: true }); -}); - -test("deep intersection of arrays", async () => { - const Author = z.object({ - posts: z.array( - z.object({ - post_id: z.number(), - }) - ), - }); - const Registry = z - .object({ - posts: z.array( - z.object({ - title: z.string(), - }) - ), - }) - .and(Author); - - const posts = [ - { post_id: 1, title: "Novels" }, - { post_id: 2, title: "Fairy tales" }, - ]; - const cat = Registry.parse({ posts }); - expect(cat.posts).toEqual(posts); - const asyncCat = await Registry.parseAsync({ posts }); - expect(asyncCat.posts).toEqual(posts); -}); - -test("invalid intersection types", async () => { - const numberIntersection = z.intersection( - z.number(), - z.number().transform((x) => x + 1) - ); - - const syncResult = numberIntersection.safeParse(1234); - expect(syncResult.success).toEqual(false); - if (!syncResult.success) { - expect(syncResult.error.issues[0].code).toEqual( - z.ZodIssueCode.invalid_intersection_types - ); - } - - const asyncResult = await numberIntersection.spa(1234); - expect(asyncResult.success).toEqual(false); - if (!asyncResult.success) { - expect(asyncResult.error.issues[0].code).toEqual( - z.ZodIssueCode.invalid_intersection_types - ); - } -}); - -test("invalid array merge", async () => { - const stringArrInt = z.intersection( - z.string().array(), - z - .string() - .array() - .transform((val) => [...val, "asdf"]) - ); - const syncResult = stringArrInt.safeParse(["asdf", "qwer"]); - expect(syncResult.success).toEqual(false); - if (!syncResult.success) { - expect(syncResult.error.issues[0].code).toEqual( - z.ZodIssueCode.invalid_intersection_types - ); - } - - const asyncResult = await stringArrInt.spa(["asdf", "qwer"]); - expect(asyncResult.success).toEqual(false); - if (!asyncResult.success) { - expect(asyncResult.error.issues[0].code).toEqual( - z.ZodIssueCode.invalid_intersection_types - ); - } -}); diff --git a/deno/lib/__tests__/literal.test.ts b/deno/lib/__tests__/literal.test.ts deleted file mode 100644 index b3f074162..000000000 --- a/deno/lib/__tests__/literal.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -const literalTuna = z.literal("tuna"); -const literalFortyTwo = z.literal(42); -const literalTrue = z.literal(true); - -const terrificSymbol = Symbol("terrific"); -const literalTerrificSymbol = z.literal(terrificSymbol); - -test("passing validations", () => { - literalTuna.parse("tuna"); - literalFortyTwo.parse(42); - literalTrue.parse(true); - literalTerrificSymbol.parse(terrificSymbol); -}); - -test("failing validations", () => { - expect(() => literalTuna.parse("shark")).toThrow(); - expect(() => literalFortyTwo.parse(43)).toThrow(); - expect(() => literalTrue.parse(false)).toThrow(); - expect(() => literalTerrificSymbol.parse(Symbol("terrific"))).toThrow(); -}); - -test("invalid_literal should have `received` field with data", () => { - const data = "shark"; - const result = literalTuna.safeParse(data); - if (!result.success) { - const issue = result.error.issues[0]; - if (issue.code === "invalid_literal") { - expect(issue.received).toBe(data); - } - } -}); diff --git a/deno/lib/__tests__/map.test.ts b/deno/lib/__tests__/map.test.ts deleted file mode 100644 index 9a2a6d783..000000000 --- a/deno/lib/__tests__/map.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -// @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 { ZodIssueCode } from "../index.ts"; - -const stringMap = z.map(z.string(), z.string()); -type stringMap = z.infer<typeof stringMap>; - -test("type inference", () => { - util.assertEqual<stringMap, Map<string, string>>(true); -}); - -test("valid parse", () => { - const result = stringMap.safeParse( - new Map([ - ["first", "foo"], - ["second", "bar"], - ]) - ); - expect(result.success).toEqual(true); - if (result.success) { - expect(result.data.has("first")).toEqual(true); - expect(result.data.has("second")).toEqual(true); - expect(result.data.get("first")).toEqual("foo"); - expect(result.data.get("second")).toEqual("bar"); - } -}); - -test("valid parse async", async () => { - const result = await stringMap.spa( - new Map([ - ["first", "foo"], - ["second", "bar"], - ]) - ); - expect(result.success).toEqual(true); - if (result.success) { - expect(result.data.has("first")).toEqual(true); - expect(result.data.has("second")).toEqual(true); - expect(result.data.get("first")).toEqual("foo"); - expect(result.data.get("second")).toEqual("bar"); - } -}); - -test("throws when a Set is given", () => { - const result = stringMap.safeParse(new Set([])); - expect(result.success).toEqual(false); - if (result.success === false) { - expect(result.error.issues.length).toEqual(1); - expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); - } -}); - -test("throws when the given map has invalid key and invalid input", () => { - const result = stringMap.safeParse(new Map([[42, Symbol()]])); - expect(result.success).toEqual(false); - if (result.success === false) { - expect(result.error.issues.length).toEqual(2); - expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); - expect(result.error.issues[0].path).toEqual([0, "key"]); - expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type); - expect(result.error.issues[1].path).toEqual([0, "value"]); - } -}); - -test("throws when the given map has multiple invalid entries", () => { - // const result = stringMap.safeParse(new Map([[42, Symbol()]])); - - const result = stringMap.safeParse( - new Map([ - [1, "foo"], - ["bar", 2], - ] as [any, any][]) as Map<any, any> - ); - - // const result = stringMap.safeParse(new Map([[42, Symbol()]])); - expect(result.success).toEqual(false); - if (result.success === false) { - expect(result.error.issues.length).toEqual(2); - expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); - expect(result.error.issues[0].path).toEqual([0, "key"]); - expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type); - expect(result.error.issues[1].path).toEqual([1, "value"]); - } -}); - -test("dirty", async () => { - const map = z.map( - z.string().refine((val) => val === val.toUpperCase(), { - message: "Keys must be uppercase", - }), - z.string() - ); - const result = await map.spa( - new Map([ - ["first", "foo"], - ["second", "bar"], - ]) - ); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues.length).toEqual(2); - expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.custom); - expect(result.error.issues[0].message).toEqual("Keys must be uppercase"); - expect(result.error.issues[1].code).toEqual(z.ZodIssueCode.custom); - expect(result.error.issues[1].message).toEqual("Keys must be uppercase"); - } -}); diff --git a/deno/lib/__tests__/masking.test.ts b/deno/lib/__tests__/masking.test.ts deleted file mode 100644 index 81bc14803..000000000 --- a/deno/lib/__tests__/masking.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("masking test", () => {}); - -test("require", () => { - const baseSchema = z.object({ - firstName: z.string(), - middleName: z.string().optional(), - lastName: z.union([z.undefined(), z.string()]), - otherName: z.union([z.string(), z.undefined(), z.string()]), - }); - baseSchema; - // const reqBase = baseSchema.require(); - // const ewr = reqBase.shape; - // expect(ewr.firstName).toBeInstanceOf(z.ZodString); - // expect(ewr.middleName).toBeInstanceOf(z.ZodString); - // expect(ewr.lastName).toBeInstanceOf(z.ZodString); - // expect(ewr.otherName).toBeInstanceOf(z.ZodUnion); -}); diff --git a/deno/lib/__tests__/mocker.test.ts b/deno/lib/__tests__/mocker.test.ts deleted file mode 100644 index 4deaee1f4..000000000 --- a/deno/lib/__tests__/mocker.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import { Mocker } from "./Mocker.ts"; - -test("mocker", () => { - const mocker = new Mocker(); - mocker.string; - mocker.number; - mocker.boolean; - mocker.null; - mocker.undefined; - mocker.stringOptional; - mocker.stringNullable; - mocker.numberOptional; - mocker.numberNullable; - mocker.booleanOptional; - mocker.booleanNullable; -}); diff --git a/deno/lib/__tests__/nan.test.ts b/deno/lib/__tests__/nan.test.ts deleted file mode 100644 index 222d3fb5b..000000000 --- a/deno/lib/__tests__/nan.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -const schema = z.nan(); - -test("passing validations", () => { - schema.parse(NaN); - schema.parse(Number("Not a number")); -}); - -test("failing validations", () => { - expect(() => schema.parse(5)).toThrow(); - expect(() => schema.parse("John")).toThrow(); - expect(() => schema.parse(true)).toThrow(); - expect(() => schema.parse(null)).toThrow(); - expect(() => schema.parse(undefined)).toThrow(); - expect(() => schema.parse({})).toThrow(); - expect(() => schema.parse([])).toThrow(); -}); diff --git a/deno/lib/__tests__/nativeEnum.test.ts b/deno/lib/__tests__/nativeEnum.test.ts deleted file mode 100644 index a8bdea148..000000000 --- a/deno/lib/__tests__/nativeEnum.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -// @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"; - -test("nativeEnum test with consts", () => { - const Fruits: { Apple: "apple"; Banana: "banana" } = { - Apple: "apple", - Banana: "banana", - }; - const fruitEnum = z.nativeEnum(Fruits); - type fruitEnum = z.infer<typeof fruitEnum>; - fruitEnum.parse("apple"); - fruitEnum.parse("banana"); - fruitEnum.parse(Fruits.Apple); - fruitEnum.parse(Fruits.Banana); - util.assertEqual<fruitEnum, "apple" | "banana">(true); -}); - -test("nativeEnum test with real enum", () => { - enum Fruits { - Apple = "apple", - Banana = "banana", - } - // @ts-ignore - const fruitEnum = z.nativeEnum(Fruits); - type fruitEnum = z.infer<typeof fruitEnum>; - fruitEnum.parse("apple"); - fruitEnum.parse("banana"); - fruitEnum.parse(Fruits.Apple); - fruitEnum.parse(Fruits.Banana); - util.assertIs<fruitEnum extends Fruits ? true : false>(true); -}); - -test("nativeEnum test with const with numeric keys", () => { - const FruitValues = { - Apple: 10, - Banana: 20, - // @ts-ignore - } as const; - const fruitEnum = z.nativeEnum(FruitValues); - type fruitEnum = z.infer<typeof fruitEnum>; - fruitEnum.parse(10); - fruitEnum.parse(20); - fruitEnum.parse(FruitValues.Apple); - fruitEnum.parse(FruitValues.Banana); - util.assertEqual<fruitEnum, 10 | 20>(true); -}); - -test("from enum", () => { - enum Fruits { - Cantaloupe, - Apple = "apple", - Banana = "banana", - } - - const FruitEnum = z.nativeEnum(Fruits as any); - type FruitEnum = z.infer<typeof FruitEnum>; - FruitEnum.parse(Fruits.Cantaloupe); - FruitEnum.parse(Fruits.Apple); - FruitEnum.parse("apple"); - FruitEnum.parse(0); - expect(() => FruitEnum.parse(1)).toThrow(); - expect(() => FruitEnum.parse("Apple")).toThrow(); - expect(() => FruitEnum.parse("Cantaloupe")).toThrow(); -}); - -test("from const", () => { - const Greek = { - Alpha: "a", - Beta: "b", - Gamma: 3, - // @ts-ignore - } as const; - - const GreekEnum = z.nativeEnum(Greek); - type GreekEnum = z.infer<typeof GreekEnum>; - GreekEnum.parse("a"); - GreekEnum.parse("b"); - GreekEnum.parse(3); - expect(() => GreekEnum.parse("v")).toThrow(); - expect(() => GreekEnum.parse("Alpha")).toThrow(); - expect(() => GreekEnum.parse(2)).toThrow(); - - expect(GreekEnum.enum.Alpha).toEqual("a"); -}); diff --git a/deno/lib/__tests__/nullable.test.ts b/deno/lib/__tests__/nullable.test.ts deleted file mode 100644 index 4dd9e8094..000000000 --- a/deno/lib/__tests__/nullable.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -function checkErrors(a: z.ZodTypeAny, bad: any) { - let expected; - try { - a.parse(bad); - } catch (error) { - expected = (error as z.ZodError).formErrors; - } - try { - a.nullable().parse(bad); - } catch (error) { - expect((error as z.ZodError).formErrors).toEqual(expected); - } -} - -test("Should have error messages appropriate for the underlying type", () => { - checkErrors(z.string().min(2), 1); - z.string().min(2).nullable().parse(null); - checkErrors(z.number().gte(2), 1); - z.number().gte(2).nullable().parse(null); - checkErrors(z.boolean(), ""); - z.boolean().nullable().parse(null); - checkErrors(z.null(), null); - z.null().nullable().parse(null); - checkErrors(z.null(), {}); - z.null().nullable().parse(null); - checkErrors(z.object({}), 1); - z.object({}).nullable().parse(null); - checkErrors(z.tuple([]), 1); - z.tuple([]).nullable().parse(null); - checkErrors(z.unknown(), 1); - z.unknown().nullable().parse(null); -}); - -test("unwrap", () => { - const unwrapped = z.string().nullable().unwrap(); - expect(unwrapped).toBeInstanceOf(z.ZodString); -}); diff --git a/deno/lib/__tests__/number.test.ts b/deno/lib/__tests__/number.test.ts deleted file mode 100644 index 31771dcc8..000000000 --- a/deno/lib/__tests__/number.test.ts +++ /dev/null @@ -1,177 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -const gtFive = z.number().gt(5); -const gteFive = z.number().gte(5); -const minFive = z.number().min(5); -const ltFive = z.number().lt(5); -const lteFive = z.number().lte(5); -const maxFive = z.number().max(5); -const intNum = z.number().int(); -const positive = z.number().positive(); -const negative = z.number().negative(); -const nonpositive = z.number().nonpositive(); -const nonnegative = z.number().nonnegative(); -const multipleOfFive = z.number().multipleOf(5); -const multipleOfNegativeFive = z.number().multipleOf(-5); -const finite = z.number().finite(); -const safe = z.number().safe(); -const stepPointOne = z.number().step(0.1); -const stepPointZeroZeroZeroOne = z.number().step(0.0001); -const stepSixPointFour = z.number().step(6.4); - -test("passing validations", () => { - z.number().parse(1); - z.number().parse(1.5); - z.number().parse(0); - z.number().parse(-1.5); - z.number().parse(-1); - z.number().parse(Infinity); - z.number().parse(-Infinity); - gtFive.parse(6); - gtFive.parse(Infinity); - gteFive.parse(5); - gteFive.parse(Infinity); - minFive.parse(5); - minFive.parse(Infinity); - ltFive.parse(4); - ltFive.parse(-Infinity); - lteFive.parse(5); - lteFive.parse(-Infinity); - maxFive.parse(5); - maxFive.parse(-Infinity); - intNum.parse(4); - positive.parse(1); - positive.parse(Infinity); - negative.parse(-1); - negative.parse(-Infinity); - nonpositive.parse(0); - nonpositive.parse(-1); - nonpositive.parse(-Infinity); - nonnegative.parse(0); - nonnegative.parse(1); - nonnegative.parse(Infinity); - multipleOfFive.parse(15); - multipleOfFive.parse(-15); - multipleOfNegativeFive.parse(-15); - multipleOfNegativeFive.parse(15); - finite.parse(123); - safe.parse(Number.MIN_SAFE_INTEGER); - safe.parse(Number.MAX_SAFE_INTEGER); - stepPointOne.parse(6); - stepPointOne.parse(6.1); - stepPointOne.parse(6.1); - stepSixPointFour.parse(12.8); - stepPointZeroZeroZeroOne.parse(3.01); -}); - -test("failing validations", () => { - expect(() => ltFive.parse(5)).toThrow(); - expect(() => lteFive.parse(6)).toThrow(); - expect(() => maxFive.parse(6)).toThrow(); - expect(() => gtFive.parse(5)).toThrow(); - expect(() => gteFive.parse(4)).toThrow(); - expect(() => minFive.parse(4)).toThrow(); - expect(() => intNum.parse(3.14)).toThrow(); - expect(() => positive.parse(0)).toThrow(); - expect(() => positive.parse(-1)).toThrow(); - expect(() => negative.parse(0)).toThrow(); - expect(() => negative.parse(1)).toThrow(); - expect(() => nonpositive.parse(1)).toThrow(); - expect(() => nonnegative.parse(-1)).toThrow(); - expect(() => multipleOfFive.parse(7.5)).toThrow(); - expect(() => multipleOfFive.parse(-7.5)).toThrow(); - expect(() => multipleOfNegativeFive.parse(-7.5)).toThrow(); - expect(() => multipleOfNegativeFive.parse(7.5)).toThrow(); - expect(() => finite.parse(Infinity)).toThrow(); - expect(() => finite.parse(-Infinity)).toThrow(); - expect(() => safe.parse(Number.MIN_SAFE_INTEGER - 1)).toThrow(); - expect(() => safe.parse(Number.MAX_SAFE_INTEGER + 1)).toThrow(); - - expect(() => stepPointOne.parse(6.11)).toThrow(); - expect(() => stepPointOne.parse(6.1000000001)).toThrow(); - expect(() => stepSixPointFour.parse(6.41)).toThrow(); -}); - -test("parse NaN", () => { - expect(() => z.number().parse(NaN)).toThrow(); -}); - -test("min max getters", () => { - expect(z.number().minValue).toBeNull; - expect(ltFive.minValue).toBeNull; - expect(lteFive.minValue).toBeNull; - expect(maxFive.minValue).toBeNull; - expect(negative.minValue).toBeNull; - expect(nonpositive.minValue).toBeNull; - expect(intNum.minValue).toBeNull; - expect(multipleOfFive.minValue).toBeNull; - expect(finite.minValue).toBeNull; - expect(gtFive.minValue).toEqual(5); - expect(gteFive.minValue).toEqual(5); - expect(minFive.minValue).toEqual(5); - expect(minFive.min(10).minValue).toEqual(10); - expect(positive.minValue).toEqual(0); - expect(nonnegative.minValue).toEqual(0); - expect(safe.minValue).toEqual(Number.MIN_SAFE_INTEGER); - - expect(z.number().maxValue).toBeNull; - expect(gtFive.maxValue).toBeNull; - expect(gteFive.maxValue).toBeNull; - expect(minFive.maxValue).toBeNull; - expect(positive.maxValue).toBeNull; - expect(nonnegative.maxValue).toBeNull; - expect(intNum.minValue).toBeNull; - expect(multipleOfFive.minValue).toBeNull; - expect(finite.minValue).toBeNull; - expect(ltFive.maxValue).toEqual(5); - expect(lteFive.maxValue).toEqual(5); - expect(maxFive.maxValue).toEqual(5); - expect(maxFive.max(1).maxValue).toEqual(1); - expect(negative.maxValue).toEqual(0); - expect(nonpositive.maxValue).toEqual(0); - expect(safe.maxValue).toEqual(Number.MAX_SAFE_INTEGER); -}); - -test("int getter", () => { - expect(z.number().isInt).toEqual(false); - expect(z.number().multipleOf(1.5).isInt).toEqual(false); - expect(gtFive.isInt).toEqual(false); - expect(gteFive.isInt).toEqual(false); - expect(minFive.isInt).toEqual(false); - expect(positive.isInt).toEqual(false); - expect(nonnegative.isInt).toEqual(false); - expect(finite.isInt).toEqual(false); - expect(ltFive.isInt).toEqual(false); - expect(lteFive.isInt).toEqual(false); - expect(maxFive.isInt).toEqual(false); - expect(negative.isInt).toEqual(false); - expect(nonpositive.isInt).toEqual(false); - expect(safe.isInt).toEqual(false); - - expect(intNum.isInt).toEqual(true); - expect(multipleOfFive.isInt).toEqual(true); -}); - -test("finite getter", () => { - expect(z.number().isFinite).toEqual(false); - expect(gtFive.isFinite).toEqual(false); - expect(gteFive.isFinite).toEqual(false); - expect(minFive.isFinite).toEqual(false); - expect(positive.isFinite).toEqual(false); - expect(nonnegative.isFinite).toEqual(false); - expect(ltFive.isFinite).toEqual(false); - expect(lteFive.isFinite).toEqual(false); - expect(maxFive.isFinite).toEqual(false); - expect(negative.isFinite).toEqual(false); - expect(nonpositive.isFinite).toEqual(false); - - expect(finite.isFinite).toEqual(true); - expect(intNum.isFinite).toEqual(true); - expect(multipleOfFive.isFinite).toEqual(true); - expect(z.number().min(5).max(10).isFinite).toEqual(true); - expect(safe.isFinite).toEqual(true); -}); diff --git a/deno/lib/__tests__/object-augmentation.test.ts b/deno/lib/__tests__/object-augmentation.test.ts deleted file mode 100644 index f3822fb05..000000000 --- a/deno/lib/__tests__/object-augmentation.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("object augmentation", () => { - const Animal = z - .object({ - species: z.string(), - }) - .augment({ - population: z.number(), - }); - // overwrites `species` - const ModifiedAnimal = Animal.augment({ - species: z.array(z.string()), - }); - ModifiedAnimal.parse({ - species: ["asd"], - population: 1324, - }); - - const bad = () => - ModifiedAnimal.parse({ - species: "asdf", - population: 1324, - } as any); - expect(bad).toThrow(); -}); diff --git a/deno/lib/__tests__/object.test.ts b/deno/lib/__tests__/object.test.ts deleted file mode 100644 index ff636a078..000000000 --- a/deno/lib/__tests__/object.test.ts +++ /dev/null @@ -1,473 +0,0 @@ -// @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"; - -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()]) })), -}); -type Test = z.infer<typeof Test>; - -test("object type inference", () => { - type TestType = { - f1: number; - f2?: string | undefined; - f3: string | null; - f4: { t: string | boolean }[]; - }; - - util.assertEqual<z.TypeOf<typeof Test>, TestType>(true); -}); - -test("unknown throw", () => { - const asdf: unknown = 35; - expect(() => Test.parse(asdf)).toThrow(); -}); - -test("shape() should return schema of particular key", () => { - const f1Schema = Test.shape.f1; - const f2Schema = Test.shape.f2; - const f3Schema = Test.shape.f3; - const f4Schema = Test.shape.f4; - - expect(f1Schema).toBeInstanceOf(z.ZodNumber); - expect(f2Schema).toBeInstanceOf(z.ZodOptional); - expect(f3Schema).toBeInstanceOf(z.ZodNullable); - expect(f4Schema).toBeInstanceOf(z.ZodArray); -}); - -test("correct parsing", () => { - Test.parse({ - f1: 12, - f2: "string", - f3: "string", - f4: [ - { - t: "string", - }, - ], - }); - - Test.parse({ - f1: 12, - f3: null, - f4: [ - { - t: false, - }, - ], - }); -}); - -test("incorrect #1", () => { - expect(() => Test.parse({} as any)).toThrow(); -}); - -test("nonstrict by default", () => { - z.object({ points: z.number() }).parse({ - points: 2314, - unknown: "asdf", - }); -}); - -const data = { - points: 2314, - unknown: "asdf", -}; - -test("strip by default", () => { - const val = z.object({ points: z.number() }).parse(data); - expect(val).toEqual({ points: 2314 }); -}); - -test("unknownkeys override", () => { - const val = z - .object({ points: z.number() }) - .strict() - .passthrough() - .strip() - .nonstrict() - .parse(data); - - expect(val).toEqual(data); -}); - -test("passthrough unknown", () => { - const val = z.object({ points: z.number() }).passthrough().parse(data); - - expect(val).toEqual(data); -}); - -test("strip unknown", () => { - const val = z.object({ points: z.number() }).strip().parse(data); - - expect(val).toEqual({ points: 2314 }); -}); - -test("strict", () => { - const val = z.object({ points: z.number() }).strict().safeParse(data); - - expect(val.success).toEqual(false); -}); - -test("catchall inference", () => { - const o1 = z - .object({ - first: z.string(), - }) - .catchall(z.number()); - - const d1 = o1.parse({ first: "asdf", num: 1243 }); - util.assertEqual<number, (typeof d1)["asdf"]>(true); - util.assertEqual<string, (typeof d1)["first"]>(true); -}); - -test("catchall overrides strict", () => { - const o1 = z - .object({ first: z.string().optional() }) - .strict() - .catchall(z.number()); - - // should run fine - // setting a catchall overrides the unknownKeys behavior - o1.parse({ - asdf: 1234, - }); - - // should only run catchall validation - // against unknown keys - o1.parse({ - first: "asdf", - asdf: 1234, - }); -}); - -test("catchall overrides strict", () => { - const o1 = z - .object({ - first: z.string(), - }) - .strict() - .catchall(z.number()); - - // should run fine - // setting a catchall overrides the unknownKeys behavior - o1.parse({ - first: "asdf", - asdf: 1234, - }); -}); - -test("test that optional keys are unset", async () => { - const SNamedEntity = z.object({ - id: z.string(), - set: z.string().optional(), - unset: z.string().optional(), - }); - const result = await SNamedEntity.parse({ - id: "asdf", - set: undefined, - }); - // eslint-disable-next-line ban/ban - expect(Object.keys(result)).toEqual(["id", "set"]); -}); - -test("test catchall parsing", async () => { - const result = z - .object({ name: z.string() }) - .catchall(z.number()) - .parse({ name: "Foo", validExtraKey: 61 }); - - expect(result).toEqual({ name: "Foo", validExtraKey: 61 }); - - const result2 = z - .object({ name: z.string() }) - .catchall(z.number()) - .safeParse({ name: "Foo", validExtraKey: 61, invalid: "asdf" }); - - expect(result2.success).toEqual(false); -}); - -test("test nonexistent keys", async () => { - const Schema = z.union([ - z.object({ a: z.string() }), - z.object({ b: z.number() }), - ]); - const obj = { a: "A" }; - const result = await Schema.spa(obj); // Works with 1.11.10, breaks with 2.0.0-beta.21 - expect(result.success).toBe(true); -}); - -test("test async union", async () => { - const Schema2 = z.union([ - z.object({ - ty: z.string(), - }), - z.object({ - ty: z.number(), - }), - ]); - - const obj = { ty: "A" }; - const result = await Schema2.spa(obj); // Works with 1.11.10, breaks with 2.0.0-beta.21 - expect(result.success).toEqual(true); -}); - -test("test inferred merged type", async () => { - const asdf = z.object({ a: z.string() }).merge(z.object({ a: z.number() })); - type asdf = z.infer<typeof asdf>; - util.assertEqual<asdf, { a: number }>(true); -}); - -test("inferred merged object type with optional properties", async () => { - const Merged = z - .object({ a: z.string(), b: z.string().optional() }) - .merge(z.object({ a: z.string().optional(), b: z.string() })); - type Merged = z.infer<typeof Merged>; - util.assertEqual<Merged, { a?: string; b: string }>(true); - // todo - // util.assertEqual<Merged, { a?: string; b: string }>(true); -}); - -test("inferred unioned object type with optional properties", async () => { - const Unioned = z.union([ - z.object({ a: z.string(), b: z.string().optional() }), - z.object({ a: z.string().optional(), b: z.string() }), - ]); - type Unioned = z.infer<typeof Unioned>; - util.assertEqual< - Unioned, - { a: string; b?: string } | { a?: string; b: string } - >(true); -}); - -test("inferred enum type", async () => { - const Enum = z.object({ a: z.string(), b: z.string().optional() }).keyof(); - - expect(Enum.Values).toEqual({ - a: "a", - b: "b", - }); - expect(Enum.enum).toEqual({ - a: "a", - b: "b", - }); - expect(Enum._def.values).toEqual(["a", "b"]); - type Enum = z.infer<typeof Enum>; - util.assertEqual<Enum, "a" | "b">(true); -}); - -test("inferred partial object type with optional properties", async () => { - const Partial = z - .object({ a: z.string(), b: z.string().optional() }) - .partial(); - type Partial = z.infer<typeof Partial>; - util.assertEqual<Partial, { a?: string; b?: string }>(true); -}); - -test("inferred picked object type with optional properties", async () => { - const Picked = z - .object({ a: z.string(), b: z.string().optional() }) - .pick({ b: true }); - type Picked = z.infer<typeof Picked>; - util.assertEqual<Picked, { b?: string }>(true); -}); - -test("inferred type for unknown/any keys", () => { - const myType = z.object({ - anyOptional: z.any().optional(), - anyRequired: z.any(), - unknownOptional: z.unknown().optional(), - unknownRequired: z.unknown(), - }); - type myType = z.infer<typeof myType>; - util.assertEqual< - myType, - { - anyOptional?: any; - anyRequired?: any; - unknownOptional?: unknown; - unknownRequired?: unknown; - } - >(true); -}); - -test("setKey", () => { - const base = z.object({ name: z.string() }); - const withNewKey = base.setKey("age", z.number()); - - type withNewKey = z.infer<typeof withNewKey>; - util.assertEqual<withNewKey, { name: string; age: number }>(true); - withNewKey.parse({ name: "asdf", age: 1234 }); -}); - -test("strictcreate", async () => { - const strictObj = z.strictObject({ - name: z.string(), - }); - - const syncResult = strictObj.safeParse({ name: "asdf", unexpected: 13 }); - expect(syncResult.success).toEqual(false); - - const asyncResult = await strictObj.spa({ name: "asdf", unexpected: 13 }); - expect(asyncResult.success).toEqual(false); -}); - -test("object with refine", async () => { - const schema = z - .object({ - a: z.string().default("foo"), - b: z.number(), - }) - .refine(() => true); - expect(schema.parse({ b: 5 })).toEqual({ b: 5, a: "foo" }); - const result = await schema.parseAsync({ b: 5 }); - expect(result).toEqual({ b: 5, a: "foo" }); -}); - -test("intersection of object with date", async () => { - const schema = z.object({ - a: z.date(), - }); - expect(schema.and(schema).parse({ a: new Date(1637353595983) })).toEqual({ - a: new Date(1637353595983), - }); - const result = await schema.parseAsync({ a: new Date(1637353595983) }); - expect(result).toEqual({ a: new Date(1637353595983) }); -}); - -test("intersection of object with refine with date", async () => { - const schema = z - .object({ - a: z.date(), - }) - .refine(() => true); - expect(schema.and(schema).parse({ a: new Date(1637353595983) })).toEqual({ - a: new Date(1637353595983), - }); - const result = await schema.parseAsync({ a: new Date(1637353595983) }); - expect(result).toEqual({ a: new Date(1637353595983) }); -}); - -test("constructor key", () => { - const person = z - .object({ - name: z.string(), - }) - .strict(); - - expect(() => - person.parse({ - name: "bob dylan", - constructor: 61, - }) - ).toThrow(); -}); - -test("constructor key", () => { - const Example = z.object({ - prop: z.string(), - opt: z.number().optional(), - arr: z.string().array(), - }); - - type Example = z.infer<typeof Example>; - util.assertEqual<keyof Example, "prop" | "opt" | "arr">(true); -}); - -test("unknownkeys merging", () => { - // This one is "strict" - const schemaA = z - .object({ - a: z.string(), - }) - .strict(); - - // This one is "strip" - const schemaB = z - .object({ - b: z.string(), - }) - .catchall(z.string()); - - const mergedSchema = schemaA.merge(schemaB); - type mergedSchema = typeof mergedSchema; - util.assertEqual<mergedSchema["_def"]["unknownKeys"], "strip">(true); - expect(mergedSchema._def.unknownKeys).toEqual("strip"); - - util.assertEqual<mergedSchema["_def"]["catchall"], z.ZodString>(true); - expect(mergedSchema._def.catchall instanceof z.ZodString).toEqual(true); -}); - -const personToExtend = z.object({ - firstName: z.string(), - lastName: z.string(), -}); - -test("extend() should return schema with new key", () => { - const PersonWithNickname = personToExtend.extend({ nickName: z.string() }); - type PersonWithNickname = z.infer<typeof PersonWithNickname>; - - const expected = { firstName: "f", nickName: "n", lastName: "l" }; - const actual = PersonWithNickname.parse(expected); - - expect(actual).toEqual(expected); - util.assertEqual< - keyof PersonWithNickname, - "firstName" | "lastName" | "nickName" - >(true); - util.assertEqual< - PersonWithNickname, - { firstName: string; lastName: string; nickName: string } - >(true); -}); - -test("extend() should have power to override existing key", () => { - const PersonWithNumberAsLastName = personToExtend.extend({ - lastName: z.number(), - }); - type PersonWithNumberAsLastName = z.infer<typeof PersonWithNumberAsLastName>; - - const expected = { firstName: "f", lastName: 42 }; - const actual = PersonWithNumberAsLastName.parse(expected); - - expect(actual).toEqual(expected); - util.assertEqual< - PersonWithNumberAsLastName, - { firstName: string; lastName: number } - >(true); -}); - -test("passthrough index signature", () => { - const a = z.object({ a: z.string() }); - type a = z.infer<typeof a>; - util.assertEqual<{ a: string }, a>(true); - const b = a.passthrough(); - type b = z.infer<typeof b>; - util.assertEqual<{ a: string } & { [k: string]: unknown }, b>(true); -}); - -test("xor", () => { - type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }; - type XOR<T, U> = T extends object - ? U extends object - ? (Without<T, U> & U) | (Without<U, T> & T) - : U - : T; - - type A = { name: string; a: number }; - type B = { name: string; b: number }; - type C = XOR<A, B>; - type Outer = { data: C }; - const Outer: z.ZodType<Outer> = z.object({ - data: z.union([ - z.object({ name: z.string(), a: z.number() }), - z.object({ name: z.string(), b: z.number() }), - ]), - }); -}); diff --git a/deno/lib/__tests__/optional.test.ts b/deno/lib/__tests__/optional.test.ts deleted file mode 100644 index 15b08a4fa..000000000 --- a/deno/lib/__tests__/optional.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -function checkErrors(a: z.ZodTypeAny, bad: any) { - let expected; - try { - a.parse(bad); - } catch (error) { - expected = (error as z.ZodError).formErrors; - } - try { - a.optional().parse(bad); - } catch (error) { - expect((error as z.ZodError).formErrors).toEqual(expected); - } -} - -test("Should have error messages appropriate for the underlying type", () => { - checkErrors(z.string().min(2), 1); - z.string().min(2).optional().parse(undefined); - checkErrors(z.number().gte(2), 1); - z.number().gte(2).optional().parse(undefined); - checkErrors(z.boolean(), ""); - z.boolean().optional().parse(undefined); - checkErrors(z.undefined(), null); - z.undefined().optional().parse(undefined); - checkErrors(z.null(), {}); - z.null().optional().parse(undefined); - checkErrors(z.object({}), 1); - z.object({}).optional().parse(undefined); - checkErrors(z.tuple([]), 1); - z.tuple([]).optional().parse(undefined); - checkErrors(z.unknown(), 1); - z.unknown().optional().parse(undefined); -}); - -test("unwrap", () => { - const unwrapped = z.string().optional().unwrap(); - expect(unwrapped).toBeInstanceOf(z.ZodString); -}); diff --git a/deno/lib/__tests__/parseUtil.test.ts b/deno/lib/__tests__/parseUtil.test.ts deleted file mode 100644 index 6be849310..000000000 --- a/deno/lib/__tests__/parseUtil.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import { - isAborted, - isDirty, - isValid, - SyncParseReturnType, -} from "../helpers/parseUtil.ts"; - -test("parseUtil isInvalid should use structural typing", () => { - // Test for issue #556: https://github.com/colinhacks/zod/issues/556 - const aborted: SyncParseReturnType = { status: "aborted" }; - const dirty: SyncParseReturnType = { status: "dirty", value: "whatever" }; - const valid: SyncParseReturnType = { status: "valid", value: "whatever" }; - - expect(isAborted(aborted)).toBe(true); - expect(isAborted(dirty)).toBe(false); - expect(isAborted(valid)).toBe(false); - - expect(isDirty(aborted)).toBe(false); - expect(isDirty(dirty)).toBe(true); - expect(isDirty(valid)).toBe(false); - - expect(isValid(aborted)).toBe(false); - expect(isValid(dirty)).toBe(false); - expect(isValid(valid)).toBe(true); -}); diff --git a/deno/lib/__tests__/parser.test.ts b/deno/lib/__tests__/parser.test.ts deleted file mode 100644 index 6d2e0de42..000000000 --- a/deno/lib/__tests__/parser.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("parse strict object with unknown keys", () => { - expect(() => - z - .object({ name: z.string() }) - .strict() - .parse({ name: "bill", unknownKey: 12 } as any) - ).toThrow(); -}); - -test("parse nonstrict object with unknown keys", () => { - z.object({ name: z.string() }) - .nonstrict() - .parse({ name: "bill", unknownKey: 12 }); -}); - -test("invalid left side of intersection", () => { - expect(() => - z.intersection(z.string(), z.number()).parse(12 as any) - ).toThrow(); -}); - -test("invalid right side of intersection", () => { - expect(() => - z.intersection(z.string(), z.number()).parse("12" as any) - ).toThrow(); -}); - -test("parsing non-array in tuple schema", () => { - expect(() => z.tuple([]).parse("12" as any)).toThrow(); -}); - -test("incorrect num elements in tuple", () => { - expect(() => z.tuple([]).parse(["asdf"] as any)).toThrow(); -}); - -test("invalid enum value", () => { - expect(() => z.enum(["Blue"]).parse("Red" as any)).toThrow(); -}); - -test("parsing unknown", () => { - z.string().parse("Red" as unknown); -}); diff --git a/deno/lib/__tests__/partials.test.ts b/deno/lib/__tests__/partials.test.ts deleted file mode 100644 index 1825753a9..000000000 --- a/deno/lib/__tests__/partials.test.ts +++ /dev/null @@ -1,253 +0,0 @@ -// @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 { ZodNullable, ZodOptional } from "../index.ts"; - -const nested = z.object({ - name: z.string(), - age: z.number(), - outer: z.object({ - inner: z.string(), - }), - array: z.array(z.object({ asdf: z.string() })), -}); - -test("shallow inference", () => { - const shallow = nested.partial(); - type shallow = z.infer<typeof shallow>; - type correct = { - name?: string | undefined; - age?: number | undefined; - outer?: { inner: string } | undefined; - array?: { asdf: string }[]; - }; - util.assertEqual<shallow, correct>(true); -}); - -test("shallow partial parse", () => { - const shallow = nested.partial(); - shallow.parse({}); - shallow.parse({ - name: "asdf", - age: 23143, - }); -}); - -test("deep partial inference", () => { - const deep = nested.deepPartial(); - const asdf = deep.shape.array.unwrap().element.shape.asdf.unwrap(); - asdf.parse("asdf"); - type deep = z.infer<typeof deep>; - type correct = { - array?: { asdf?: string }[]; - name?: string | undefined; - age?: number | undefined; - outer?: { inner?: string | undefined } | undefined; - }; - - util.assertEqual<deep, correct>(true); -}); - -test("deep partial parse", () => { - const deep = nested.deepPartial(); - - expect(deep.shape.name instanceof z.ZodOptional).toBe(true); - expect(deep.shape.outer instanceof z.ZodOptional).toBe(true); - expect(deep.shape.outer._def.innerType instanceof z.ZodObject).toBe(true); - expect( - deep.shape.outer._def.innerType.shape.inner instanceof z.ZodOptional - ).toBe(true); - expect( - deep.shape.outer._def.innerType.shape.inner._def.innerType instanceof - z.ZodString - ).toBe(true); -}); - -test("deep partial runtime tests", () => { - const deep = nested.deepPartial(); - deep.parse({}); - deep.parse({ - outer: {}, - }); - deep.parse({ - name: "asdf", - age: 23143, - outer: { - inner: "adsf", - }, - }); -}); - -test("deep partial optional/nullable", () => { - const schema = z - .object({ - name: z.string().optional(), - age: z.number().nullable(), - }) - .deepPartial(); - - expect(schema.shape.name.unwrap()).toBeInstanceOf(ZodOptional); - expect(schema.shape.age.unwrap()).toBeInstanceOf(ZodNullable); -}); - -test("deep partial tuple", () => { - const schema = z - .object({ - tuple: z.tuple([ - z.object({ - name: z.string().optional(), - age: z.number().nullable(), - }), - ]), - }) - .deepPartial(); - - expect(schema.shape.tuple.unwrap().items[0].shape.name).toBeInstanceOf( - ZodOptional - ); -}); - -test("deep partial inference", () => { - const mySchema = z.object({ - name: z.string(), - array: z.array(z.object({ asdf: z.string() })), - tuple: z.tuple([z.object({ value: z.string() })]), - }); - - const partialed = mySchema.deepPartial(); - type partialed = z.infer<typeof partialed>; - type expected = { - name?: string | undefined; - array?: - | { - asdf?: string | undefined; - }[] - | undefined; - tuple?: [{ value?: string }] | undefined; - }; - util.assertEqual<expected, partialed>(true); -}); - -test("required", () => { - const object = z.object({ - name: z.string(), - age: z.number().optional(), - field: z.string().optional().default("asdf"), - nullableField: z.number().nullable(), - nullishField: z.string().nullish(), - }); - - const requiredObject = object.required(); - expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); - expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber); - expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); - expect(requiredObject.shape.nullableField).toBeInstanceOf(z.ZodNullable); - expect(requiredObject.shape.nullishField).toBeInstanceOf(z.ZodNullable); -}); - -test("required inference", () => { - const object = z.object({ - name: z.string(), - age: z.number().optional(), - field: z.string().optional().default("asdf"), - nullableField: z.number().nullable(), - nullishField: z.string().nullish(), - }); - - const requiredObject = object.required(); - - type required = z.infer<typeof requiredObject>; - type expected = { - name: string; - age: number; - field: string; - nullableField: number | null; - nullishField: string | null; - }; - util.assertEqual<expected, required>(true); -}); - -test("required with mask", () => { - const object = z.object({ - name: z.string(), - age: z.number().optional(), - field: z.string().optional().default("asdf"), - country: z.string().optional(), - }); - - const requiredObject = object.required({ age: true }); - expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); - expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber); - expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); - expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional); -}); - -test("required with mask -- ignore falsy values", () => { - const object = z.object({ - name: z.string(), - age: z.number().optional(), - field: z.string().optional().default("asdf"), - country: z.string().optional(), - }); - - // @ts-expect-error - const requiredObject = object.required({ age: true, country: false }); - expect(requiredObject.shape.name).toBeInstanceOf(z.ZodString); - expect(requiredObject.shape.age).toBeInstanceOf(z.ZodNumber); - expect(requiredObject.shape.field).toBeInstanceOf(z.ZodDefault); - expect(requiredObject.shape.country).toBeInstanceOf(z.ZodOptional); -}); - -test("partial with mask", async () => { - const object = z.object({ - name: z.string(), - age: z.number().optional(), - field: z.string().optional().default("asdf"), - country: z.string(), - }); - - const masked = object - .partial({ age: true, field: true, name: true }) - .strict(); - - expect(masked.shape.name).toBeInstanceOf(z.ZodOptional); - expect(masked.shape.age).toBeInstanceOf(z.ZodOptional); - expect(masked.shape.field).toBeInstanceOf(z.ZodOptional); - expect(masked.shape.country).toBeInstanceOf(z.ZodString); - - masked.parse({ country: "US" }); - await masked.parseAsync({ country: "US" }); -}); - -test("partial with mask -- ignore falsy values", async () => { - const object = z.object({ - name: z.string(), - age: z.number().optional(), - field: z.string().optional().default("asdf"), - country: z.string(), - }); - - // @ts-expect-error - const masked = object.partial({ name: true, country: false }).strict(); - - expect(masked.shape.name).toBeInstanceOf(z.ZodOptional); - expect(masked.shape.age).toBeInstanceOf(z.ZodOptional); - expect(masked.shape.field).toBeInstanceOf(z.ZodDefault); - expect(masked.shape.country).toBeInstanceOf(z.ZodString); - - masked.parse({ country: "US" }); - await masked.parseAsync({ country: "US" }); -}); - -test("deeppartial array", () => { - const schema = z.object({ array: z.string().array().min(42) }).deepPartial(); - - // works as expected - schema.parse({}); - - // should be false, but is true - expect(schema.safeParse({ array: [] }).success).toBe(false); -}); diff --git a/deno/lib/__tests__/pickomit.test.ts b/deno/lib/__tests__/pickomit.test.ts deleted file mode 100644 index f89b01253..000000000 --- a/deno/lib/__tests__/pickomit.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -// @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"; - -const fish = z.object({ - name: z.string(), - age: z.number(), - nested: z.object({}), -}); - -test("pick type inference", () => { - const nameonlyFish = fish.pick({ name: true }); - type nameonlyFish = z.infer<typeof nameonlyFish>; - util.assertEqual<nameonlyFish, { name: string }>(true); -}); - -test("pick parse - success", () => { - const nameonlyFish = fish.pick({ name: true }); - nameonlyFish.parse({ name: "bob" }); - - // @ts-expect-error checking runtime picks `name` only. - const anotherNameonlyFish = fish.pick({ name: true, age: false }); - anotherNameonlyFish.parse({ name: "bob" }); -}); - -test("pick parse - fail", () => { - fish.pick({ name: true }).parse({ name: "12" } as any); - fish.pick({ name: true }).parse({ name: "bob", age: 12 } as any); - fish.pick({ age: true }).parse({ age: 12 } as any); - - const nameonlyFish = fish.pick({ name: true }).strict(); - const bad1 = () => nameonlyFish.parse({ name: 12 } as any); - const bad2 = () => nameonlyFish.parse({ name: "bob", age: 12 } as any); - const bad3 = () => nameonlyFish.parse({ age: 12 } as any); - - // @ts-expect-error checking runtime picks `name` only. - const anotherNameonlyFish = fish.pick({ name: true, age: false }).strict(); - const bad4 = () => anotherNameonlyFish.parse({ name: "bob", age: 12 } as any); - - expect(bad1).toThrow(); - expect(bad2).toThrow(); - expect(bad3).toThrow(); - expect(bad4).toThrow(); -}); - -test("omit type inference", () => { - const nonameFish = fish.omit({ name: true }); - type nonameFish = z.infer<typeof nonameFish>; - util.assertEqual<nonameFish, { age: number; nested: {} }>(true); -}); - -test("omit parse - success", () => { - const nonameFish = fish.omit({ name: true }); - nonameFish.parse({ age: 12, nested: {} }); - - // @ts-expect-error checking runtime omits `name` only. - const anotherNonameFish = fish.omit({ name: true, age: false }); - anotherNonameFish.parse({ age: 12, nested: {} }); -}); - -test("omit parse - fail", () => { - const nonameFish = fish.omit({ name: true }); - const bad1 = () => nonameFish.parse({ name: 12 } as any); - const bad2 = () => nonameFish.parse({ age: 12 } as any); - const bad3 = () => nonameFish.parse({} as any); - - // @ts-expect-error checking runtime omits `name` only. - const anotherNonameFish = fish.omit({ name: true, age: false }); - const bad4 = () => anotherNonameFish.parse({ nested: {} } as any); - - expect(bad1).toThrow(); - expect(bad2).toThrow(); - expect(bad3).toThrow(); - expect(bad4).toThrow(); -}); - -test("nonstrict inference", () => { - const laxfish = fish.pick({ name: true }).catchall(z.any()); - type laxfish = z.infer<typeof laxfish>; - util.assertEqual<laxfish, { name: string } & { [k: string]: any }>(true); -}); - -test("nonstrict parsing - pass", () => { - const laxfish = fish.passthrough().pick({ name: true }); - laxfish.parse({ name: "asdf", whatever: "asdf" }); - laxfish.parse({ name: "asdf", age: 12, nested: {} }); -}); - -test("nonstrict parsing - fail", () => { - const laxfish = fish.passthrough().pick({ name: true }); - const bad = () => laxfish.parse({ whatever: "asdf" } as any); - expect(bad).toThrow(); -}); diff --git a/deno/lib/__tests__/pipeline.test.ts b/deno/lib/__tests__/pipeline.test.ts deleted file mode 100644 index 349505a2c..000000000 --- a/deno/lib/__tests__/pipeline.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("string to number pipeline", () => { - const schema = z.string().transform(Number).pipe(z.number()); - expect(schema.parse("1234")).toEqual(1234); -}); - -test("string to number pipeline async", async () => { - const schema = z - .string() - .transform(async (val) => Number(val)) - .pipe(z.number()); - expect(await schema.parseAsync("1234")).toEqual(1234); -}); - -test("break if dirty", () => { - const schema = z - .string() - .refine((c) => c === "1234") - .transform(async (val) => Number(val)) - .pipe(z.number().refine((v) => v < 100)); - const r1: any = schema.safeParse("12345"); - expect(r1.error.issues.length).toBe(1); - const r2: any = schema.safeParse("3"); - expect(r2.error.issues.length).toBe(1); -}); diff --git a/deno/lib/__tests__/preprocess.test.ts b/deno/lib/__tests__/preprocess.test.ts deleted file mode 100644 index 50ac02e05..000000000 --- a/deno/lib/__tests__/preprocess.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -// @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"; - -test("preprocess", () => { - const schema = z.preprocess((data) => [data], z.string().array()); - - const value = schema.parse("asdf"); - expect(value).toEqual(["asdf"]); - util.assertEqual<(typeof schema)["_input"], unknown>(true); -}); - -test("async preprocess", async () => { - const schema = z.preprocess(async (data) => [data], z.string().array()); - - const value = await schema.parseAsync("asdf"); - expect(value).toEqual(["asdf"]); -}); - -test("preprocess ctx.addIssue with parse", () => { - expect(() => { - z.preprocess((data, ctx) => { - ctx.addIssue({ - code: "custom", - message: `${data} is not one of our allowed strings`, - }); - return data; - }, z.string()).parse("asdf"); - }).toThrow( - JSON.stringify( - [ - { - code: "custom", - message: "asdf is not one of our allowed strings", - path: [], - }, - ], - null, - 2 - ) - ); -}); - -test("preprocess ctx.addIssue non-fatal by default", () => { - try { - z.preprocess((data, ctx) => { - ctx.addIssue({ - code: "custom", - message: `custom error`, - }); - return data; - }, z.string()).parse(1234); - } catch (err) { - z.ZodError.assert(err); - expect(err.issues.length).toEqual(2); - } -}); - -test("preprocess ctx.addIssue fatal true", () => { - try { - z.preprocess((data, ctx) => { - ctx.addIssue({ - code: "custom", - message: `custom error`, - fatal: true, - }); - return data; - }, z.string()).parse(1234); - } catch (err) { - z.ZodError.assert(err); - expect(err.issues.length).toEqual(1); - } -}); - -test("async preprocess ctx.addIssue with parse", async () => { - const schema = z.preprocess(async (data, ctx) => { - ctx.addIssue({ - code: "custom", - message: `custom error`, - }); - return data; - }, z.string()); - - expect(schema.parseAsync("asdf")).rejects.toThrow( - JSON.stringify( - [ - { - code: "custom", - message: "custom error", - path: [], - }, - ], - null, - 2 - ) - ); -}); - -test("preprocess ctx.addIssue with parseAsync", async () => { - const result = await z - .preprocess(async (data, ctx) => { - ctx.addIssue({ - code: "custom", - message: `${data} is not one of our allowed strings`, - }); - return data; - }, z.string()) - .safeParseAsync("asdf"); - - expect(JSON.parse(JSON.stringify(result))).toEqual({ - success: false, - error: { - issues: [ - { - code: "custom", - message: "asdf is not one of our allowed strings", - path: [], - }, - ], - name: "ZodError", - }, - }); -}); - -test("z.NEVER in preprocess", () => { - const foo = z.preprocess((val, ctx) => { - if (!val) { - ctx.addIssue({ code: z.ZodIssueCode.custom, message: "bad" }); - return z.NEVER; - } - return val; - }, z.number()); - - type foo = z.infer<typeof foo>; - util.assertEqual<foo, number>(true); - const arg = foo.safeParse(undefined); - if (!arg.success) { - expect(arg.error.issues[0].message).toEqual("bad"); - } -}); -test("preprocess as the second property of object", () => { - const schema = z.object({ - nonEmptyStr: z.string().min(1), - positiveNum: z.preprocess((v) => Number(v), z.number().positive()), - }); - const result = schema.safeParse({ - nonEmptyStr: "", - positiveNum: "", - }); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues.length).toEqual(2); - expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.too_small); - expect(result.error.issues[1].code).toEqual(z.ZodIssueCode.too_small); - } -}); - -test("preprocess validates with sibling errors", () => { - expect(() => { - z.object({ - // Must be first - missing: z.string().refine(() => false), - preprocess: z.preprocess( - (data: any) => data?.trim(), - z.string().regex(/ asdf/) - ), - }).parse({ preprocess: " asdf" }); - }).toThrow( - JSON.stringify( - [ - { - code: "invalid_type", - expected: "string", - received: "undefined", - path: ["missing"], - message: "Required", - }, - { - validation: "regex", - code: "invalid_string", - message: "Invalid", - path: ["preprocess"], - }, - ], - null, - 2 - ) - ); -}); diff --git a/deno/lib/__tests__/primitive.test.ts b/deno/lib/__tests__/primitive.test.ts deleted file mode 100644 index 5815f765e..000000000 --- a/deno/lib/__tests__/primitive.test.ts +++ /dev/null @@ -1,455 +0,0 @@ -// @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 { Mocker } from "./Mocker.ts"; - -const literalStringSchema = z.literal("asdf"); -const literalNumberSchema = z.literal(12); -const literalBooleanSchema = z.literal(true); -const literalBigIntSchema = z.literal(BigInt(42)); -const MySymbol = Symbol("stuff"); -const literalSymbolSchema = z.literal(MySymbol); -const stringSchema = z.string(); -const numberSchema = z.number(); -const bigintSchema = z.bigint(); -const booleanSchema = z.boolean(); -const dateSchema = z.date(); -const symbolSchema = z.symbol(); - -const nullSchema = z.null(); -const undefinedSchema = z.undefined(); -const stringSchemaOptional = z.string().optional(); -const stringSchemaNullable = z.string().nullable(); -const numberSchemaOptional = z.number().optional(); -const numberSchemaNullable = z.number().nullable(); -const bigintSchemaOptional = z.bigint().optional(); -const bigintSchemaNullable = z.bigint().nullable(); -const booleanSchemaOptional = z.boolean().optional(); -const booleanSchemaNullable = z.boolean().nullable(); -const dateSchemaOptional = z.date().optional(); -const dateSchemaNullable = z.date().nullable(); -const symbolSchemaOptional = z.symbol().optional(); -const symbolSchemaNullable = z.symbol().nullable(); - -const val = new Mocker(); - -test("literal string correct", () => { - expect(literalStringSchema.parse("asdf")).toBe("asdf"); -}); - -test("literal string incorrect", () => { - const f = () => literalStringSchema.parse("not_asdf"); - expect(f).toThrow(); -}); - -test("literal string number", () => { - const f = () => literalStringSchema.parse(123); - expect(f).toThrow(); -}); - -test("literal string boolean", () => { - const f = () => literalStringSchema.parse(true); - expect(f).toThrow(); -}); - -test("literal string boolean", () => { - const f = () => literalStringSchema.parse(true); - expect(f).toThrow(); -}); - -test("literal string object", () => { - const f = () => literalStringSchema.parse({}); - expect(f).toThrow(); -}); - -test("literal number correct", () => { - expect(literalNumberSchema.parse(12)).toBe(12); -}); - -test("literal number incorrect", () => { - const f = () => literalNumberSchema.parse(13); - expect(f).toThrow(); -}); - -test("literal number number", () => { - const f = () => literalNumberSchema.parse(val.string); - expect(f).toThrow(); -}); - -test("literal number boolean", () => { - const f = () => literalNumberSchema.parse(val.boolean); - expect(f).toThrow(); -}); - -test("literal number object", () => { - const f = () => literalStringSchema.parse({}); - expect(f).toThrow(); -}); - -test("literal boolean correct", () => { - expect(literalBooleanSchema.parse(true)).toBe(true); -}); - -test("literal boolean incorrect", () => { - const f = () => literalBooleanSchema.parse(false); - expect(f).toThrow(); -}); - -test("literal boolean number", () => { - const f = () => literalBooleanSchema.parse("asdf"); - expect(f).toThrow(); -}); - -test("literal boolean boolean", () => { - const f = () => literalBooleanSchema.parse(123); - expect(f).toThrow(); -}); - -test("literal boolean object", () => { - const f = () => literalBooleanSchema.parse({}); - expect(f).toThrow(); -}); - -test("literal bigint correct", () => { - expect(literalBigIntSchema.parse(BigInt(42))).toBe(BigInt(42)); -}); - -test("literal bigint incorrect", () => { - const f = () => literalBigIntSchema.parse(BigInt(43)); - expect(f).toThrow(); -}); - -test("literal bigint number", () => { - const f = () => literalBigIntSchema.parse("asdf"); - expect(f).toThrow(); -}); - -test("literal bigint boolean", () => { - const f = () => literalBigIntSchema.parse(123); - expect(f).toThrow(); -}); - -test("literal bigint object", () => { - const f = () => literalBigIntSchema.parse({}); - expect(f).toThrow(); -}); - -test("literal symbol", () => { - util.assertEqual<z.infer<typeof literalSymbolSchema>, typeof MySymbol>(true); - literalSymbolSchema.parse(MySymbol); - expect(() => literalSymbolSchema.parse(Symbol("asdf"))).toThrow(); -}); - -test("parse stringSchema string", () => { - stringSchema.parse(val.string); -}); - -test("parse stringSchema number", () => { - const f = () => stringSchema.parse(val.number); - expect(f).toThrow(); -}); - -test("parse stringSchema boolean", () => { - const f = () => stringSchema.parse(val.boolean); - expect(f).toThrow(); -}); - -test("parse stringSchema undefined", () => { - const f = () => stringSchema.parse(val.undefined); - expect(f).toThrow(); -}); - -test("parse stringSchema null", () => { - const f = () => stringSchema.parse(val.null); - expect(f).toThrow(); -}); - -test("parse numberSchema string", () => { - const f = () => numberSchema.parse(val.string); - expect(f).toThrow(); -}); - -test("parse numberSchema number", () => { - numberSchema.parse(val.number); -}); - -test("parse numberSchema bigint", () => { - const f = () => numberSchema.parse(val.bigint); - expect(f).toThrow(); -}); - -test("parse numberSchema boolean", () => { - const f = () => numberSchema.parse(val.boolean); - expect(f).toThrow(); -}); - -test("parse numberSchema undefined", () => { - const f = () => numberSchema.parse(val.undefined); - expect(f).toThrow(); -}); - -test("parse numberSchema null", () => { - const f = () => numberSchema.parse(val.null); - expect(f).toThrow(); -}); - -test("parse bigintSchema string", () => { - const f = () => bigintSchema.parse(val.string); - expect(f).toThrow(); -}); - -test("parse bigintSchema number", () => { - const f = () => bigintSchema.parse(val.number); - expect(f).toThrow(); -}); - -test("parse bigintSchema bigint", () => { - bigintSchema.parse(val.bigint); -}); - -test("parse bigintSchema boolean", () => { - const f = () => bigintSchema.parse(val.boolean); - expect(f).toThrow(); -}); - -test("parse bigintSchema undefined", () => { - const f = () => bigintSchema.parse(val.undefined); - expect(f).toThrow(); -}); - -test("parse bigintSchema null", () => { - const f = () => bigintSchema.parse(val.null); - expect(f).toThrow(); -}); - -test("parse booleanSchema string", () => { - const f = () => booleanSchema.parse(val.string); - expect(f).toThrow(); -}); - -test("parse booleanSchema number", () => { - const f = () => booleanSchema.parse(val.number); - expect(f).toThrow(); -}); - -test("parse booleanSchema boolean", () => { - booleanSchema.parse(val.boolean); -}); - -test("parse booleanSchema undefined", () => { - const f = () => booleanSchema.parse(val.undefined); - expect(f).toThrow(); -}); - -test("parse booleanSchema null", () => { - const f = () => booleanSchema.parse(val.null); - expect(f).toThrow(); -}); - -// ============== - -test("parse dateSchema string", () => { - const f = () => dateSchema.parse(val.string); - expect(f).toThrow(); -}); - -test("parse dateSchema number", () => { - const f = () => dateSchema.parse(val.number); - expect(f).toThrow(); -}); - -test("parse dateSchema boolean", () => { - const f = () => dateSchema.parse(val.boolean); - expect(f).toThrow(); -}); - -test("parse dateSchema date", () => { - dateSchema.parse(val.date); -}); - -test("parse dateSchema undefined", () => { - const f = () => dateSchema.parse(val.undefined); - expect(f).toThrow(); -}); - -test("parse dateSchema null", () => { - const f = () => dateSchema.parse(val.null); - expect(f).toThrow(); -}); - -test("parse dateSchema invalid date", async () => { - try { - await dateSchema.parseAsync(new Date("invalid")); - } catch (err) { - expect((err as z.ZodError).issues[0].code).toEqual( - z.ZodIssueCode.invalid_date - ); - } -}); -// ============== - -test("parse symbolSchema string", () => { - const f = () => symbolSchema.parse(val.string); - expect(f).toThrow(); -}); - -test("parse symbolSchema number", () => { - const f = () => symbolSchema.parse(val.number); - expect(f).toThrow(); -}); - -test("parse symbolSchema boolean", () => { - const f = () => symbolSchema.parse(val.boolean); - expect(f).toThrow(); -}); - -test("parse symbolSchema date", () => { - const f = () => symbolSchema.parse(val.date); - expect(f).toThrow(); -}); - -test("parse symbolSchema symbol", () => { - symbolSchema.parse(val.symbol); -}); - -test("parse symbolSchema undefined", () => { - const f = () => symbolSchema.parse(val.undefined); - expect(f).toThrow(); -}); - -test("parse symbolSchema null", () => { - const f = () => symbolSchema.parse(val.null); - expect(f).toThrow(); -}); - -// ============== - -test("parse undefinedSchema string", () => { - const f = () => undefinedSchema.parse(val.string); - expect(f).toThrow(); -}); - -test("parse undefinedSchema number", () => { - const f = () => undefinedSchema.parse(val.number); - expect(f).toThrow(); -}); - -test("parse undefinedSchema boolean", () => { - const f = () => undefinedSchema.parse(val.boolean); - expect(f).toThrow(); -}); - -test("parse undefinedSchema undefined", () => { - undefinedSchema.parse(val.undefined); -}); - -test("parse undefinedSchema null", () => { - const f = () => undefinedSchema.parse(val.null); - expect(f).toThrow(); -}); - -test("parse nullSchema string", () => { - const f = () => nullSchema.parse(val.string); - expect(f).toThrow(); -}); - -test("parse nullSchema number", () => { - const f = () => nullSchema.parse(val.number); - expect(f).toThrow(); -}); - -test("parse nullSchema boolean", () => { - const f = () => nullSchema.parse(val.boolean); - expect(f).toThrow(); -}); - -test("parse nullSchema undefined", () => { - const f = () => nullSchema.parse(val.undefined); - expect(f).toThrow(); -}); - -test("parse nullSchema null", () => { - nullSchema.parse(val.null); -}); - -test("primitive inference", () => { - util.assertEqual<z.TypeOf<typeof literalStringSchema>, "asdf">(true); - util.assertEqual<z.TypeOf<typeof literalNumberSchema>, 12>(true); - util.assertEqual<z.TypeOf<typeof literalBooleanSchema>, true>(true); - util.assertEqual<z.TypeOf<typeof literalBigIntSchema>, bigint>(true); - util.assertEqual<z.TypeOf<typeof stringSchema>, string>(true); - util.assertEqual<z.TypeOf<typeof numberSchema>, number>(true); - util.assertEqual<z.TypeOf<typeof bigintSchema>, bigint>(true); - util.assertEqual<z.TypeOf<typeof booleanSchema>, boolean>(true); - util.assertEqual<z.TypeOf<typeof dateSchema>, Date>(true); - util.assertEqual<z.TypeOf<typeof symbolSchema>, symbol>(true); - - util.assertEqual<z.TypeOf<typeof nullSchema>, null>(true); - util.assertEqual<z.TypeOf<typeof undefinedSchema>, undefined>(true); - util.assertEqual<z.TypeOf<typeof stringSchemaOptional>, string | undefined>( - true - ); - util.assertEqual<z.TypeOf<typeof stringSchemaNullable>, string | null>(true); - util.assertEqual<z.TypeOf<typeof numberSchemaOptional>, number | undefined>( - true - ); - util.assertEqual<z.TypeOf<typeof numberSchemaNullable>, number | null>(true); - util.assertEqual<z.TypeOf<typeof bigintSchemaOptional>, bigint | undefined>( - true - ); - util.assertEqual<z.TypeOf<typeof bigintSchemaNullable>, bigint | null>(true); - util.assertEqual<z.TypeOf<typeof booleanSchemaOptional>, boolean | undefined>( - true - ); - util.assertEqual<z.TypeOf<typeof booleanSchemaNullable>, boolean | null>( - true - ); - util.assertEqual<z.TypeOf<typeof dateSchemaOptional>, Date | undefined>(true); - util.assertEqual<z.TypeOf<typeof dateSchemaNullable>, Date | null>(true); - util.assertEqual<z.TypeOf<typeof symbolSchemaOptional>, symbol | undefined>( - true - ); - util.assertEqual<z.TypeOf<typeof symbolSchemaNullable>, symbol | null>(true); - - // [ - // literalStringSchemaTest, - // literalNumberSchemaTest, - // literalBooleanSchemaTest, - // literalBigIntSchemaTest, - // stringSchemaTest, - // numberSchemaTest, - // bigintSchemaTest, - // booleanSchemaTest, - // dateSchemaTest, - // symbolSchemaTest, - - // nullSchemaTest, - // undefinedSchemaTest, - // stringSchemaOptionalTest, - // stringSchemaNullableTest, - // numberSchemaOptionalTest, - // numberSchemaNullableTest, - // bigintSchemaOptionalTest, - // bigintSchemaNullableTest, - // booleanSchemaOptionalTest, - // booleanSchemaNullableTest, - // dateSchemaOptionalTest, - // dateSchemaNullableTest, - // symbolSchemaOptionalTest, - // symbolSchemaNullableTest, - - // ]; -}); - -test("get literal value", () => { - expect(literalStringSchema.value).toEqual("asdf"); -}); - -test("optional convenience method", () => { - z.ostring().parse(undefined); - z.onumber().parse(undefined); - z.oboolean().parse(undefined); -}); diff --git a/deno/lib/__tests__/promise.test.ts b/deno/lib/__tests__/promise.test.ts deleted file mode 100644 index 383de22f1..000000000 --- a/deno/lib/__tests__/promise.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -// @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"; - -const promSchema = z.promise( - z.object({ - name: z.string(), - age: z.number(), - }) -); - -test("promise inference", () => { - type promSchemaType = z.infer<typeof promSchema>; - util.assertEqual<promSchemaType, Promise<{ name: string; age: number }>>( - true - ); -}); - -test("promise parsing success", async () => { - const pr = promSchema.parse(Promise.resolve({ name: "Bobby", age: 10 })); - expect(pr).toBeInstanceOf(Promise); - const result = await pr; - expect(typeof result).toBe("object"); - expect(typeof result.age).toBe("number"); - expect(typeof result.name).toBe("string"); -}); - -test("promise parsing success 2", () => { - const fakePromise = { - then() { - return this; - }, - catch() { - return this; - }, - }; - promSchema.parse(fakePromise); -}); - -test("promise parsing fail", async () => { - const bad = promSchema.parse(Promise.resolve({ name: "Bobby", age: "10" })); - // return await expect(bad).resolves.toBe({ name: 'Bobby', age: '10' }); - return await expect(bad).rejects.toBeInstanceOf(z.ZodError); - // done(); -}); - -test("promise parsing fail 2", async () => { - const failPromise = promSchema.parse( - Promise.resolve({ name: "Bobby", age: "10" }) - ); - await expect(failPromise).rejects.toBeInstanceOf(z.ZodError); - // done();/z -}); - -test("promise parsing fail", () => { - const bad = () => promSchema.parse({ then: () => {}, catch: {} }); - expect(bad).toThrow(); -}); - -// test('sync promise parsing', () => { -// expect(() => z.promise(z.string()).parse(Promise.resolve('asfd'))).toThrow(); -// }); - -const asyncFunction = z.function(z.tuple([]), promSchema); - -test("async function pass", async () => { - const validatedFunction = asyncFunction.implement(async () => { - return { name: "jimmy", age: 14 }; - }); - await expect(validatedFunction()).resolves.toEqual({ - name: "jimmy", - age: 14, - }); -}); - -test("async function fail", async () => { - const validatedFunction = asyncFunction.implement(() => { - return Promise.resolve("asdf" as any); - }); - await expect(validatedFunction()).rejects.toBeInstanceOf(z.ZodError); -}); - -test("async promise parsing", () => { - const res = z.promise(z.number()).parseAsync(Promise.resolve(12)); - expect(res).toBeInstanceOf(Promise); -}); - -test("resolves", () => { - const foo = z.literal("foo"); - const res = z.promise(foo); - expect(res.unwrap()).toEqual(foo); -}); diff --git a/deno/lib/__tests__/readonly.test.ts b/deno/lib/__tests__/readonly.test.ts deleted file mode 100644 index 27d2e0c9c..000000000 --- a/deno/lib/__tests__/readonly.test.ts +++ /dev/null @@ -1,205 +0,0 @@ -// @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"; - -enum testEnum { - A, - B, -} - -const schemas = [ - z.string().readonly(), - z.number().readonly(), - z.nan().readonly(), - z.bigint().readonly(), - z.boolean().readonly(), - z.date().readonly(), - z.undefined().readonly(), - z.null().readonly(), - z.any().readonly(), - z.unknown().readonly(), - z.void().readonly(), - z.function().args(z.string(), z.number()).readonly(), - - z.array(z.string()).readonly(), - z.tuple([z.string(), z.number()]).readonly(), - z.map(z.string(), z.date()).readonly(), - z.set(z.promise(z.string())).readonly(), - z.record(z.string()).readonly(), - z.record(z.string(), z.number()).readonly(), - z.object({ a: z.string(), 1: z.number() }).readonly(), - z.nativeEnum(testEnum).readonly(), - z.promise(z.string()).readonly(), -] as const; - -test("flat inference", () => { - util.assertEqual<z.infer<(typeof schemas)[0]>, string>(true); - util.assertEqual<z.infer<(typeof schemas)[1]>, number>(true); - util.assertEqual<z.infer<(typeof schemas)[2]>, number>(true); - util.assertEqual<z.infer<(typeof schemas)[3]>, bigint>(true); - util.assertEqual<z.infer<(typeof schemas)[4]>, boolean>(true); - util.assertEqual<z.infer<(typeof schemas)[5]>, Date>(true); - util.assertEqual<z.infer<(typeof schemas)[6]>, undefined>(true); - util.assertEqual<z.infer<(typeof schemas)[7]>, null>(true); - util.assertEqual<z.infer<(typeof schemas)[8]>, any>(true); - util.assertEqual<z.infer<(typeof schemas)[9]>, Readonly<unknown>>(true); - util.assertEqual<z.infer<(typeof schemas)[10]>, void>(true); - util.assertEqual< - z.infer<(typeof schemas)[11]>, - (args_0: string, args_1: number, ...args_2: unknown[]) => unknown - >(true); - util.assertEqual<z.infer<(typeof schemas)[12]>, readonly string[]>(true); - - util.assertEqual<z.infer<(typeof schemas)[13]>, readonly [string, number]>( - true - ); - util.assertEqual<z.infer<(typeof schemas)[14]>, ReadonlyMap<string, Date>>( - true - ); - util.assertEqual<z.infer<(typeof schemas)[15]>, ReadonlySet<Promise<string>>>( - true - ); - util.assertEqual< - z.infer<(typeof schemas)[16]>, - Readonly<Record<string, string>> - >(true); - util.assertEqual< - z.infer<(typeof schemas)[17]>, - Readonly<Record<string, number>> - >(true); - util.assertEqual< - z.infer<(typeof schemas)[18]>, - { readonly a: string; readonly 1: number } - >(true); - util.assertEqual<z.infer<(typeof schemas)[19]>, Readonly<testEnum>>(true); - util.assertEqual<z.infer<(typeof schemas)[20]>, Promise<string>>(true); -}); - -// test("deep inference", () => { -// util.assertEqual<z.infer<(typeof deepReadonlySchemas_0)[0]>, string>(true); -// util.assertEqual<z.infer<(typeof deepReadonlySchemas_0)[1]>, number>(true); -// util.assertEqual<z.infer<(typeof deepReadonlySchemas_0)[2]>, number>(true); -// util.assertEqual<z.infer<(typeof deepReadonlySchemas_0)[3]>, bigint>(true); -// util.assertEqual<z.infer<(typeof deepReadonlySchemas_0)[4]>, boolean>(true); -// util.assertEqual<z.infer<(typeof deepReadonlySchemas_0)[5]>, Date>(true); -// util.assertEqual<z.infer<(typeof deepReadonlySchemas_0)[6]>, undefined>(true); -// util.assertEqual<z.infer<(typeof deepReadonlySchemas_0)[7]>, null>(true); -// util.assertEqual<z.infer<(typeof deepReadonlySchemas_0)[8]>, any>(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[9]>, -// Readonly<unknown> -// >(true); -// util.assertEqual<z.infer<(typeof deepReadonlySchemas_0)[10]>, void>(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[11]>, -// (args_0: string, args_1: number, ...args_2: unknown[]) => unknown -// >(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[12]>, -// readonly string[] -// >(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[13]>, -// readonly [string, number] -// >(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[14]>, -// ReadonlyMap<string, Date> -// >(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[15]>, -// ReadonlySet<Promise<string>> -// >(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[16]>, -// Readonly<Record<string, string>> -// >(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[17]>, -// Readonly<Record<string, number>> -// >(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[18]>, -// { readonly a: string; readonly 1: number } -// >(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[19]>, -// Readonly<testEnum> -// >(true); -// util.assertEqual< -// z.infer<(typeof deepReadonlySchemas_0)[20]>, -// Promise<string> -// >(true); - -// util.assertEqual< -// z.infer<typeof crazyDeepReadonlySchema>, -// ReadonlyMap< -// ReadonlySet<readonly [string, number]>, -// { -// readonly a: { -// readonly [x: string]: readonly any[]; -// }; -// readonly b: { -// readonly c: { -// readonly d: { -// readonly e: { -// readonly f: { -// readonly g?: {}; -// }; -// }; -// }; -// }; -// }; -// } -// > -// >(true); -// }); - -test("object freezing", () => { - expect(Object.isFrozen(z.array(z.string()).readonly().parse(["a"]))).toBe( - true - ); - expect( - Object.isFrozen( - z.tuple([z.string(), z.number()]).readonly().parse(["a", 1]) - ) - ).toBe(true); - expect( - Object.isFrozen( - z - .map(z.string(), z.date()) - .readonly() - .parse(new Map([["a", new Date()]])) - ) - ).toBe(true); - expect( - Object.isFrozen( - z - .set(z.promise(z.string())) - .readonly() - .parse(new Set([Promise.resolve("a")])) - ) - ).toBe(true); - expect( - Object.isFrozen(z.record(z.string()).readonly().parse({ a: "b" })) - ).toBe(true); - expect( - Object.isFrozen(z.record(z.string(), z.number()).readonly().parse({ a: 1 })) - ).toBe(true); - expect( - Object.isFrozen( - z - .object({ a: z.string(), 1: z.number() }) - .readonly() - .parse({ a: "b", 1: 2 }) - ) - ).toBe(true); - expect( - Object.isFrozen( - z.promise(z.string()).readonly().parse(Promise.resolve("a")) - ) - ).toBe(true); -}); diff --git a/deno/lib/__tests__/record.test.ts b/deno/lib/__tests__/record.test.ts deleted file mode 100644 index ecb698af9..000000000 --- a/deno/lib/__tests__/record.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -// @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"; - -const booleanRecord = z.record(z.boolean()); -type booleanRecord = z.infer<typeof booleanRecord>; - -const recordWithEnumKeys = z.record(z.enum(["Tuna", "Salmon"]), z.string()); -type recordWithEnumKeys = z.infer<typeof recordWithEnumKeys>; - -const recordWithLiteralKeys = z.record( - z.union([z.literal("Tuna"), z.literal("Salmon")]), - z.string() -); -type recordWithLiteralKeys = z.infer<typeof recordWithLiteralKeys>; - -test("type inference", () => { - util.assertEqual<booleanRecord, Record<string, boolean>>(true); - - util.assertEqual< - recordWithEnumKeys, - Partial<Record<"Tuna" | "Salmon", string>> - >(true); - - util.assertEqual< - recordWithLiteralKeys, - Partial<Record<"Tuna" | "Salmon", string>> - >(true); -}); - -test("methods", () => { - booleanRecord.optional(); - booleanRecord.nullable(); -}); - -test("string record parse - pass", () => { - booleanRecord.parse({ - k1: true, - k2: false, - 1234: false, - }); -}); - -test("string record parse - fail", () => { - const badCheck = () => - booleanRecord.parse({ - asdf: 1234, - } as any); - expect(badCheck).toThrow(); - - expect(() => booleanRecord.parse("asdf")).toThrow(); -}); - -test("string record parse - fail", () => { - const badCheck = () => - booleanRecord.parse({ - asdf: {}, - } as any); - expect(badCheck).toThrow(); -}); - -test("string record parse - fail", () => { - const badCheck = () => - booleanRecord.parse({ - asdf: [], - } as any); - expect(badCheck).toThrow(); -}); - -test("key schema", () => { - const result1 = recordWithEnumKeys.parse({ - Tuna: "asdf", - Salmon: "asdf", - }); - expect(result1).toEqual({ - Tuna: "asdf", - Salmon: "asdf", - }); - - const result2 = recordWithLiteralKeys.parse({ - Tuna: "asdf", - Salmon: "asdf", - }); - expect(result2).toEqual({ - Tuna: "asdf", - Salmon: "asdf", - }); - - // shouldn't require us to specify all props in record - const result3 = recordWithEnumKeys.parse({ - Tuna: "abcd", - }); - expect(result3).toEqual({ - Tuna: "abcd", - }); - - // shouldn't require us to specify all props in record - const result4 = recordWithLiteralKeys.parse({ - Salmon: "abcd", - }); - expect(result4).toEqual({ - Salmon: "abcd", - }); - - expect(() => - recordWithEnumKeys.parse({ - Tuna: "asdf", - Salmon: "asdf", - Trout: "asdf", - }) - ).toThrow(); - - expect(() => - recordWithLiteralKeys.parse({ - Tuna: "asdf", - Salmon: "asdf", - - Trout: "asdf", - }) - ).toThrow(); -}); - -// test("record element", () => { -// expect(booleanRecord.element).toBeInstanceOf(z.ZodBoolean); -// }); - -test("key and value getters", () => { - const rec = z.record(z.string(), z.number()); - - rec.keySchema.parse("asdf"); - rec.valueSchema.parse(1234); - rec.element.parse(1234); -}); - -test("is not vulnerable to prototype pollution", async () => { - const rec = z.record( - z.object({ - a: z.string(), - }) - ); - - const data = JSON.parse(` - { - "__proto__": { - "a": "evil" - }, - "b": { - "a": "good" - } - } - `); - - const obj1 = rec.parse(data); - expect(obj1.a).toBeUndefined(); - - const obj2 = rec.safeParse(data); - expect(obj2.success).toBe(true); - if (obj2.success) { - expect(obj2.data.a).toBeUndefined(); - } - - const obj3 = await rec.parseAsync(data); - expect(obj3.a).toBeUndefined(); - - const obj4 = await rec.safeParseAsync(data); - expect(obj4.success).toBe(true); - if (obj4.success) { - expect(obj4.data.a).toBeUndefined(); - } -}); diff --git a/deno/lib/__tests__/recursive.test.ts b/deno/lib/__tests__/recursive.test.ts deleted file mode 100644 index 4f359c656..000000000 --- a/deno/lib/__tests__/recursive.test.ts +++ /dev/null @@ -1,198 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import { z } from "../index.ts"; - -interface Category { - name: string; - subcategories: Category[]; -} - -const testCategory: Category = { - name: "I", - subcategories: [ - { - name: "A", - subcategories: [ - { - name: "1", - subcategories: [ - { - name: "a", - subcategories: [], - }, - ], - }, - ], - }, - ], -}; - -test("recursion with z.late.object", () => { - const Category: z.ZodType<Category> = z.late.object(() => ({ - name: z.string(), - subcategories: z.array(Category), - })); - Category.parse(testCategory); -}); - -test("recursion with z.lazy", () => { - const Category: z.ZodType<Category> = z.lazy(() => - z.object({ - name: z.string(), - subcategories: z.array(Category), - }) - ); - Category.parse(testCategory); -}); - -test("schema getter", () => { - z.lazy(() => z.string()).schema.parse("asdf"); -}); - -type LinkedList = null | { value: number; next: LinkedList }; - -const linkedListExample = { - value: 1, - next: { - value: 2, - next: { - value: 3, - next: { - value: 4, - next: null, - }, - }, - }, -}; - -test("recursion involving union type", () => { - const LinkedListSchema: z.ZodType<LinkedList> = z.lazy(() => - z.union([ - z.null(), - z.object({ - value: z.number(), - next: LinkedListSchema, - }), - ]) - ); - LinkedListSchema.parse(linkedListExample); -}); - -// interface A { -// val: number; -// b: B; -// } - -// interface B { -// val: number; -// a: A; -// } - -// const A: z.ZodType<A> = z.late.object(() => ({ -// val: z.number(), -// b: B, -// })); - -// const B: z.ZodType<B> = z.late.object(() => ({ -// val: z.number(), -// a: A, -// })); - -// const Alazy: z.ZodType<A> = z.lazy(() => z.object({ -// val: z.number(), -// b: B, -// })); - -// const Blazy: z.ZodType<B> = z.lazy(() => z.object({ -// val: z.number(), -// a: A, -// })); - -// const a: any = { val: 1 }; -// const b: any = { val: 2 }; -// a.b = b; -// b.a = a; - -// test('valid check', () => { -// A.parse(a); -// B.parse(b); -// }); - -// test("valid check lazy", () => { -// A.parse({val:1, b:}); -// B.parse(b); -// }); - -// test('masking check', () => { -// const FragmentOnA = z -// .object({ -// val: z.number(), -// b: z -// .object({ -// val: z.number(), -// a: z -// .object({ -// val: z.number(), -// }) -// .nonstrict(), -// }) -// .nonstrict(), -// }) -// .nonstrict(); - -// const fragment = FragmentOnA.parse(a); -// fragment; -// }); - -// test('invalid check', () => { -// expect(() => A.parse({} as any)).toThrow(); -// }); - -// test('schema getter', () => { -// (A as z.ZodLazy<any>).schema; -// }); - -// test("self recursion with cyclical data", () => { -// interface Category { -// name: string; -// subcategories: Category[]; -// } - -// const Category: z.ZodType<Category> = z.late.object(() => ({ -// name: z.string(), -// subcategories: z.array(Category), -// })); - -// const untypedCategory: any = { -// name: "Category A", -// }; -// // creating a cycle -// untypedCategory.subcategories = [untypedCategory]; -// Category.parse(untypedCategory); -// }); - -// test("self recursion with base type", () => { -// const BaseCategory = z.object({ -// name: z.string(), -// }); -// type BaseCategory = z.infer<typeof BaseCategory>; - -// type Category = BaseCategory & { subcategories: Category[] }; - -// const Category: z.ZodType<Category> = z.late -// .object(() => ({ -// subcategories: z.array(Category), -// })) -// .extend({ -// name: z.string(), -// }); - -// const untypedCategory: any = { -// name: "Category A", -// }; -// // creating a cycle -// untypedCategory.subcategories = [untypedCategory]; -// Category.parse(untypedCategory); // parses successfully -// }); diff --git a/deno/lib/__tests__/refine.test.ts b/deno/lib/__tests__/refine.test.ts deleted file mode 100644 index f505fdbb7..000000000 --- a/deno/lib/__tests__/refine.test.ts +++ /dev/null @@ -1,307 +0,0 @@ -// @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 { ZodIssueCode } from "../ZodError.ts"; - -test("refinement", () => { - const obj1 = z.object({ - first: z.string(), - second: z.string(), - }); - const obj2 = obj1.partial().strict(); - - const obj3 = obj2.refine( - (data) => data.first || data.second, - "Either first or second should be filled in." - ); - - expect(obj1 === (obj2 as any)).toEqual(false); - expect(obj2 === (obj3 as any)).toEqual(false); - - expect(() => obj1.parse({})).toThrow(); - expect(() => obj2.parse({ third: "adsf" })).toThrow(); - expect(() => obj3.parse({})).toThrow(); - obj3.parse({ first: "a" }); - obj3.parse({ second: "a" }); - obj3.parse({ first: "a", second: "a" }); -}); - -test("refinement 2", () => { - const validationSchema = z - .object({ - email: z.string().email(), - password: z.string(), - confirmPassword: z.string(), - }) - .refine( - (data) => data.password === data.confirmPassword, - "Both password and confirmation must match" - ); - - expect(() => - validationSchema.parse({ - email: "aaaa@gmail.com", - password: "aaaaaaaa", - confirmPassword: "bbbbbbbb", - }) - ).toThrow(); -}); - -test("refinement type guard", () => { - const validationSchema = z.object({ - a: z.string().refine((s): s is "a" => s === "a"), - }); - type Input = z.input<typeof validationSchema>; - type Schema = z.infer<typeof validationSchema>; - - util.assertEqual<"a", Input["a"]>(false); - util.assertEqual<string, Input["a"]>(true); - - util.assertEqual<"a", Schema["a"]>(true); - util.assertEqual<string, Schema["a"]>(false); -}); - -test("refinement Promise", async () => { - const validationSchema = z - .object({ - email: z.string().email(), - password: z.string(), - confirmPassword: z.string(), - }) - .refine( - (data) => - Promise.resolve().then(() => data.password === data.confirmPassword), - "Both password and confirmation must match" - ); - - await validationSchema.parseAsync({ - email: "aaaa@gmail.com", - password: "password", - confirmPassword: "password", - }); -}); - -test("custom path", async () => { - const result = await z - .object({ - password: z.string(), - confirm: z.string(), - }) - .refine((data) => data.confirm === data.password, { path: ["confirm"] }) - .spa({ password: "asdf", confirm: "qewr" }); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].path).toEqual(["confirm"]); - } -}); - -test("use path in refinement context", async () => { - const noNested = z.string()._refinement((_val, ctx) => { - if (ctx.path.length > 0) { - ctx.addIssue({ - code: ZodIssueCode.custom, - message: `schema cannot be nested. path: ${ctx.path.join(".")}`, - }); - return false; - } else { - return true; - } - }); - - const data = z.object({ - foo: noNested, - }); - - const t1 = await noNested.spa("asdf"); - const t2 = await data.spa({ foo: "asdf" }); - - expect(t1.success).toBe(true); - expect(t2.success).toBe(false); - if (t2.success === false) { - expect(t2.error.issues[0].message).toEqual( - "schema cannot be nested. path: foo" - ); - } -}); - -test("superRefine", () => { - const Strings = z.array(z.string()).superRefine((val, ctx) => { - if (val.length > 3) { - ctx.addIssue({ - code: z.ZodIssueCode.too_big, - maximum: 3, - type: "array", - inclusive: true, - exact: true, - message: "Too many items 😡", - }); - } - - if (val.length !== new Set(val).size) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: `No duplicates allowed.`, - }); - } - }); - - const result = Strings.safeParse(["asfd", "asfd", "asfd", "asfd"]); - - expect(result.success).toEqual(false); - if (!result.success) expect(result.error.issues.length).toEqual(2); - - Strings.parse(["asfd", "qwer"]); -}); - -test("superRefine async", async () => { - const Strings = z.array(z.string()).superRefine(async (val, ctx) => { - if (val.length > 3) { - ctx.addIssue({ - code: z.ZodIssueCode.too_big, - maximum: 3, - type: "array", - inclusive: true, - exact: true, - message: "Too many items 😡", - }); - } - - if (val.length !== new Set(val).size) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: `No duplicates allowed.`, - }); - } - }); - - const result = await Strings.safeParseAsync(["asfd", "asfd", "asfd", "asfd"]); - - expect(result.success).toEqual(false); - if (!result.success) expect(result.error.issues.length).toEqual(2); - - Strings.parseAsync(["asfd", "qwer"]); -}); - -test("superRefine - type narrowing", () => { - type NarrowType = { type: string; age: number }; - const schema = z - .object({ - type: z.string(), - age: z.number(), - }) - .nullable() - .superRefine((arg, ctx): arg is NarrowType => { - if (!arg) { - // still need to make a call to ctx.addIssue - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "cannot be null", - fatal: true, - }); - return false; - } - return true; - }); - - util.assertEqual<z.infer<typeof schema>, NarrowType>(true); - - expect(schema.safeParse({ type: "test", age: 0 }).success).toEqual(true); - expect(schema.safeParse(null).success).toEqual(false); -}); - -test("chained mixed refining types", () => { - type firstRefinement = { first: string; second: number; third: true }; - type secondRefinement = { first: "bob"; second: number; third: true }; - type thirdRefinement = { first: "bob"; second: 33; third: true }; - const schema = z - .object({ - first: z.string(), - second: z.number(), - third: z.boolean(), - }) - .nullable() - .refine((arg): arg is firstRefinement => !!arg?.third) - .superRefine((arg, ctx): arg is secondRefinement => { - util.assertEqual<typeof arg, firstRefinement>(true); - if (arg.first !== "bob") { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "`first` property must be `bob`", - }); - return false; - } - return true; - }) - .refine((arg): arg is thirdRefinement => { - util.assertEqual<typeof arg, secondRefinement>(true); - return arg.second === 33; - }); - - util.assertEqual<z.infer<typeof schema>, thirdRefinement>(true); -}); - -test("get inner type", () => { - z.string() - .refine(() => true) - .innerType() - .parse("asdf"); -}); - -test("chained refinements", () => { - const objectSchema = z - .object({ - length: z.number(), - size: z.number(), - }) - .refine(({ length }) => length > 5, { - path: ["length"], - message: "length greater than 5", - }) - .refine(({ size }) => size > 7, { - path: ["size"], - message: "size greater than 7", - }); - const r1 = objectSchema.safeParse({ - length: 4, - size: 9, - }); - expect(r1.success).toEqual(false); - if (!r1.success) expect(r1.error.issues.length).toEqual(1); - - const r2 = objectSchema.safeParse({ - length: 4, - size: 3, - }); - expect(r2.success).toEqual(false); - if (!r2.success) expect(r2.error.issues.length).toEqual(2); -}); - -test("fatal superRefine", () => { - const Strings = z - .string() - .superRefine((val, ctx) => { - if (val === "") { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "foo", - fatal: true, - }); - } - }) - .superRefine((val, ctx) => { - if (val !== " ") { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "bar", - }); - } - }); - - const result = Strings.safeParse(""); - - expect(result.success).toEqual(false); - if (!result.success) expect(result.error.issues.length).toEqual(1); -}); diff --git a/deno/lib/__tests__/safeparse.test.ts b/deno/lib/__tests__/safeparse.test.ts deleted file mode 100644 index fbae3d72b..000000000 --- a/deno/lib/__tests__/safeparse.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; -const stringSchema = z.string(); - -test("safeparse fail", () => { - const safe = stringSchema.safeParse(12); - expect(safe.success).toEqual(false); - expect(safe.error).toBeInstanceOf(z.ZodError); -}); - -test("safeparse pass", () => { - const safe = stringSchema.safeParse("12"); - expect(safe.success).toEqual(true); - expect(safe.data).toEqual("12"); -}); - -test("safeparse unexpected error", () => { - expect(() => - stringSchema - .refine((data) => { - throw new Error(data); - }) - .safeParse("12") - ).toThrow(); -}); diff --git a/deno/lib/__tests__/set.test.ts b/deno/lib/__tests__/set.test.ts deleted file mode 100644 index 0626bac94..000000000 --- a/deno/lib/__tests__/set.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -// @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 { ZodIssueCode } from "../index.ts"; - -const stringSet = z.set(z.string()); -type stringSet = z.infer<typeof stringSet>; - -const minTwo = z.set(z.string()).min(2); -const maxTwo = z.set(z.string()).max(2); -const justTwo = z.set(z.string()).size(2); -const nonEmpty = z.set(z.string()).nonempty(); -const nonEmptyMax = z.set(z.string()).nonempty().max(2); - -test("type inference", () => { - util.assertEqual<stringSet, Set<string>>(true); -}); - -test("valid parse", () => { - const result = stringSet.safeParse(new Set(["first", "second"])); - expect(result.success).toEqual(true); - if (result.success) { - expect(result.data.has("first")).toEqual(true); - expect(result.data.has("second")).toEqual(true); - expect(result.data.has("third")).toEqual(false); - } - - expect(() => { - minTwo.parse(new Set(["a", "b"])); - minTwo.parse(new Set(["a", "b", "c"])); - maxTwo.parse(new Set(["a", "b"])); - maxTwo.parse(new Set(["a"])); - justTwo.parse(new Set(["a", "b"])); - nonEmpty.parse(new Set(["a"])); - nonEmptyMax.parse(new Set(["a"])); - }).not.toThrow(); -}); - -test("valid parse async", async () => { - const result = await stringSet.spa(new Set(["first", "second"])); - expect(result.success).toEqual(true); - if (result.success) { - expect(result.data.has("first")).toEqual(true); - expect(result.data.has("second")).toEqual(true); - expect(result.data.has("third")).toEqual(false); - } - - const asyncResult = await stringSet.safeParse(new Set(["first", "second"])); - expect(asyncResult.success).toEqual(true); - if (asyncResult.success) { - expect(asyncResult.data.has("first")).toEqual(true); - expect(asyncResult.data.has("second")).toEqual(true); - expect(asyncResult.data.has("third")).toEqual(false); - } -}); - -test("valid parse: size-related methods", () => { - expect(() => { - minTwo.parse(new Set(["a", "b"])); - minTwo.parse(new Set(["a", "b", "c"])); - maxTwo.parse(new Set(["a", "b"])); - maxTwo.parse(new Set(["a"])); - justTwo.parse(new Set(["a", "b"])); - nonEmpty.parse(new Set(["a"])); - nonEmptyMax.parse(new Set(["a"])); - }).not.toThrow(); - - const sizeZeroResult = stringSet.parse(new Set()); - expect(sizeZeroResult.size).toBe(0); - - const sizeTwoResult = minTwo.parse(new Set(["a", "b"])); - expect(sizeTwoResult.size).toBe(2); -}); - -test("failing when parsing empty set in nonempty ", () => { - const result = nonEmpty.safeParse(new Set()); - expect(result.success).toEqual(false); - - if (result.success === false) { - expect(result.error.issues.length).toEqual(1); - expect(result.error.issues[0].code).toEqual(ZodIssueCode.too_small); - } -}); - -test("failing when set is smaller than min() ", () => { - const result = minTwo.safeParse(new Set(["just_one"])); - expect(result.success).toEqual(false); - - if (result.success === false) { - expect(result.error.issues.length).toEqual(1); - expect(result.error.issues[0].code).toEqual(ZodIssueCode.too_small); - } -}); - -test("failing when set is bigger than max() ", () => { - const result = maxTwo.safeParse(new Set(["one", "two", "three"])); - expect(result.success).toEqual(false); - - if (result.success === false) { - expect(result.error.issues.length).toEqual(1); - expect(result.error.issues[0].code).toEqual(ZodIssueCode.too_big); - } -}); - -test("doesn’t throw when an empty set is given", () => { - const result = stringSet.safeParse(new Set([])); - expect(result.success).toEqual(true); -}); - -test("throws when a Map is given", () => { - const result = stringSet.safeParse(new Map([])); - expect(result.success).toEqual(false); - if (result.success === false) { - expect(result.error.issues.length).toEqual(1); - expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); - } -}); - -test("throws when the given set has invalid input", () => { - const result = stringSet.safeParse(new Set([Symbol()])); - expect(result.success).toEqual(false); - if (result.success === false) { - expect(result.error.issues.length).toEqual(1); - expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); - expect(result.error.issues[0].path).toEqual([0]); - } -}); - -test("throws when the given set has multiple invalid entries", () => { - const result = stringSet.safeParse(new Set([1, 2] as any[]) as Set<any>); - - expect(result.success).toEqual(false); - if (result.success === false) { - expect(result.error.issues.length).toEqual(2); - expect(result.error.issues[0].code).toEqual(ZodIssueCode.invalid_type); - expect(result.error.issues[0].path).toEqual([0]); - expect(result.error.issues[1].code).toEqual(ZodIssueCode.invalid_type); - expect(result.error.issues[1].path).toEqual([1]); - } -}); diff --git a/deno/lib/__tests__/string.test.ts b/deno/lib/__tests__/string.test.ts deleted file mode 100644 index 2dc5b79a6..000000000 --- a/deno/lib/__tests__/string.test.ts +++ /dev/null @@ -1,512 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -const minFive = z.string().min(5, "min5"); -const maxFive = z.string().max(5, "max5"); -const justFive = z.string().length(5); -const nonempty = z.string().min(1, "nonempty"); -const includes = z.string().includes("includes"); -const includesFromIndex2 = z.string().includes("includes", { position: 2 }); -const startsWith = z.string().startsWith("startsWith"); -const endsWith = z.string().endsWith("endsWith"); - -test("passing validations", () => { - minFive.parse("12345"); - minFive.parse("123456"); - maxFive.parse("12345"); - maxFive.parse("1234"); - nonempty.parse("1"); - justFive.parse("12345"); - includes.parse("XincludesXX"); - includesFromIndex2.parse("XXXincludesXX"); - startsWith.parse("startsWithX"); - endsWith.parse("XendsWith"); -}); - -test("failing validations", () => { - expect(() => minFive.parse("1234")).toThrow(); - expect(() => maxFive.parse("123456")).toThrow(); - expect(() => nonempty.parse("")).toThrow(); - expect(() => justFive.parse("1234")).toThrow(); - expect(() => justFive.parse("123456")).toThrow(); - expect(() => includes.parse("XincludeXX")).toThrow(); - expect(() => includesFromIndex2.parse("XincludesXX")).toThrow(); - expect(() => startsWith.parse("x")).toThrow(); - expect(() => endsWith.parse("x")).toThrow(); -}); - -test("email validations", () => { - const validEmails = [ - `email@domain.com`, - `firstname.lastname@domain.com`, - `email@subdomain.domain.com`, - `firstname+lastname@domain.com`, - `1234567890@domain.com`, - `email@domain-one.com`, - `_______@domain.com`, - `email@domain.name`, - `email@domain.co.jp`, - `firstname-lastname@domain.com`, - `very.common@example.com`, - `disposable.style.email.with+symbol@example.com`, - `other.email-with-hyphen@example.com`, - `fully-qualified-domain@example.com`, - `user.name+tag+sorting@example.com`, - `x@example.com`, - `mojojojo@asdf.example.com`, - `example-indeed@strange-example.com`, - `example@s.example`, - `user-@example.org`, - `user@my-example.com`, - `a@b.cd`, - `work+user@mail.com`, - `tom@test.te-st.com`, - `something@subdomain.domain-with-hyphens.tld`, - `francois@etu.inp-n7.fr`, - ]; - const invalidEmails = [ - // no "printable characters" - // `user%example.com@example.org`, - // `mailhost!username@example.org`, - // `test/test@test.com`, - - // double @ - `francois@@etu.inp-n7.fr`, - // do not support quotes - `"email"@domain.com`, - `"e asdf sadf ?<>ail"@domain.com`, - `" "@example.org`, - `"john..doe"@example.org`, - `"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com`, - - // do not support IPv4 - `email@123.123.123.123`, - `email@[123.123.123.123]`, - `postmaster@123.123.123.123`, - `user@[68.185.127.196]`, - `ipv4@[85.129.96.247]`, - `valid@[79.208.229.53]`, - `valid@[255.255.255.255]`, - `valid@[255.0.55.2]`, - `valid@[255.0.55.2]`, - - // do not support ipv6 - `hgrebert0@[IPv6:4dc8:ac7:ce79:8878:1290:6098:5c50:1f25]`, - `bshapiro4@[IPv6:3669:c709:e981:4884:59a3:75d1:166b:9ae]`, - `jsmith@[IPv6:2001:db8::1]`, - `postmaster@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:7334]`, - `postmaster@[IPv6:2001:0db8:85a3:0000:0000:8a2e:0370:192.168.1.1]`, - - // microsoft test cases - `plainaddress`, - `#@%^%#$@#$@#.com`, - `@domain.com`, - `Joe Smith <email@domain.com>`, - `email.domain.com`, - `email@domain@domain.com`, - `.email@domain.com`, - `email.@domain.com`, - `email..email@domain.com`, - `あいうえお@domain.com`, - `email@domain.com (Joe Smith)`, - `email@domain`, - `email@-domain.com`, - `email@111.222.333.44444`, - `email@domain..com`, - `Abc.example.com`, - `A@b@c@example.com`, - `colin..hacks@domain.com`, - `a"b(c)d,e:f;g<h>i[j\k]l@example.com`, - `just"not"right@example.com`, - `this is"not\allowed@example.com`, - `this\ still\"not\\allowed@example.com`, - - // random - `i_like_underscore@but_its_not_allowed_in_this_part.example.com`, - `QA[icon]CHOCOLATE[icon]@test.com`, - `invalid@-start.com`, - `invalid@end.com-`, - `a.b@c.d`, - `invalid@[1.1.1.-1]`, - `invalid@[68.185.127.196.55]`, - `temp@[192.168.1]`, - `temp@[9.18.122.]`, - `double..point@test.com`, - `asdad@test..com`, - `asdad@hghg...sd...au`, - `asdad@hghg........au`, - `invalid@[256.2.2.48]`, - `invalid@[256.2.2.48]`, - `invalid@[999.465.265.1]`, - `jkibbey4@[IPv6:82c4:19a8::70a9:2aac:557::ea69:d985:28d]`, - `mlivesay3@[9952:143f:b4df:2179:49a1:5e82:b92e:6b6]`, - `gbacher0@[IPv6:bc37:4d3f:5048:2e26:37cc:248e:df8e:2f7f:af]`, - `invalid@[IPv6:5348:4ed3:5d38:67fb:e9b:acd2:c13:192.168.256.1]`, - `test@.com`, - `aaaaaaaaaaaaaaalongemailthatcausesregexDoSvulnerability@test.c`, - ]; - const emailSchema = z.string().email(); - - expect( - validEmails.every((email) => { - return emailSchema.safeParse(email).success; - }) - ).toBe(true); - expect( - invalidEmails.every((email) => { - return emailSchema.safeParse(email).success === false; - }) - ).toBe(true); -}); - -test("url validations", () => { - const url = z.string().url(); - url.parse("http://google.com"); - url.parse("https://google.com/asdf?asdf=ljk3lk4&asdf=234#asdf"); - expect(() => url.parse("asdf")).toThrow(); - expect(() => url.parse("https:/")).toThrow(); - expect(() => url.parse("asdfj@lkjsdf.com")).toThrow(); -}); - -test("url error overrides", () => { - try { - z.string().url().parse("https"); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual("Invalid url"); - } - try { - z.string().url("badurl").parse("https"); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual("badurl"); - } - try { - z.string().url({ message: "badurl" }).parse("https"); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual("badurl"); - } -}); - -test("emoji validations", () => { - const emoji = z.string().emoji(); - - emoji.parse("👋👋👋👋"); - emoji.parse("🍺👩🚀🫡"); - emoji.parse("💚💙💜💛❤️"); - emoji.parse("🐛🗝🐏🍡🎦🚢🏨💫🎌☘🗡😹🔒🎬➡️🍹🗂🚨⚜🕑〽️🚦🌊🍴💍🍌💰😳🌺🍃"); - emoji.parse("🇹🇷🤽🏿♂️"); - emoji.parse( - "😀😁😂🤣😃😄😅😆😉😊😋😎😍😘🥰😗😙😚☺️☺🙂🤗🤩🤔🤨😐😑😶🙄😏😣😥😮🤐😯😪😫😴😌😛😜😝🤤😒😓😔😕🙃🤑😲☹️☹🙁😖😞😟😤😢😭😦😧😨😩🤯😬😰😱🥵🥶😳🤪😵😡😠🤬😷🤒🤕🤢🤮🤧😇🤠🥳🥴🥺🤥🤫🤭🧐🤓😈👿🤡👹👺💀☠️☠👻👽👾🤖💩😺😸😹😻😼😽🙀😿😾🙈🙉🙊🏻🏼🏽🏾🏿👶👶🏻👶🏼👶🏽👶🏾👶🏿🧒🧒🏻🧒🏼🧒🏽🧒🏾🧒🏿👦👦🏻👦🏼👦🏽👦🏾👦🏿👧👧🏻👧🏼👧🏽👧🏾👧🏿🧑🧑🏻🧑🏼🧑🏽🧑🏾🧑🏿👨👨🏻👨🏼👨🏽👨🏾👨🏿👩👩🏻👩🏼👩🏽👩🏾👩🏿🧓🧓🏻🧓🏼🧓🏽🧓🏾🧓🏿👴👴🏻👴🏼👴🏽👴🏾👴🏿👵👵🏻👵🏼👵🏽👵🏾👵🏿👨⚕️👨⚕👨🏻⚕️👨🏻⚕👨🏼⚕️👨🏼⚕👨🏽⚕️👨🏽⚕👨🏾⚕️👨🏾⚕👨🏿⚕️👨🏿⚕👩⚕️👩⚕👩🏻⚕️👩🏻⚕👩🏼⚕️👩🏼⚕👩🏽⚕️👩🏽⚕👩🏾⚕️👩🏾⚕👩🏿⚕️👩🏿⚕👨🎓👨🏻🎓👨🏼🎓👨🏽🎓👨🏾🎓👨🏿🎓👩🎓👩🏻🎓👩🏼🎓👩🏽🎓👩🏾🎓👩🏿🎓👨🏫👨🏻🏫👨🏼🏫👨🏽🏫👨🏾🏫👨🏿🏫👩🏫👩🏻🏫👩🏼🏫👩🏽🏫👩🏾🏫👩🏿🏫👨⚖️👨⚖👨🏻⚖️👨🏻⚖👨🏼⚖️👨🏼⚖👨🏽⚖️👨🏽⚖👨🏾⚖️👨🏾⚖👨🏿⚖️👨🏿⚖👩⚖️👩⚖👩🏻⚖️👩🏻⚖👩🏼⚖️👩🏼⚖👩🏽⚖️👩🏽⚖👩🏾⚖️👩🏾⚖👩🏿⚖️👩🏿⚖👨🌾👨🏻🌾👨🏼🌾👨🏽🌾👨🏾🌾👨🏿🌾👩🌾👩🏻🌾👩🏼🌾👩🏽🌾👩🏾🌾👩🏿🌾👨🍳👨🏻🍳👨🏼🍳👨🏽🍳👨🏾🍳👨🏿🍳👩🍳👩🏻🍳👩🏼🍳👩🏽🍳👩🏾🍳👩🏿🍳👨🔧👨🏻🔧👨🏼🔧👨🏽🔧👨🏾🔧👨🏿🔧👩🔧👩🏻🔧👩🏼🔧👩🏽🔧👩🏾🔧👩🏿🔧👨🏭👨🏻🏭👨🏼🏭👨🏽🏭👨🏾🏭👨🏿🏭👩🏭👩🏻🏭👩🏼🏭👩🏽🏭👩🏾🏭👩🏿🏭👨💼👨🏻💼👨🏼💼👨🏽💼👨🏾💼👨🏿💼👩💼👩🏻💼👩🏼💼👩🏽💼👩🏾💼👩🏿💼👨🔬👨🏻🔬👨🏼🔬👨🏽🔬👨🏾🔬👨🏿🔬👩🔬👩🏻🔬👩🏼🔬👩🏽🔬👩🏾🔬👩🏿🔬👨💻👨🏻💻👨🏼💻👨🏽💻👨🏾💻👨🏿💻👩💻👩🏻💻👩🏼💻👩🏽💻👩🏾💻👩🏿💻👨🎤👨🏻🎤👨🏼🎤👨🏽🎤👨🏾🎤👨🏿🎤👩🎤👩🏻🎤👩🏼🎤👩🏽🎤👩🏾🎤👩🏿🎤👨🎨👨🏻🎨👨🏼🎨👨🏽🎨👨🏾🎨👨🏿🎨👩🎨👩🏻🎨👩🏼🎨👩🏽🎨👩🏾🎨👩🏿🎨👨✈️👨✈👨🏻✈️👨🏻✈👨🏼✈️👨🏼✈👨🏽✈️👨🏽✈👨🏾✈️👨🏾✈👨🏿✈️👨🏿✈👩✈️👩✈👩🏻✈️👩🏻✈👩🏼✈️👩🏼✈👩🏽✈️👩🏽✈👩🏾✈️👩🏾✈👩🏿✈️👩🏿✈👨🚀👨🏻🚀👨🏼🚀👨🏽🚀👨🏾🚀👨🏿🚀👩🚀👩🏻🚀👩🏼🚀👩🏽🚀👩🏾🚀👩🏿🚀👨🚒👨🏻🚒👨🏼🚒👨🏽🚒👨🏾🚒👨🏿🚒👩🚒👩🏻🚒👩🏼🚒👩🏽🚒👩🏾🚒👩🏿🚒👮👮🏻👮🏼👮🏽👮🏾👮🏿👮♂️👮♂👮🏻♂️👮🏻♂👮🏼♂️👮🏼♂👮🏽♂️👮🏽♂👮🏾♂️👮🏾♂👮🏿♂️👮🏿♂👮♀️👮♀👮🏻♀️👮🏻♀👮🏼♀️👮🏼♀👮🏽♀️👮🏽♀👮🏾♀️👮🏾♀👮🏿♀️👮🏿♀🕵️🕵🕵🏻🕵🏼🕵🏽🕵🏾🕵🏿🕵️♂️🕵♂️🕵️♂🕵♂🕵🏻♂️🕵🏻♂🕵🏼♂️🕵🏼♂🕵🏽♂️🕵🏽♂🕵🏾♂️🕵🏾♂🕵🏿♂️🕵🏿♂🕵️♀️🕵♀️🕵️♀🕵♀🕵🏻♀️🕵🏻♀🕵🏼♀️🕵🏼♀🕵🏽♀️🕵🏽♀🕵🏾♀️🕵🏾♀🕵🏿♀️🕵🏿♀💂💂🏻💂🏼💂🏽💂🏾💂🏿💂♂️💂♂💂🏻♂️💂🏻♂💂🏼♂️💂🏼♂💂🏽♂️💂🏽♂💂🏾♂️💂🏾♂💂🏿♂️💂🏿♂💂♀️💂♀💂🏻♀️💂🏻♀💂🏼♀️💂🏼♀💂🏽♀️💂🏽♀💂🏾♀️💂🏾♀💂🏿♀️💂🏿♀👷👷🏻👷🏼👷🏽👷🏾👷🏿👷♂️👷♂👷🏻♂️👷🏻♂👷🏼♂️👷🏼♂👷🏽♂️👷🏽♂👷🏾♂️👷🏾♂👷🏿♂️👷🏿♂👷♀️👷♀👷🏻♀️👷🏻♀👷🏼♀️👷🏼♀👷🏽♀️👷🏽♀👷🏾♀️👷🏾♀👷🏿♀️👷🏿♀🤴🤴🏻🤴🏼🤴🏽🤴🏾🤴🏿👸👸🏻👸🏼👸🏽👸🏾👸🏿👳👳🏻👳🏼👳🏽👳🏾👳🏿👳♂️👳♂👳🏻♂️👳🏻♂👳🏼♂️👳🏼♂👳🏽♂️👳🏽♂👳🏾♂️👳🏾♂👳🏿♂️👳🏿♂👳♀️👳♀👳🏻♀️👳🏻♀👳🏼♀️👳🏼♀👳🏽♀️👳🏽♀👳🏾♀️👳🏾♀👳🏿♀️👳🏿♀👲👲🏻👲🏼👲🏽👲🏾👲🏿🧕🧕🏻🧕🏼🧕🏽🧕🏾🧕🏿🧔🧔🏻🧔🏼🧔🏽🧔🏾🧔🏿👱👱🏻👱🏼👱🏽👱🏾👱🏿👱♂️👱♂👱🏻♂️👱🏻♂👱🏼♂️👱🏼♂👱🏽♂️👱🏽♂👱🏾♂️👱🏾♂👱🏿♂️👱🏿♂👱♀️👱♀👱🏻♀️👱🏻♀👱🏼♀️👱🏼♀👱🏽♀️👱🏽♀👱🏾♀️👱🏾♀👱🏿♀️👱🏿♀👨🦰👨🏻🦰👨🏼🦰👨🏽🦰👨🏾🦰👨🏿🦰👩🦰👩🏻🦰👩🏼🦰👩🏽🦰👩🏾🦰👩🏿🦰👨🦱👨🏻🦱👨🏼🦱👨🏽🦱👨🏾🦱👨🏿🦱👩🦱👩🏻🦱👩🏼🦱👩🏽🦱👩🏾🦱👩🏿🦱👨🦲👨🏻🦲👨🏼🦲👨🏽🦲👨🏾🦲👨🏿🦲👩🦲👩🏻🦲👩🏼🦲👩🏽🦲👩🏾🦲👩🏿🦲👨🦳👨🏻🦳👨🏼🦳👨🏽🦳👨🏾🦳👨🏿🦳👩🦳👩🏻🦳👩🏼🦳👩🏽🦳👩🏾🦳👩🏿🦳🤵🤵🏻🤵🏼🤵🏽🤵🏾🤵🏿👰👰🏻👰🏼👰🏽👰🏾👰🏿🤰🤰🏻🤰🏼🤰🏽🤰🏾🤰🏿🤱🤱🏻🤱🏼🤱🏽🤱🏾🤱🏿👼👼🏻👼🏼👼🏽👼🏾👼🏿🎅🎅🏻🎅🏼🎅🏽🎅🏾🎅🏿🤶🤶🏻🤶🏼🤶🏽🤶🏾🤶🏿🦸🦸🏻🦸🏼🦸🏽🦸🏾🦸🏿🦸♀️🦸♀🦸🏻♀️🦸🏻♀🦸🏼♀️🦸🏼♀🦸🏽♀️🦸🏽♀🦸🏾♀️🦸🏾♀🦸🏿♀️🦸🏿♀🦸♂️🦸♂🦸🏻♂️🦸🏻♂🦸🏼♂️🦸🏼♂🦸🏽♂️🦸🏽♂🦸🏾♂️🦸🏾♂🦸🏿♂️🦸🏿♂🦹🦹🏻🦹🏼🦹🏽🦹🏾🦹🏿🦹♀️🦹♀🦹🏻♀️🦹🏻♀🦹🏼♀️🦹🏼♀🦹🏽♀️🦹🏽♀🦹🏾♀️🦹🏾♀🦹🏿♀️🦹🏿♀🦹♂️🦹♂🦹🏻♂️🦹🏻♂🦹🏼♂️🦹🏼♂🦹🏽♂️🦹🏽♂🦹🏾♂️🦹🏾♂🦹🏿♂️🦹🏿♂🧙🧙🏻🧙🏼🧙🏽🧙🏾🧙🏿🧙♀️🧙♀🧙🏻♀️🧙🏻♀🧙🏼♀️🧙🏼♀🧙🏽♀️🧙🏽♀🧙🏾♀️🧙🏾♀🧙🏿♀️🧙🏿♀🧙♂️🧙♂🧙🏻♂️🧙🏻♂🧙🏼♂️🧙🏼♂🧙🏽♂️🧙🏽♂🧙🏾♂️🧙🏾♂🧙🏿♂️🧙🏿♂🧚🧚🏻🧚🏼🧚🏽🧚🏾🧚🏿🧚♀️🧚♀🧚🏻♀️🧚🏻♀🧚🏼♀️🧚🏼♀🧚🏽♀️🧚🏽♀🧚🏾♀️🧚🏾♀🧚🏿♀️🧚🏿♀🧚♂️🧚♂🧚🏻♂️🧚🏻♂🧚🏼♂️🧚🏼♂🧚🏽♂️🧚🏽♂🧚🏾♂️🧚🏾♂🧚🏿♂️🧚🏿♂🧛🧛🏻🧛🏼🧛🏽🧛🏾🧛🏿🧛♀️🧛♀🧛🏻♀️🧛🏻♀🧛🏼♀️🧛🏼♀🧛🏽♀️🧛🏽♀🧛🏾♀️🧛🏾♀🧛🏿♀️🧛🏿♀🧛♂️🧛♂🧛🏻♂️🧛🏻♂🧛🏼♂️🧛🏼♂🧛🏽♂️🧛🏽♂🧛🏾♂️🧛🏾♂🧛🏿♂️🧛🏿♂🧜🧜🏻🧜🏼🧜🏽🧜🏾🧜🏿🧜♀️🧜♀🧜🏻♀️🧜🏻♀🧜🏼♀️🧜🏼♀🧜🏽♀️🧜🏽♀🧜🏾♀️🧜🏾♀🧜🏿♀️🧜🏿♀🧜♂️🧜♂🧜🏻♂️🧜🏻♂🧜🏼♂️🧜🏼♂🧜🏽♂️🧜🏽♂🧜🏾♂️🧜🏾♂🧜🏿♂️🧜🏿♂🧝🧝🏻🧝🏼🧝🏽🧝🏾🧝🏿🧝♀️🧝♀🧝🏻♀️🧝🏻♀🧝🏼♀️🧝🏼♀🧝🏽♀️🧝🏽♀🧝🏾♀️🧝🏾♀🧝🏿♀️🧝🏿♀🧝♂️🧝♂🧝🏻♂️🧝🏻♂🧝🏼♂️🧝🏼♂🧝🏽♂️🧝🏽♂🧝🏾♂️🧝🏾♂🧝🏿♂️🧝🏿♂🧞🧞♀️🧞♀🧞♂️🧞♂🧟🧟♀️🧟♀🧟♂️🧟♂🙍🙍🏻🙍🏼🙍🏽🙍🏾🙍🏿🙍♂️🙍♂🙍🏻♂️🙍🏻♂🙍🏼♂️🙍🏼♂🙍🏽♂️🙍🏽♂🙍🏾♂️🙍🏾♂🙍🏿♂️🙍🏿♂🙍♀️🙍♀🙍🏻♀️🙍🏻♀🙍🏼♀️🙍🏼♀🙍🏽♀️🙍🏽♀🙍🏾♀️🙍🏾♀🙍🏿♀️🙍🏿♀🙎🙎🏻🙎🏼🙎🏽🙎🏾🙎🏿🙎♂️🙎♂🙎🏻♂️🙎🏻♂🙎🏼♂️🙎🏼♂🙎🏽♂️🙎🏽♂🙎🏾♂️🙎🏾♂🙎🏿♂️🙎🏿♂🙎♀️🙎♀🙎🏻♀️🙎🏻♀🙎🏼♀️🙎🏼♀🙎🏽♀️🙎🏽♀🙎🏾♀️🙎🏾♀🙎🏿♀️🙎🏿♀🙅🙅🏻🙅🏼🙅🏽🙅🏾🙅🏿🙅♂️🙅♂🙅🏻♂️🙅🏻♂🙅🏼♂️🙅🏼♂🙅🏽♂️🙅🏽♂🙅🏾♂️🙅🏾♂🙅🏿♂️🙅🏿♂🙅♀️🙅♀🙅🏻♀️🙅🏻♀🙅🏼♀️🙅🏼♀🙅🏽♀️🙅🏽♀🙅🏾♀️🙅🏾♀🙅🏿♀️🙅🏿♀🙆🙆🏻🙆🏼🙆🏽🙆🏾🙆🏿🙆♂️🙆♂🙆🏻♂️🙆🏻♂🙆🏼♂️🙆🏼♂🙆🏽♂️🙆🏽♂🙆🏾♂️🙆🏾♂🙆🏿♂️🙆🏿♂🙆♀️🙆♀🙆🏻♀️🙆🏻♀🙆🏼♀️🙆🏼♀🙆🏽♀️🙆🏽♀🙆🏾♀️🙆🏾♀🙆🏿♀️🙆🏿♀💁💁🏻💁🏼💁🏽💁🏾💁🏿💁♂️💁♂💁🏻♂️💁🏻♂💁🏼♂️💁🏼♂💁🏽♂️💁🏽♂💁🏾♂️💁🏾♂💁🏿♂️💁🏿♂💁♀️💁♀💁🏻♀️💁🏻♀💁🏼♀️💁🏼♀💁🏽♀️💁🏽♀💁🏾♀️💁🏾♀💁🏿♀️💁🏿♀🙋🙋🏻🙋🏼🙋🏽🙋🏾🙋🏿🙋♂️🙋♂🙋🏻♂️🙋🏻♂🙋🏼♂️🙋🏼♂🙋🏽♂️🙋🏽♂🙋🏾♂️🙋🏾♂🙋🏿♂️🙋🏿♂🙋♀️🙋♀🙋🏻♀️🙋🏻♀🙋🏼♀️🙋🏼♀🙋🏽♀️🙋🏽♀🙋🏾♀️🙋🏾♀🙋🏿♀️🙋🏿♀🙇🙇🏻🙇🏼🙇🏽🙇🏾🙇🏿🙇♂️🙇♂🙇🏻♂️🙇🏻♂🙇🏼♂️🙇🏼♂🙇🏽♂️🙇🏽♂🙇🏾♂️🙇🏾♂🙇🏿♂️🙇🏿♂🙇♀️🙇♀🙇🏻♀️🙇🏻♀🙇🏼♀️🙇🏼♀🙇🏽♀️🙇🏽♀🙇🏾♀️🙇🏾♀🙇🏿♀️🙇🏿♀🤦🤦🏻🤦🏼🤦🏽🤦🏾🤦🏿🤦♂️🤦♂🤦🏻♂️🤦🏻♂🤦🏼♂️🤦🏼♂🤦🏽♂️🤦🏽♂🤦🏾♂️🤦🏾♂🤦🏿♂️🤦🏿♂🤦♀️🤦♀🤦🏻♀️🤦🏻♀🤦🏼♀️🤦🏼♀🤦🏽♀️🤦🏽♀🤦🏾♀️🤦🏾♀🤦🏿♀️🤦🏿♀🤷🤷🏻🤷🏼🤷🏽🤷🏾🤷🏿🤷♂️🤷♂🤷🏻♂️🤷🏻♂🤷🏼♂️🤷🏼♂🤷🏽♂️🤷🏽♂🤷🏾♂️🤷🏾♂🤷🏿♂️🤷🏿♂🤷♀️🤷♀🤷🏻♀️🤷🏻♀🤷🏼♀️🤷🏼♀🤷🏽♀️🤷🏽♀🤷🏾♀️🤷🏾♀🤷🏿♀️🤷🏿♀💆💆🏻💆🏼💆🏽💆🏾💆🏿💆♂️💆♂💆🏻♂️💆🏻♂💆🏼♂️💆🏼♂💆🏽♂️💆🏽♂💆🏾♂️💆🏾♂💆🏿♂️💆🏿♂💆♀️💆♀💆🏻♀️💆🏻♀💆🏼♀️💆🏼♀💆🏽♀️💆🏽♀💆🏾♀️💆🏾♀💆🏿♀️💆🏿♀💇💇🏻💇🏼💇🏽💇🏾💇🏿💇♂️💇♂💇🏻♂️💇🏻♂💇🏼♂️💇🏼♂💇🏽♂️💇🏽♂💇🏾♂️💇🏾♂💇🏿♂️💇🏿♂💇♀️💇♀💇🏻♀️💇🏻♀💇🏼♀️💇🏼♀💇🏽♀️💇🏽♀💇🏾♀️💇🏾♀💇🏿♀️💇🏿♀🚶🚶🏻🚶🏼🚶🏽🚶🏾🚶🏿🚶♂️🚶♂🚶🏻♂️🚶🏻♂🚶🏼♂️🚶🏼♂🚶🏽♂️🚶🏽♂🚶🏾♂️🚶🏾♂🚶🏿♂️🚶🏿♂🚶♀️🚶♀🚶🏻♀️🚶🏻♀🚶🏼♀️🚶🏼♀🚶🏽♀️🚶🏽♀🚶🏾♀️🚶🏾♀🚶🏿♀️🚶🏿♀🏃🏃🏻🏃🏼🏃🏽🏃🏾🏃🏿🏃♂️🏃♂🏃🏻♂️🏃🏻♂🏃🏼♂️🏃🏼♂🏃🏽♂️🏃🏽♂🏃🏾♂️🏃🏾♂🏃🏿♂️🏃🏿♂🏃♀️🏃♀🏃🏻♀️🏃🏻♀🏃🏼♀️🏃🏼♀🏃🏽♀️🏃🏽♀🏃🏾♀️🏃🏾♀🏃🏿♀️🏃🏿♀💃💃🏻💃🏼💃🏽💃🏾💃🏿🕺🕺🏻🕺🏼🕺🏽🕺🏾🕺🏿👯👯♂️👯♂👯♀️👯♀🧖🧖🏻🧖🏼🧖🏽🧖🏾🧖🏿🧖♀️🧖♀🧖🏻♀️🧖🏻♀🧖🏼♀️🧖🏼♀🧖🏽♀️🧖🏽♀🧖🏾♀️🧖🏾♀🧖🏿♀️🧖🏿♀🧖♂️🧖♂🧖🏻♂️🧖🏻♂🧖🏼♂️🧖🏼♂🧖🏽♂️🧖🏽♂🧖🏾♂️🧖🏾♂🧖🏿♂️🧖🏿♂🧗🧗🏻🧗🏼🧗🏽🧗🏾🧗🏿🧗♀️🧗♀🧗🏻♀️🧗🏻♀🧗🏼♀️🧗🏼♀🧗🏽♀️🧗🏽♀🧗🏾♀️🧗🏾♀🧗🏿♀️🧗🏿♀🧗♂️🧗♂🧗🏻♂️🧗🏻♂🧗🏼♂️🧗🏼♂🧗🏽♂️🧗🏽♂🧗🏾♂️🧗🏾♂🧗🏿♂️🧗🏿♂🧘🧘🏻🧘🏼🧘🏽🧘🏾🧘🏿🧘♀️🧘♀🧘🏻♀️🧘🏻♀🧘🏼♀️🧘🏼♀🧘🏽♀️🧘🏽♀🧘🏾♀️🧘🏾♀🧘🏿♀️🧘🏿♀🧘♂️🧘♂🧘🏻♂️🧘🏻♂🧘🏼♂️🧘🏼♂🧘🏽♂️🧘🏽♂🧘🏾♂️🧘🏾♂🧘🏿♂️🧘🏿♂🛀🛀🏻🛀🏼🛀🏽🛀🏾🛀🏿🛌🛌🏻🛌🏼🛌🏽🛌🏾🛌🏿🕴️🕴🕴🏻🕴🏼🕴🏽🕴🏾🕴🏿🗣️🗣👤👥🤺🏇🏇🏻🏇🏼🏇🏽🏇🏾🏇🏿⛷️⛷🏂🏂🏻🏂🏼🏂🏽🏂🏾🏂🏿🏌️🏌🏌🏻🏌🏼🏌🏽🏌🏾🏌🏿🏌️♂️🏌♂️🏌️♂🏌♂🏌🏻♂️🏌🏻♂🏌🏼♂️🏌🏼♂🏌🏽♂️🏌🏽♂🏌🏾♂️🏌🏾♂🏌🏿♂️🏌🏿♂🏌️♀️🏌♀️🏌️♀🏌♀🏌🏻♀️🏌🏻♀🏌🏼♀️🏌🏼♀🏌🏽♀️🏌🏽♀🏌🏾♀️🏌🏾♀🏌🏿♀️🏌🏿♀🏄🏄🏻🏄🏼🏄🏽🏄🏾🏄🏿🏄♂️🏄♂🏄🏻♂️🏄🏻♂🏄🏼♂️🏄🏼♂🏄🏽♂️🏄🏽♂🏄🏾♂️🏄🏾♂🏄🏿♂️🏄🏿♂🏄♀️🏄♀🏄🏻♀️🏄🏻♀🏄🏼♀️🏄🏼♀🏄🏽♀️🏄🏽♀🏄🏾♀️🏄🏾♀🏄🏿♀️🏄🏿♀🚣🚣🏻🚣🏼🚣🏽🚣🏾🚣🏿🚣♂️🚣♂🚣🏻♂️🚣🏻♂🚣🏼♂️🚣🏼♂🚣🏽♂️🚣🏽♂🚣🏾♂️🚣🏾♂🚣🏿♂️🚣🏿♂🚣♀️🚣♀🚣🏻♀️🚣🏻♀🚣🏼♀️🚣🏼♀🚣🏽♀️🚣🏽♀🚣🏾♀️🚣🏾♀🚣🏿♀️🚣🏿♀🏊🏊🏻🏊🏼🏊🏽🏊🏾🏊🏿🏊♂️🏊♂🏊🏻♂️🏊🏻♂🏊🏼♂️🏊🏼♂🏊🏽♂️🏊🏽♂🏊🏾♂️🏊🏾♂🏊🏿♂️🏊🏿♂🏊♀️🏊♀🏊🏻♀️🏊🏻♀🏊🏼♀️🏊🏼♀🏊🏽♀️🏊🏽♀🏊🏾♀️🏊🏾♀🏊🏿♀️🏊🏿♀⛹️⛹⛹🏻⛹🏼⛹🏽⛹🏾⛹🏿⛹️♂️⛹♂️⛹️♂⛹♂⛹🏻♂️⛹🏻♂⛹🏼♂️⛹🏼♂⛹🏽♂️⛹🏽♂⛹🏾♂️⛹🏾♂⛹🏿♂️⛹🏿♂⛹️♀️⛹♀️⛹️♀⛹♀⛹🏻♀️⛹🏻♀⛹🏼♀️⛹🏼♀⛹🏽♀️⛹🏽♀⛹🏾♀️⛹🏾♀⛹🏿♀️⛹🏿♀🏋️🏋🏋🏻🏋🏼🏋🏽🏋🏾🏋🏿🏋️♂️🏋♂️🏋️♂🏋♂🏋🏻♂️🏋🏻♂🏋🏼♂️🏋🏼♂🏋🏽♂️🏋🏽♂🏋🏾♂️🏋🏾♂🏋🏿♂️🏋🏿♂🏋️♀️🏋♀️🏋️♀🏋♀🏋🏻♀️🏋🏻♀🏋🏼♀️🏋🏼♀🏋🏽♀️🏋🏽♀🏋🏾♀️🏋🏾♀🏋🏿♀️🏋🏿♀🚴🚴🏻🚴🏼🚴🏽🚴🏾🚴🏿🚴♂️🚴♂🚴🏻♂️🚴🏻♂🚴🏼♂️🚴🏼♂🚴🏽♂️🚴🏽♂🚴🏾♂️🚴🏾♂🚴🏿♂️🚴🏿♂🚴♀️🚴♀🚴🏻♀️🚴🏻♀🚴🏼♀️🚴🏼♀🚴🏽♀️🚴🏽♀🚴🏾♀️🚴🏾♀🚴🏿♀️🚴🏿♀🚵🚵🏻🚵🏼🚵🏽🚵🏾🚵🏿🚵♂️🚵♂🚵🏻♂️🚵🏻♂🚵🏼♂️🚵🏼♂🚵🏽♂️🚵🏽♂🚵🏾♂️🚵🏾♂🚵🏿♂️🚵🏿♂🚵♀️🚵♀🚵🏻♀️🚵🏻♀🚵🏼♀️🚵🏼♀🚵🏽♀️🚵🏽♀🚵🏾♀️🚵🏾♀🚵🏿♀️🚵🏿♀🏎️🏎🏍️🏍🤸🤸🏻🤸🏼🤸🏽🤸🏾🤸🏿🤸♂️🤸♂🤸🏻♂️🤸🏻♂🤸🏼♂️🤸🏼♂🤸🏽♂️🤸🏽♂🤸🏾♂️🤸🏾♂🤸🏿♂️🤸🏿♂🤸♀️🤸♀🤸🏻♀️🤸🏻♀🤸🏼♀️🤸🏼♀🤸🏽♀️🤸🏽♀🤸🏾♀️🤸🏾♀🤸🏿♀️🤸🏿♀🤼🤼♂️🤼♂🤼♀️🤼♀🤽🤽🏻🤽🏼🤽🏽🤽🏾🤽🏿🤽♂️🤽♂🤽🏻♂️🤽🏻♂🤽🏼♂️🤽🏼♂🤽🏽♂️🤽🏽♂🤽🏾♂️🤽🏾♂🤽🏿♂️🤽🏿♂🤽♀️🤽♀🤽🏻♀️🤽🏻♀🤽🏼♀️🤽🏼♀🤽🏽♀️🤽🏽♀🤽🏾♀️🤽🏾♀🤽🏿♀️🤽🏿♀🤾🤾🏻🤾🏼🤾🏽🤾🏾🤾🏿🤾♂️🤾♂🤾🏻♂️🤾🏻♂🤾🏼♂️🤾🏼♂🤾🏽♂️🤾🏽♂🤾🏾♂️🤾🏾♂🤾🏿♂️🤾🏿♂🤾♀️🤾♀🤾🏻♀️🤾🏻♀🤾🏼♀️🤾🏼♀🤾🏽♀️🤾🏽♀🤾🏾♀️🤾🏾♀🤾🏿♀️🤾🏿♀🤹🤹🏻🤹🏼🤹🏽🤹🏾🤹🏿🤹♂️🤹♂🤹🏻♂️🤹🏻♂🤹🏼♂️🤹🏼♂🤹🏽♂️🤹🏽♂🤹🏾♂️🤹🏾♂🤹🏿♂️🤹🏿♂🤹♀️🤹♀🤹🏻♀️🤹🏻♀🤹🏼♀️🤹🏼♀🤹🏽♀️🤹🏽♀🤹🏾♀️🤹🏾♀🤹🏿♀️🤹🏿♀👫👬👭💏👩❤️💋👨👩❤💋👨👨❤️💋👨👨❤💋👨👩❤️💋👩👩❤💋👩💑👩❤️👨👩❤👨👨❤️👨👨❤👨👩❤️👩👩❤👩👪👨👩👦👨👩👧👨👩👧👦👨👩👦👦👨👩👧👧👨👨👦👨👨👧👨👨👧👦👨👨👦👦👨👨👧👧👩👩👦👩👩👧👩👩👧👦👩👩👦👦👩👩👧👧👨👦👨👦👦👨👧👨👧👦👨👧👧👩👦👩👦👦👩👧👩👧👦👩👧👧🤳🤳🏻🤳🏼🤳🏽🤳🏾🤳🏿💪💪🏻💪🏼💪🏽💪🏾💪🏿🦵🦵🏻🦵🏼🦵🏽🦵🏾🦵🏿🦶🦶🏻🦶🏼🦶🏽🦶🏾🦶🏿👈👈🏻👈🏼👈🏽👈🏾👈🏿👉👉🏻👉🏼👉🏽👉🏾👉🏿☝️☝☝🏻☝🏼☝🏽☝🏾☝🏿👆👆🏻👆🏼👆🏽👆🏾👆🏿🖕🖕🏻🖕🏼🖕🏽🖕🏾🖕🏿👇👇🏻👇🏼👇🏽👇🏾👇🏿✌️✌✌🏻✌🏼✌🏽✌🏾✌🏿🤞🤞🏻🤞🏼🤞🏽🤞🏾🤞🏿🖖🖖🏻🖖🏼🖖🏽🖖🏾🖖🏿🤘🤘🏻🤘🏼🤘🏽🤘🏾🤘🏿🤙🤙🏻🤙🏼🤙🏽🤙🏾🤙🏿🖐️🖐🖐🏻🖐🏼🖐🏽🖐🏾🖐🏿✋✋🏻✋🏼✋🏽✋🏾✋🏿👌👌🏻👌🏼👌🏽👌🏾👌🏿👍👍🏻👍🏼👍🏽👍🏾👍🏿👎👎🏻👎🏼👎🏽👎🏾👎🏿✊✊🏻✊🏼✊🏽✊🏾✊🏿👊👊🏻👊🏼👊🏽👊🏾👊🏿🤛🤛🏻🤛🏼🤛🏽🤛🏾🤛🏿🤜🤜🏻🤜🏼🤜🏽🤜🏾🤜🏿🤚🤚🏻🤚🏼🤚🏽🤚🏾🤚🏿👋👋🏻👋🏼👋🏽👋🏾👋🏿🤟🤟🏻🤟🏼🤟🏽🤟🏾🤟🏿✍️✍✍🏻✍🏼✍🏽✍🏾✍🏿👏👏🏻👏🏼👏🏽👏🏾👏🏿👐👐🏻👐🏼👐🏽👐🏾👐🏿🙌🙌🏻🙌🏼🙌🏽🙌🏾🙌🏿🤲🤲🏻🤲🏼🤲🏽🤲🏾🤲🏿🙏🙏🏻🙏🏼🙏🏽🙏🏾🙏🏿🤝💅💅🏻💅🏼💅🏽💅🏾💅🏿👂👂🏻👂🏼👂🏽👂🏾👂🏿👃👃🏻👃🏼👃🏽👃🏾👃🏿🦰🦱🦲🦳👣👀👁️👁👁️🗨️👁🗨️👁️🗨👁🗨🧠🦴🦷👅👄💋💘❤️❤💓💔💕💖💗💙💚💛🧡💜🖤💝💞💟❣️❣💌💤💢💣💥💦💨💫💬🗨️🗨🗯️🗯💭🕳️🕳👓🕶️🕶🥽🥼👔👕👖🧣🧤🧥🧦👗👘👙👚👛👜👝🛍️🛍🎒👞👟🥾🥿👠👡👢👑👒🎩🎓🧢⛑️⛑📿💄💍💎🐵🐒🦍🐶🐕🐩🐺🦊🦝🐱🐈🦁🐯🐅🐆🐴🐎🦄🦓🦌🐮🐂🐃🐄🐷🐖🐗🐽🐏🐑🐐🐪🐫🦙🦒🐘🦏🦛🐭🐁🐀🐹🐰🐇🐿️🐿🦔🦇🐻🐨🐼🦘🦡🐾🦃🐔🐓🐣🐤🐥🐦🐧🕊️🕊🦅🦆🦢🦉🦚🦜🐸🐊🐢🦎🐍🐲🐉🦕🦖🐳🐋🐬🐟🐠🐡🦈🐙🐚🦀🦞🦐🦑🐌🦋🐛🐜🐝🐞🦗🕷️🕷🕸️🕸🦂🦟🦠💐🌸💮🏵️🏵🌹🥀🌺🌻🌼🌷🌱🌲🌳🌴🌵🌾🌿☘️☘🍀🍁🍂🍃🍇🍈🍉🍊🍋🍌🍍🥭🍎🍏🍐🍑🍒🍓🥝🍅🥥🥑🍆🥔🥕🌽🌶️🌶🥒🥬🥦🍄🥜🌰🍞🥐🥖🥨🥯🥞🧀🍖🍗🥩🥓🍔🍟🍕🌭🥪🌮🌯🥙🥚🍳🥘🍲🥣🥗🍿🧂🥫🍱🍘🍙🍚🍛🍜🍝🍠🍢🍣🍤🍥🥮🍡🥟🥠🥡🍦🍧🍨🍩🍪🎂🍰🧁🥧🍫🍬🍭🍮🍯🍼🥛☕🍵🍶🍾🍷🍸🍹🍺🍻🥂🥃🥤🥢🍽️🍽🍴🥄🔪🏺🌍🌎🌏🌐🗺️🗺🗾🧭🏔️🏔⛰️⛰🌋🗻🏕️🏕🏖️🏖🏜️🏜🏝️🏝🏞️🏞🏟️🏟🏛️🏛🏗️🏗🧱🏘️🏘🏚️🏚🏠🏡🏢🏣🏤🏥🏦🏨🏩🏪🏫🏬🏭🏯🏰💒🗼🗽⛪🕌🕍⛩️⛩🕋⛲⛺🌁🌃🏙️🏙🌄🌅🌆🌇🌉♨️♨🌌🎠🎡🎢💈🎪🚂🚃🚄🚅🚆🚇🚈🚉🚊🚝🚞🚋🚌🚍🚎🚐🚑🚒🚓🚔🚕🚖🚗🚘🚙🚚🚛🚜🚲🛴🛹🛵🚏🛣️🛣🛤️🛤🛢️🛢⛽🚨🚥🚦🛑🚧⚓⛵🛶🚤🛳️🛳⛴️⛴🛥️🛥🚢✈️✈🛩️🛩🛫🛬💺🚁🚟🚠🚡🛰️🛰🚀🛸🛎️🛎🧳⌛⏳⌚⏰⏱️⏱⏲️⏲🕰️🕰🕛🕧🕐🕜🕑🕝🕒🕞🕓🕟🕔🕠🕕🕡🕖🕢🕗🕣🕘🕤🕙🕥🕚🕦🌑🌒🌓🌔🌕🌖🌗🌘🌙🌚🌛🌜🌡️🌡☀️☀🌝🌞⭐🌟🌠☁️☁⛅⛈️⛈🌤️🌤🌥️🌥🌦️🌦🌧️🌧🌨️🌨🌩️🌩🌪️🌪🌫️🌫🌬️🌬🌀🌈🌂☂️☂☔⛱️⛱⚡❄️❄☃️☃⛄☄️☄🔥💧🌊🎃🎄🎆🎇🧨✨🎈🎉🎊🎋🎍🎎🎏🎐🎑🧧🎀🎁🎗️🎗🎟️🎟🎫🎖️🎖🏆🏅🥇🥈🥉⚽⚾🥎🏀🏐🏈🏉🎾🥏🎳🏏🏑🏒🥍🏓🏸🥊🥋🥅⛳⛸️⛸🎣🎽🎿🛷🥌🎯🎱🔮🧿🎮🕹️🕹🎰🎲🧩🧸♠️♠♥️♥♦️♦♣️♣♟️♟🃏🀄🎴🎭🖼️🖼🎨🧵🧶🔇🔈🔉🔊📢📣📯🔔🔕🎼🎵🎶🎙️🎙🎚️🎚🎛️🎛🎤🎧📻🎷🎸🎹🎺🎻🥁📱📲☎️☎📞📟📠🔋🔌💻🖥️🖥🖨️🖨⌨️⌨🖱️🖱🖲️🖲💽💾💿📀🧮🎥🎞️🎞📽️📽🎬📺📷📸📹📼🔍🔎🕯️🕯💡🔦🏮📔📕📖📗📘📙📚📓📒📃📜📄📰🗞️🗞📑🔖🏷️🏷💰💴💵💶💷💸💳🧾💹💱💲✉️✉📧📨📩📤📥📦📫📪📬📭📮🗳️🗳✏️✏✒️✒🖋️🖋🖊️🖊🖌️🖌🖍️🖍📝💼📁📂🗂️🗂📅📆🗒️🗒🗓️🗓📇📈📉📊📋📌📍📎🖇️🖇📏📐✂️✂🗃️🗃🗄️🗄🗑️🗑🔒🔓🔏🔐🔑🗝️🗝🔨⛏️⛏⚒️⚒🛠️🛠🗡️🗡⚔️⚔🔫🏹🛡️🛡🔧🔩⚙️⚙🗜️🗜⚖️⚖🔗⛓️⛓🧰🧲⚗️⚗🧪🧫🧬🔬🔭📡💉💊🚪🛏️🛏🛋️🛋🚽🚿🛁🧴🧷🧹🧺🧻🧼🧽🧯🛒🚬⚰️⚰⚱️⚱🗿🏧🚮🚰♿🚹🚺🚻🚼🚾🛂🛃🛄🛅⚠️⚠🚸⛔🚫🚳🚭🚯🚱🚷📵🔞☢️☢☣️☣⬆️⬆↗️↗➡️➡↘️↘⬇️⬇↙️↙⬅️⬅↖️↖↕️↕↔️↔↩️↩↪️↪⤴️⤴⤵️⤵🔃🔄🔙🔚🔛🔜🔝🛐⚛️⚛🕉️🕉✡️✡☸️☸☯️☯✝️✝☦️☦☪️☪☮️☮🕎🔯♈♉♊♋♌♍♎♏♐♑♒♓⛎🔀🔁🔂▶️▶⏩⏭️⏭⏯️⏯◀️◀⏪⏮️⏮🔼⏫🔽⏬⏸️⏸⏹️⏹⏺️⏺⏏️⏏🎦🔅🔆📶📳📴♀️♀♂️♂⚕️⚕♾️♾♻️♻⚜️⚜🔱📛🔰⭕✅☑️☑✔️✔✖️✖❌❎➕➖➗➰➿〽️〽✳️✳✴️✴❇️❇‼️‼⁉️⁉❓❔❕❗〰️〰©️©®️®™️™#️⃣#⃣*️⃣*⃣0️⃣0⃣1️⃣1⃣2️⃣2⃣3️⃣3⃣4️⃣4⃣5️⃣5⃣6️⃣6⃣7️⃣7⃣8️⃣8⃣9️⃣9⃣🔟💯🔠🔡🔢🔣🔤🅰️🅰🆎🅱️🅱🆑🆒🆓ℹ️ℹ🆔Ⓜ️Ⓜ🆕🆖🅾️🅾🆗🅿️🅿🆘🆙🆚🈁🈂️🈂🈷️🈷🈶🈯🉐🈹🈚🈲🉑🈸🈴🈳㊗️㊗㊙️㊙🈺🈵▪️▪▫️▫◻️◻◼️◼◽◾⬛⬜🔶🔷🔸🔹🔺🔻💠🔘🔲🔳⚪⚫🔴🔵🏁🚩🎌🏴🏳️🏳🏳️🌈🏳🌈🏴☠️🏴☠🇦🇨🇦🇩🇦🇪🇦🇫🇦🇬🇦🇮🇦🇱🇦🇲🇦🇴🇦🇶🇦🇷🇦🇸🇦🇹🇦🇺🇦🇼🇦🇽🇦🇿🇧🇦🇧🇧🇧🇩🇧🇪🇧🇫🇧🇬🇧🇭🇧🇮🇧🇯🇧🇱🇧🇲🇧🇳🇧🇴🇧🇶🇧🇷🇧🇸🇧🇹🇧🇻🇧🇼🇧🇾🇧🇿🇨🇦🇨🇨🇨🇩🇨🇫🇨🇬🇨🇭🇨🇮🇨🇰🇨🇱🇨🇲🇨🇳🇨🇴🇨🇵🇨🇷🇨🇺🇨🇻🇨🇼🇨🇽🇨🇾🇨🇿🇩🇪🇩🇬🇩🇯🇩🇰🇩🇲🇩🇴🇩🇿🇪🇦🇪🇨🇪🇪🇪🇬🇪🇭🇪🇷🇪🇸🇪🇹🇪🇺🇫🇮🇫🇯🇫🇰🇫🇲🇫🇴🇫🇷🇬🇦🇬🇧🇬🇩🇬🇪🇬🇫🇬🇬🇬🇭🇬🇮🇬🇱🇬🇲🇬🇳🇬🇵🇬🇶🇬🇷🇬🇸🇬🇹🇬🇺🇬🇼🇬🇾🇭🇰🇭🇲🇭🇳🇭🇷🇭🇹🇭🇺🇮🇨🇮🇩🇮🇪🇮🇱🇮🇲🇮🇳🇮🇴🇮🇶🇮🇷🇮🇸🇮🇹🇯🇪🇯🇲🇯🇴🇯🇵🇰🇪🇰🇬🇰🇭🇰🇮🇰🇲🇰🇳🇰🇵🇰🇷🇰🇼🇰🇾🇰🇿🇱🇦🇱🇧🇱🇨🇱🇮🇱🇰🇱🇷🇱🇸🇱🇹🇱🇺🇱🇻🇱🇾🇲🇦🇲🇨🇲🇩🇲🇪🇲🇫🇲🇬🇲🇭🇲🇰🇲🇱🇲🇲🇲🇳🇲🇴🇲🇵🇲🇶🇲🇷🇲🇸🇲🇹🇲🇺🇲🇻🇲🇼🇲🇽🇲🇾🇲🇿🇳🇦🇳🇨🇳🇪🇳🇫🇳🇬🇳🇮🇳🇱🇳🇴🇳🇵🇳🇷🇳🇺🇳🇿🇴🇲🇵🇦🇵🇪🇵🇫🇵🇬🇵🇭🇵🇰🇵🇱🇵🇲🇵🇳🇵🇷🇵🇸🇵🇹🇵🇼🇵🇾🇶🇦🇷🇪🇷🇴🇷🇸🇷🇺🇷🇼🇸🇦🇸🇧🇸🇨🇸🇩🇸🇪🇸🇬🇸🇭🇸🇮🇸🇯🇸🇰🇸🇱🇸🇲🇸🇳🇸🇴🇸🇷🇸🇸🇸🇹🇸🇻🇸🇽🇸🇾🇸🇿🇹🇦🇹🇨🇹🇩🇹🇫🇹🇬🇹🇭🇹🇯🇹🇰🇹🇱🇹🇲🇹🇳🇹🇴🇹🇷🇹🇹🇹🇻🇹🇼🇹🇿🇺🇦🇺🇬🇺🇲🇺🇳🇺🇸🇺🇾🇺🇿🇻🇦🇻🇨🇻🇪🇻🇬🇻🇮🇻🇳🇻🇺🇼🇫🇼🇸🇽🇰🇾🇪🇾🇹🇿🇦🇿🇲🇿🇼🏴🏴🏴" - ); - expect(() => emoji.parse(":-)")).toThrow(); - expect(() => emoji.parse("😀 is an emoji")).toThrow(); - expect(() => emoji.parse("😀stuff")).toThrow(); - expect(() => emoji.parse("stuff😀")).toThrow(); -}); - -test("uuid", () => { - const uuid = z.string().uuid("custom error"); - uuid.parse("9491d710-3185-4e06-bea0-6a2f275345e0"); - uuid.parse("d89e7b01-7598-ed11-9d7a-0022489382fd"); // new sequential id - uuid.parse("00000000-0000-0000-0000-000000000000"); - uuid.parse("b3ce60f8-e8b9-40f5-1150-172ede56ff74"); // Variant 0 - RFC 4122: Reserved, NCS backward compatibility - uuid.parse("92e76bf9-28b3-4730-cd7f-cb6bc51f8c09"); // Variant 2 - RFC 4122: Reserved, Microsoft Corporation backward compatibility - const result = uuid.safeParse("9491d710-3185-4e06-bea0-6a2f275345e0X"); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].message).toEqual("custom error"); - } -}); - -test("bad uuid", () => { - const uuid = z.string().uuid("custom error"); - uuid.parse("9491d710-3185-4e06-bea0-6a2f275345e0"); - const result = uuid.safeParse("invalid uuid"); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].message).toEqual("custom error"); - } -}); - -test("cuid", () => { - const cuid = z.string().cuid(); - cuid.parse("ckopqwooh000001la8mbi2im9"); - const result = cuid.safeParse("cifjhdsfhsd-invalid-cuid"); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].message).toEqual("Invalid cuid"); - } -}); - -test("cuid2", () => { - const cuid2 = z.string().cuid2(); - const validStrings = [ - "a", // short string - "tz4a98xxat96iws9zmbrgj3a", // normal string - "kf5vz6ssxe4zjcb409rjgo747tc5qjazgptvotk6", // longer than require("@paralleldrive/cuid2").bigLength - ]; - validStrings.forEach((s) => cuid2.parse(s)); - const invalidStrings = [ - "", // empty string - "1z4a98xxat96iws9zmbrgj3a", // starts with a number - "tz4a98xxat96iws9zMbrgj3a", // include uppercase - "tz4a98xxat96iws-zmbrgj3a", // involve symbols - ]; - const results = invalidStrings.map((s) => cuid2.safeParse(s)); - expect(results.every((r) => !r.success)).toEqual(true); - if (!results[0].success) { - expect(results[0].error.issues[0].message).toEqual("Invalid cuid2"); - } -}); - -test("ulid", () => { - const ulid = z.string().ulid(); - ulid.parse("01ARZ3NDEKTSV4RRFFQ69G5FAV"); - const result = ulid.safeParse("invalidulid"); - expect(result.success).toEqual(false); - const tooLong = "01ARZ3NDEKTSV4RRFFQ69G5FAVA"; - expect(ulid.safeParse(tooLong).success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].message).toEqual("Invalid ulid"); - } -}); - -test("regex", () => { - z.string() - .regex(/^moo+$/) - .parse("mooooo"); - expect(() => z.string().uuid().parse("purr")).toThrow(); -}); - -test("regexp error message", () => { - const result = z - .string() - .regex(/^moo+$/) - .safeParse("boooo"); - if (!result.success) { - expect(result.error.issues[0].message).toEqual("Invalid"); - } else { - throw new Error("validation should have failed"); - } - - expect(() => z.string().uuid().parse("purr")).toThrow(); -}); - -test("regex lastIndex reset", () => { - const schema = z.string().regex(/^\d+$/g); - expect(schema.safeParse("123").success).toEqual(true); - expect(schema.safeParse("123").success).toEqual(true); - expect(schema.safeParse("123").success).toEqual(true); - expect(schema.safeParse("123").success).toEqual(true); - expect(schema.safeParse("123").success).toEqual(true); -}); - -test("checks getters", () => { - expect(z.string().email().isEmail).toEqual(true); - expect(z.string().email().isURL).toEqual(false); - expect(z.string().email().isCUID).toEqual(false); - expect(z.string().email().isCUID2).toEqual(false); - expect(z.string().email().isUUID).toEqual(false); - expect(z.string().email().isIP).toEqual(false); - expect(z.string().email().isULID).toEqual(false); - - expect(z.string().url().isEmail).toEqual(false); - expect(z.string().url().isURL).toEqual(true); - expect(z.string().url().isCUID).toEqual(false); - expect(z.string().url().isCUID2).toEqual(false); - expect(z.string().url().isUUID).toEqual(false); - expect(z.string().url().isIP).toEqual(false); - expect(z.string().url().isULID).toEqual(false); - - expect(z.string().cuid().isEmail).toEqual(false); - expect(z.string().cuid().isURL).toEqual(false); - expect(z.string().cuid().isCUID).toEqual(true); - expect(z.string().cuid().isCUID2).toEqual(false); - expect(z.string().cuid().isUUID).toEqual(false); - expect(z.string().cuid().isIP).toEqual(false); - expect(z.string().cuid().isULID).toEqual(false); - - expect(z.string().cuid2().isEmail).toEqual(false); - expect(z.string().cuid2().isURL).toEqual(false); - expect(z.string().cuid2().isCUID).toEqual(false); - expect(z.string().cuid2().isCUID2).toEqual(true); - expect(z.string().cuid2().isUUID).toEqual(false); - expect(z.string().cuid2().isIP).toEqual(false); - expect(z.string().cuid2().isULID).toEqual(false); - - expect(z.string().uuid().isEmail).toEqual(false); - expect(z.string().uuid().isURL).toEqual(false); - expect(z.string().uuid().isCUID).toEqual(false); - expect(z.string().uuid().isCUID2).toEqual(false); - expect(z.string().uuid().isUUID).toEqual(true); - expect(z.string().uuid().isIP).toEqual(false); - expect(z.string().uuid().isULID).toEqual(false); - - expect(z.string().ip().isEmail).toEqual(false); - expect(z.string().ip().isURL).toEqual(false); - expect(z.string().ip().isCUID).toEqual(false); - expect(z.string().ip().isCUID2).toEqual(false); - expect(z.string().ip().isUUID).toEqual(false); - expect(z.string().ip().isIP).toEqual(true); - expect(z.string().ip().isULID).toEqual(false); - - expect(z.string().ulid().isEmail).toEqual(false); - expect(z.string().ulid().isURL).toEqual(false); - expect(z.string().ulid().isCUID).toEqual(false); - expect(z.string().ulid().isCUID2).toEqual(false); - expect(z.string().ulid().isUUID).toEqual(false); - expect(z.string().ulid().isIP).toEqual(false); - expect(z.string().ulid().isULID).toEqual(true); -}); - -test("min max getters", () => { - expect(z.string().min(5).minLength).toEqual(5); - expect(z.string().min(5).min(10).minLength).toEqual(10); - expect(z.string().minLength).toEqual(null); - - expect(z.string().max(5).maxLength).toEqual(5); - expect(z.string().max(5).max(1).maxLength).toEqual(1); - expect(z.string().maxLength).toEqual(null); -}); - -test("trim", () => { - expect(z.string().trim().min(2).parse(" 12 ")).toEqual("12"); - - // ordering of methods is respected - expect(z.string().min(2).trim().parse(" 1 ")).toEqual("1"); - expect(() => z.string().trim().min(2).parse(" 1 ")).toThrow(); -}); - -test("lowerCase", () => { - expect(z.string().toLowerCase().parse("ASDF")).toEqual("asdf"); - expect(z.string().toUpperCase().parse("asdf")).toEqual("ASDF"); -}); - -test("datetime", () => { - const a = z.string().datetime({}); - expect(a.isDatetime).toEqual(true); - - const b = z.string().datetime({ offset: true }); - expect(b.isDatetime).toEqual(true); - - const c = z.string().datetime({ precision: 3 }); - expect(c.isDatetime).toEqual(true); - - const d = z.string().datetime({ offset: true, precision: 0 }); - expect(d.isDatetime).toEqual(true); - - const { isDatetime } = z.string().datetime(); - expect(isDatetime).toEqual(true); -}); - -test("datetime parsing", () => { - const datetime = z.string().datetime(); - datetime.parse("1970-01-01T00:00:00.000Z"); - datetime.parse("2022-10-13T09:52:31.816Z"); - datetime.parse("2022-10-13T09:52:31.8162314Z"); - datetime.parse("1970-01-01T00:00:00Z"); - datetime.parse("2022-10-13T09:52:31Z"); - expect(() => datetime.parse("")).toThrow(); - expect(() => datetime.parse("foo")).toThrow(); - expect(() => datetime.parse("2020-10-14")).toThrow(); - expect(() => datetime.parse("T18:45:12.123")).toThrow(); - expect(() => datetime.parse("2020-10-14T17:42:29+00:00")).toThrow(); - - const datetimeNoMs = z.string().datetime({ precision: 0 }); - datetimeNoMs.parse("1970-01-01T00:00:00Z"); - datetimeNoMs.parse("2022-10-13T09:52:31Z"); - expect(() => datetimeNoMs.parse("tuna")).toThrow(); - expect(() => datetimeNoMs.parse("1970-01-01T00:00:00.000Z")).toThrow(); - expect(() => datetimeNoMs.parse("1970-01-01T00:00:00.Z")).toThrow(); - expect(() => datetimeNoMs.parse("2022-10-13T09:52:31.816Z")).toThrow(); - - const datetime3Ms = z.string().datetime({ precision: 3 }); - datetime3Ms.parse("1970-01-01T00:00:00.000Z"); - datetime3Ms.parse("2022-10-13T09:52:31.123Z"); - expect(() => datetime3Ms.parse("tuna")).toThrow(); - expect(() => datetime3Ms.parse("1970-01-01T00:00:00.1Z")).toThrow(); - expect(() => datetime3Ms.parse("1970-01-01T00:00:00.12Z")).toThrow(); - expect(() => datetime3Ms.parse("2022-10-13T09:52:31Z")).toThrow(); - - const datetimeOffset = z.string().datetime({ offset: true }); - datetimeOffset.parse("1970-01-01T00:00:00.000Z"); - datetimeOffset.parse("2022-10-13T09:52:31.816234134Z"); - datetimeOffset.parse("1970-01-01T00:00:00Z"); - datetimeOffset.parse("2022-10-13T09:52:31.4Z"); - datetimeOffset.parse("2020-10-14T17:42:29+00:00"); - datetimeOffset.parse("2020-10-14T17:42:29+03:15"); - datetimeOffset.parse("2020-10-14T17:42:29+0315"); - datetimeOffset.parse("2020-10-14T17:42:29+03"); - expect(() => datetimeOffset.parse("tuna")).toThrow(); - expect(() => datetimeOffset.parse("2022-10-13T09:52:31.Z")).toThrow(); - - const datetimeOffsetNoMs = z - .string() - .datetime({ offset: true, precision: 0 }); - datetimeOffsetNoMs.parse("1970-01-01T00:00:00Z"); - datetimeOffsetNoMs.parse("2022-10-13T09:52:31Z"); - datetimeOffsetNoMs.parse("2020-10-14T17:42:29+00:00"); - datetimeOffsetNoMs.parse("2020-10-14T17:42:29+0000"); - datetimeOffsetNoMs.parse("2020-10-14T17:42:29+00"); - expect(() => datetimeOffsetNoMs.parse("tuna")).toThrow(); - expect(() => datetimeOffsetNoMs.parse("1970-01-01T00:00:00.000Z")).toThrow(); - expect(() => datetimeOffsetNoMs.parse("1970-01-01T00:00:00.Z")).toThrow(); - expect(() => datetimeOffsetNoMs.parse("2022-10-13T09:52:31.816Z")).toThrow(); - expect(() => - datetimeOffsetNoMs.parse("2020-10-14T17:42:29.124+00:00") - ).toThrow(); - - const datetimeOffset4Ms = z.string().datetime({ offset: true, precision: 4 }); - datetimeOffset4Ms.parse("1970-01-01T00:00:00.1234Z"); - datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+00:00"); - datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+0000"); - datetimeOffset4Ms.parse("2020-10-14T17:42:29.1234+00"); - expect(() => datetimeOffset4Ms.parse("tuna")).toThrow(); - expect(() => datetimeOffset4Ms.parse("1970-01-01T00:00:00.123Z")).toThrow(); - expect(() => - datetimeOffset4Ms.parse("2020-10-14T17:42:29.124+00:00") - ).toThrow(); -}); - -test("IP validation", () => { - const ip = z.string().ip(); - expect(ip.safeParse("122.122.122.122").success).toBe(true); - - const ipv4 = z.string().ip({ version: "v4" }); - expect(() => ipv4.parse("6097:adfa:6f0b:220d:db08:5021:6191:7990")).toThrow(); - - const ipv6 = z.string().ip({ version: "v6" }); - expect(() => ipv6.parse("254.164.77.1")).toThrow(); - - const validIPs = [ - "1e5e:e6c8:daac:514b:114b:e360:d8c0:682c", - "9d4:c956:420f:5788:4339:9b3b:2418:75c3", - "a6ea::2454:a5ce:94.105.123.75", - "474f:4c83::4e40:a47:ff95:0cda", - "d329:0:25b4:db47:a9d1:0:4926:0000", - "e48:10fb:1499:3e28:e4b6:dea5:4692:912c", - "114.71.82.94", - "0.0.0.0", - "37.85.236.115", - ]; - - const invalidIPs = [ - "d329:1be4:25b4:db47:a9d1:dc71:4926:992c:14af", - "d5e7:7214:2b78::3906:85e6:53cc:709:32ba", - "8f69::c757:395e:976e::3441", - "54cb::473f:d516:0.255.256.22", - "54cb::473f:d516:192.168.1", - "256.0.4.4", - "-1.0.555.4", - "0.0.0.0.0", - "1.1.1", - ]; - // no parameters check IPv4 or IPv6 - const ipSchema = z.string().ip(); - expect(validIPs.every((ip) => ipSchema.safeParse(ip).success)).toBe(true); - expect( - invalidIPs.every((ip) => ipSchema.safeParse(ip).success === false) - ).toBe(true); -}); diff --git a/deno/lib/__tests__/template-literal.test.ts b/deno/lib/__tests__/template-literal.test.ts deleted file mode 100644 index a0932130a..000000000 --- a/deno/lib/__tests__/template-literal.test.ts +++ /dev/null @@ -1,699 +0,0 @@ -// @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"; - -const empty = z.templateLiteral(); -const hello = z.templateLiteral().literal("hello"); -const world = z.templateLiteral().interpolated(z.literal("world")); -const one = z.templateLiteral().literal(1); -const two = z.templateLiteral().interpolated(z.literal(2)); -const truee = z.templateLiteral().literal(true); -const anotherTrue = z.templateLiteral().interpolated(z.literal(true)); -const falsee = z.templateLiteral().literal(false); -const anotherFalse = z.templateLiteral().interpolated(z.literal(false)); -const nulll = z.templateLiteral().literal(null); -const anotherNull = z.templateLiteral().interpolated(z.null()); -const undefinedd = z.templateLiteral().literal(undefined); -const anotherUndefined = z.templateLiteral().interpolated(z.undefined()); -const anyString = z.templateLiteral().interpolated(z.string()); -const anyNumber = z.templateLiteral().interpolated(z.number()); -const anyFiniteNumber = z.templateLiteral().interpolated(z.number().finite()); -const anyInt = z.templateLiteral().interpolated(z.number().int()); -const anyNegativeNumber = z - .templateLiteral() - .interpolated(z.number().negative()); -const anyPositiveNumber = z - .templateLiteral() - .interpolated(z.number().positive()); -const zeroButInADumbWay = z - .templateLiteral() - .interpolated(z.number().nonnegative().nonpositive()); -const finiteButInADumbWay = z - .templateLiteral() - .interpolated(z.number().min(5).max(10)); -const bool = z.templateLiteral().interpolated(z.boolean()); -const bigone = z.templateLiteral().interpolated(z.literal(BigInt(1))); -const anyBigint = z.templateLiteral().interpolated(z.bigint()); -const nullableYo = z - .templateLiteral() - .interpolated(z.nullable(z.literal("yo"))); -const nullableString = z.templateLiteral().interpolated(z.nullable(z.string())); -const optionalYeah = z - .templateLiteral() - .interpolated(z.literal("yeah").optional()); -const optionalString = z.templateLiteral().interpolated(z.string().optional()); -const optionalNumber = z.templateLiteral().interpolated(z.number().optional()); -const nullishBruh = z - .templateLiteral() - .interpolated(z.literal("bruh").nullish()); -const nullishString = z.templateLiteral().interpolated(z.string().nullish()); -const cuid = z.templateLiteral().interpolated(z.string().cuid()); -const cuidZZZ = z - .templateLiteral() - .interpolated(z.string().cuid()) - .literal("ZZZ"); -const cuid2 = z.templateLiteral().interpolated(z.string().cuid2()); -const datetime = z.templateLiteral().interpolated(z.string().datetime()); -const email = z.templateLiteral().interpolated(z.string().email()); -const ip = z.templateLiteral().interpolated(z.string().ip()); -const ipv4 = z.templateLiteral().interpolated(z.string().ip({ version: "v4" })); -const ipv6 = z.templateLiteral().interpolated(z.string().ip({ version: "v6" })); -const ulid = z.templateLiteral().interpolated(z.string().ulid()); -const uuid = z.templateLiteral().interpolated(z.string().uuid()); -const stringAToZ = z - .templateLiteral() - .interpolated(z.string().regex(/^[a-z]+$/)); -const stringStartsWith = z - .templateLiteral() - .interpolated(z.string().startsWith("hello")); -const stringEndsWith = z - .templateLiteral() - .interpolated(z.string().endsWith("world")); -const stringMax5 = z.templateLiteral().interpolated(z.string().max(5)); -const stringMin5 = z.templateLiteral().interpolated(z.string().min(5)); -const stringLen5 = z.templateLiteral().interpolated(z.string().length(5)); -const stringMin5Max10 = z - .templateLiteral() - .interpolated(z.string().min(5).max(10)); -const stringStartsWithMax5 = z - .templateLiteral() - .interpolated(z.string().startsWith("hello").max(5)); -const brandedString = z - .templateLiteral() - .interpolated(z.string().min(1).brand("myBrand")); -const anything = z.templateLiteral().interpolated(z.any()); - -const url = z - .templateLiteral() - .literal("https://") - .interpolated(z.string().regex(/\w+/)) - .literal(".") - .interpolated(z.enum(["com", "net"])); - -const measurement = z.coerce - .templateLiteral() - .interpolated(z.number().finite()) - .interpolated( - z.enum(["px", "em", "rem", "vh", "vw", "vmin", "vmax"]).optional() - ); - -const connectionString = z - .templateLiteral() - .literal("mongodb://") - .interpolated( - z - .templateLiteral() - .interpolated(z.string().regex(/\w+/).describe("username")) - .literal(":") - .interpolated(z.string().regex(/\w+/).describe("password")) - .literal("@") - .optional() - ) - .interpolated(z.string().regex(/\w+/).describe("host")) - .literal(":") - .interpolated(z.number().finite().int().positive().describe("port")) - .interpolated( - z - .templateLiteral() - .literal("/") - .interpolated( - z.string().regex(/\w+/).optional().describe("defaultauthdb") - ) - .interpolated( - z - .templateLiteral() - .literal("?") - .interpolated(z.string().regex(/^\w+=\w+(&\w+=\w+)*$/)) - .optional() - .describe("options") - ) - .optional() - ); - -test("template literal type inference", () => { - util.assertEqual<z.infer<typeof empty>, ``>(true); - util.assertEqual<z.infer<typeof hello>, `hello`>(true); - util.assertEqual<z.infer<typeof world>, `world`>(true); - util.assertEqual<z.infer<typeof one>, `1`>(true); - util.assertEqual<z.infer<typeof two>, `2`>(true); - util.assertEqual<z.infer<typeof truee>, `true`>(true); - util.assertEqual<z.infer<typeof anotherTrue>, `true`>(true); - util.assertEqual<z.infer<typeof falsee>, `false`>(true); - util.assertEqual<z.infer<typeof anotherFalse>, `false`>(true); - util.assertEqual<z.infer<typeof nulll>, `null`>(true); - util.assertEqual<z.infer<typeof anotherNull>, `null`>(true); - util.assertEqual<z.infer<typeof undefinedd>, `undefined`>(true); - util.assertEqual<z.infer<typeof anotherUndefined>, `undefined`>(true); - util.assertEqual<z.infer<typeof anyString>, string>(true); - util.assertEqual<z.infer<typeof anyNumber>, `${number}`>(true); - util.assertEqual<z.infer<typeof anyFiniteNumber>, `${number}`>(true); - util.assertEqual<z.infer<typeof anyInt>, `${number}`>(true); - util.assertEqual<z.infer<typeof anyNegativeNumber>, `${number}`>(true); - util.assertEqual<z.infer<typeof anyPositiveNumber>, `${number}`>(true); - util.assertEqual<z.infer<typeof zeroButInADumbWay>, `${number}`>(true); - util.assertEqual<z.infer<typeof finiteButInADumbWay>, `${number}`>(true); - util.assertEqual<z.infer<typeof bool>, `true` | `false`>(true); - util.assertEqual<z.infer<typeof bigone>, `${bigint}`>(true); - util.assertEqual<z.infer<typeof anyBigint>, `${bigint}`>(true); - util.assertEqual<z.infer<typeof nullableYo>, `yo` | `null`>(true); - util.assertEqual<z.infer<typeof nullableString>, string>(true); - util.assertEqual<z.infer<typeof optionalYeah>, `yeah` | ``>(true); - util.assertEqual<z.infer<typeof optionalString>, string>(true); - util.assertEqual<z.infer<typeof optionalNumber>, `${number}` | ``>(true); - util.assertEqual<z.infer<typeof nullishBruh>, `bruh` | `null` | ``>(true); - util.assertEqual<z.infer<typeof nullishString>, string>(true); - util.assertEqual<z.infer<typeof cuid>, string>(true); - util.assertEqual<z.infer<typeof cuidZZZ>, `${string}ZZZ`>(true); - util.assertEqual<z.infer<typeof cuid2>, string>(true); - util.assertEqual<z.infer<typeof datetime>, string>(true); - util.assertEqual<z.infer<typeof email>, string>(true); - util.assertEqual<z.infer<typeof ip>, string>(true); - util.assertEqual<z.infer<typeof ipv4>, string>(true); - util.assertEqual<z.infer<typeof ipv6>, string>(true); - util.assertEqual<z.infer<typeof ulid>, string>(true); - util.assertEqual<z.infer<typeof uuid>, string>(true); - util.assertEqual<z.infer<typeof stringAToZ>, string>(true); - util.assertEqual<z.infer<typeof stringStartsWith>, string>(true); - util.assertEqual<z.infer<typeof stringEndsWith>, string>(true); - util.assertEqual<z.infer<typeof stringMax5>, string>(true); - util.assertEqual<z.infer<typeof stringMin5>, string>(true); - util.assertEqual<z.infer<typeof stringLen5>, string>(true); - util.assertEqual<z.infer<typeof stringMin5Max10>, string>(true); - util.assertEqual<z.infer<typeof stringStartsWithMax5>, string>(true); - util.assertEqual<z.infer<typeof brandedString>, string>(true); - util.assertEqual<z.infer<typeof anything>, `${any}`>(true); - - util.assertEqual< - z.infer<typeof url>, - `https://${string}.com` | `https://${string}.net` - >(true); - - util.assertEqual< - z.infer<typeof measurement>, - | `${number}` - | `${number}px` - | `${number}em` - | `${number}rem` - | `${number}vh` - | `${number}vw` - | `${number}vmin` - | `${number}vmax` - >(true); - - util.assertEqual< - z.infer<typeof connectionString>, - | `mongodb://${string}:${number}` - | `mongodb://${string}:${number}/${string}` - | `mongodb://${string}:${number}/${string}?${string}` - | `mongodb://${string}:${string}@${string}:${number}` - | `mongodb://${string}:${string}@${string}:${number}/${string}` - | `mongodb://${string}:${string}@${string}:${number}/${string}?${string}` - >(true); -}); - -test("template literal unsupported args", () => { - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.object({})) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.array(z.object({}))) - ).toThrow(); - expect(() => - z.templateLiteral().interpolated( - // @ts-expect-error - z.union([z.object({}), z.string()]) - ) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.never()) - ).toThrow(); - // @ts-expect-error - expect(() => z.templateLiteral().interpolated(z.date())).toThrow(); - expect(() => - z - .templateLiteral() - // @ts-expect-error - .interpolated(z.custom<object>((data) => true)) - ).toThrow(); - expect(() => - z.templateLiteral().interpolated( - // @ts-expect-error - z.discriminatedUnion("discriminator", [z.object({}), z.object({})]) - ) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.function()) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.instanceof(class MyClass {})) - ).toThrow(); - expect(() => - z.templateLiteral().interpolated( - // @ts-expect-error - z.intersection(z.object({}), z.object({})) - ) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.map(z.string(), z.string())) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.nullable(z.object({}))) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.optional(z.object({}))) - ).toThrow(); - expect(() => - z.templateLiteral().interpolated( - // @ts-expect-error - z.preprocess(() => true, z.boolean()) - ) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.promise()) - ).toThrow(); - // @ts-expect-error - expect(() => z.templateLiteral().interpolated(z.nan())).toThrow(); - expect(() => - z.templateLiteral().interpolated( - // @ts-expect-error - z.pipeline(z.string(), z.string()) - ) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.record(z.unknown())) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.set(z.string())) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.symbol()) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.tuple([z.string()])) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.unknown()) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.void()) - ).toThrow(); - expect(() => - // @ts-expect-error - z.templateLiteral().interpolated(z.lazy(() => z.string())) - ).toThrow(); - expect(() => - z.templateLiteral().interpolated( - // @ts-expect-error - z.object({}).brand("brand") - ) - ).toThrow(); - expect(() => - z.templateLiteral().interpolated(z.number().multipleOf(2)) - ).toThrow(); - expect(() => z.templateLiteral().interpolated(z.string().emoji())).toThrow(); - expect(() => z.templateLiteral().interpolated(z.string().url())).toThrow(); - expect(() => z.templateLiteral().interpolated(z.string().trim())).toThrow(); - expect(() => - z.templateLiteral().interpolated(z.string().includes("train")) - ).toThrow(); - expect(() => - z.templateLiteral().interpolated(z.string().toLowerCase()) - ).toThrow(); - expect(() => - z.templateLiteral().interpolated(z.string().toUpperCase()) - ).toThrow(); -}); - -test("template literal parsing - success - basic cases", () => { - expect(() => z.templateLiteral().parse(7)).toThrow(); - - empty.parse(""); - hello.parse("hello"); - world.parse("world"); - one.parse("1"); - two.parse("2"); - truee.parse("true"); - anotherTrue.parse("true"); - falsee.parse("false"); - anotherFalse.parse("false"); - nulll.parse("null"); - anotherNull.parse("null"); - undefinedd.parse("undefined"); - anotherUndefined.parse("undefined"); - anyString.parse("blahblahblah"); - anyString.parse(""); - anyNumber.parse("123"); - anyNumber.parse("1.23"); - anyNumber.parse("0"); - anyNumber.parse("-1.23"); - anyNumber.parse("-123"); - anyNumber.parse("Infinity"); - anyNumber.parse("-Infinity"); - anyFiniteNumber.parse("123"); - anyFiniteNumber.parse("1.23"); - anyFiniteNumber.parse("0"); - anyFiniteNumber.parse("-1.23"); - anyFiniteNumber.parse("-123"); - anyInt.parse("123"); - anyInt.parse("-123"); - anyNegativeNumber.parse("-123"); - anyNegativeNumber.parse("-1.23"); - anyNegativeNumber.parse("-Infinity"); - anyPositiveNumber.parse("123"); - anyPositiveNumber.parse("1.23"); - anyPositiveNumber.parse("Infinity"); - zeroButInADumbWay.parse("0"); - zeroButInADumbWay.parse("00000"); - finiteButInADumbWay.parse("5"); - finiteButInADumbWay.parse("10"); - finiteButInADumbWay.parse("6.66"); - bool.parse("true"); - bool.parse("false"); - bigone.parse("1"); - anyBigint.parse("123456"); - anyBigint.parse("0"); - anyBigint.parse("-123456"); - nullableYo.parse("yo"); - nullableYo.parse("null"); - nullableString.parse("abc"); - nullableString.parse("null"); - optionalYeah.parse("yeah"); - optionalYeah.parse(""); - optionalString.parse("abc"); - optionalString.parse(""); - optionalNumber.parse("123"); - optionalNumber.parse("1.23"); - optionalNumber.parse("0"); - optionalNumber.parse("-1.23"); - optionalNumber.parse("-123"); - optionalNumber.parse("Infinity"); - optionalNumber.parse("-Infinity"); - nullishBruh.parse("bruh"); - nullishBruh.parse("null"); - nullishBruh.parse(""); - cuid.parse("cjld2cyuq0000t3rmniod1foy"); - cuidZZZ.parse("cjld2cyuq0000t3rmniod1foyZZZ"); - cuid2.parse("tz4a98xxat96iws9zmbrgj3a"); - datetime.parse(new Date().toISOString()); - email.parse("info@example.com"); - ip.parse("213.174.246.205"); - ip.parse("c359:f57c:21e5:39eb:1187:e501:f936:b452"); - ipv4.parse("213.174.246.205"); - ipv6.parse("c359:f57c:21e5:39eb:1187:e501:f936:b452"); - ulid.parse("01GW3D2QZJBYB6P1Z1AE997VPW"); - uuid.parse("808989fd-3a6e-4af2-b607-737323a176f6"); - stringAToZ.parse("asudgaskhdgashd"); - stringStartsWith.parse("hello world"); - stringEndsWith.parse("hello world"); - stringMax5.parse("hello"); - stringMin5.parse("hello"); - stringLen5.parse("hello"); - stringMin5Max10.parse("hello worl"); - stringStartsWithMax5.parse("hello"); - brandedString.parse("branded string"); - anything.parse(""); - anything.parse("everything"); -}); - -test("template literal parsing - failure - basic cases", () => { - expect(() => empty.parse("a")).toThrow(); - expect(() => hello.parse("hello!")).toThrow(); - expect(() => hello.parse("!hello")).toThrow(); - expect(() => world.parse("world!")).toThrow(); - expect(() => world.parse("!world")).toThrow(); - expect(() => one.parse("2")).toThrow(); - expect(() => one.parse("12")).toThrow(); - expect(() => one.parse("21")).toThrow(); - expect(() => two.parse("1")).toThrow(); - expect(() => two.parse("21")).toThrow(); - expect(() => two.parse("12")).toThrow(); - expect(() => truee.parse("false")).toThrow(); - expect(() => truee.parse("1true")).toThrow(); - expect(() => truee.parse("true1")).toThrow(); - expect(() => anotherTrue.parse("false")).toThrow(); - expect(() => anotherTrue.parse("1true")).toThrow(); - expect(() => anotherTrue.parse("true1")).toThrow(); - expect(() => falsee.parse("true")).toThrow(); - expect(() => falsee.parse("1false")).toThrow(); - expect(() => falsee.parse("false1")).toThrow(); - expect(() => anotherFalse.parse("true")).toThrow(); - expect(() => anotherFalse.parse("1false")).toThrow(); - expect(() => anotherFalse.parse("false1")).toThrow(); - expect(() => nulll.parse("123")).toThrow(); - expect(() => nulll.parse("null1")).toThrow(); - expect(() => nulll.parse("1null")).toThrow(); - expect(() => anotherNull.parse("123")).toThrow(); - expect(() => anotherNull.parse("null1")).toThrow(); - expect(() => anotherNull.parse("1null")).toThrow(); - expect(() => undefinedd.parse("123")).toThrow(); - expect(() => undefinedd.parse("undefined1")).toThrow(); - expect(() => undefinedd.parse("1undefined")).toThrow(); - expect(() => anotherUndefined.parse("123")).toThrow(); - expect(() => anotherUndefined.parse("undefined1")).toThrow(); - expect(() => anotherUndefined.parse("1undefined")).toThrow(); - expect(() => anyNumber.parse("2a")).toThrow(); - expect(() => anyNumber.parse("a2")).toThrow(); - expect(() => anyNumber.parse("-2a")).toThrow(); - expect(() => anyNumber.parse("a-2")).toThrow(); - expect(() => anyNumber.parse("2.5a")).toThrow(); - expect(() => anyNumber.parse("a2.5")).toThrow(); - expect(() => anyNumber.parse("Infinitya")).toThrow(); - expect(() => anyNumber.parse("aInfinity")).toThrow(); - expect(() => anyNumber.parse("-Infinitya")).toThrow(); - expect(() => anyNumber.parse("a-Infinity")).toThrow(); - expect(() => anyNumber.parse("2e5")).toThrow(); - expect(() => anyNumber.parse("2e-5")).toThrow(); - expect(() => anyNumber.parse("2e+5")).toThrow(); - expect(() => anyNumber.parse("-2e5")).toThrow(); - expect(() => anyNumber.parse("-2e-5")).toThrow(); - expect(() => anyNumber.parse("-2e+5")).toThrow(); - expect(() => anyNumber.parse("2.1e5")).toThrow(); - expect(() => anyNumber.parse("2.1e-5")).toThrow(); - expect(() => anyNumber.parse("2.1e+5")).toThrow(); - expect(() => anyNumber.parse("-2.1e5")).toThrow(); - expect(() => anyNumber.parse("-2.1e-5")).toThrow(); - expect(() => anyNumber.parse("-2.1e+5")).toThrow(); - expect(() => anyFiniteNumber.parse("Infinity")).toThrow(); - expect(() => anyFiniteNumber.parse("-Infinity")).toThrow(); - expect(() => anyFiniteNumber.parse("123a")).toThrow(); - expect(() => anyFiniteNumber.parse("a123")).toThrow(); - expect(() => anyInt.parse("1.23")).toThrow(); - expect(() => anyInt.parse("-1.23")).toThrow(); - expect(() => anyInt.parse("d1")).toThrow(); - expect(() => anyInt.parse("1d")).toThrow(); - expect(() => anyNegativeNumber.parse("0")).toThrow(); - expect(() => anyNegativeNumber.parse("1")).toThrow(); - expect(() => anyNegativeNumber.parse("Infinity")).toThrow(); - expect(() => anyPositiveNumber.parse("0")).toThrow(); - expect(() => anyPositiveNumber.parse("-1")).toThrow(); - expect(() => anyPositiveNumber.parse("-Infinity")).toThrow(); - expect(() => zeroButInADumbWay.parse("1")).toThrow(); - expect(() => zeroButInADumbWay.parse("-1")).toThrow(); - expect(() => finiteButInADumbWay.parse("Infinity")).toThrow(); - expect(() => finiteButInADumbWay.parse("-Infinity")).toThrow(); - expect(() => finiteButInADumbWay.parse("-5")).toThrow(); - expect(() => finiteButInADumbWay.parse("10a")).toThrow(); - expect(() => finiteButInADumbWay.parse("a10")).toThrow(); - expect(() => bool.parse("123")).toThrow(); - expect(() => bigone.parse("2")).toThrow(); - expect(() => bigone.parse("c1")).toThrow(); - expect(() => anyBigint.parse("1.23")).toThrow(); - expect(() => anyBigint.parse("-1.23")).toThrow(); - expect(() => anyBigint.parse("c123")).toThrow(); - expect(() => nullableYo.parse("yo1")).toThrow(); - expect(() => nullableYo.parse("1yo")).toThrow(); - expect(() => nullableYo.parse("null1")).toThrow(); - expect(() => nullableYo.parse("1null")).toThrow(); - expect(() => optionalYeah.parse("yeah1")).toThrow(); - expect(() => optionalYeah.parse("1yeah")).toThrow(); - expect(() => optionalYeah.parse("undefined")).toThrow(); - expect(() => optionalNumber.parse("123a")).toThrow(); - expect(() => optionalNumber.parse("a123")).toThrow(); - expect(() => optionalNumber.parse("Infinitya")).toThrow(); - expect(() => optionalNumber.parse("aInfinity")).toThrow(); - expect(() => nullishBruh.parse("bruh1")).toThrow(); - expect(() => nullishBruh.parse("1bruh")).toThrow(); - expect(() => nullishBruh.parse("null1")).toThrow(); - expect(() => nullishBruh.parse("1null")).toThrow(); - expect(() => nullishBruh.parse("undefined")).toThrow(); - expect(() => cuid.parse("bjld2cyuq0000t3rmniod1foy")).toThrow(); - expect(() => cuid.parse("cjld2cyu")).toThrow(); - expect(() => cuid.parse("cjld2 cyu")).toThrow(); - expect(() => cuid.parse("cjld2cyuq0000t3rmniod1foy ")).toThrow(); - expect(() => cuid.parse("1cjld2cyuq0000t3rmniod1foy")).toThrow(); - expect(() => cuidZZZ.parse("cjld2cyuq0000t3rmniod1foy")).toThrow(); - expect(() => cuidZZZ.parse("cjld2cyuq0000t3rmniod1foyZZY")).toThrow(); - expect(() => cuidZZZ.parse("cjld2cyuq0000t3rmniod1foyZZZ1")).toThrow(); - expect(() => cuidZZZ.parse("1cjld2cyuq0000t3rmniod1foyZZZ")).toThrow(); - expect(() => cuid2.parse("9z4a98xxat96iws9zmbrgj3a")).toThrow(); - expect(() => cuid2.parse("tz4a98xxat96iws9zmbrgj3!")).toThrow(); - expect(() => datetime.parse("2022-01-01 00:00:00")).toThrow(); - expect(() => email.parse("info@example.com@")).toThrow(); - expect(() => ip.parse("213.174.246:205")).toThrow(); - expect(() => ip.parse("c359.f57c:21e5:39eb:1187:e501:f936:b452")).toThrow(); - expect(() => ipv4.parse("1213.174.246.205")).toThrow(); - expect(() => ipv4.parse("c359:f57c:21e5:39eb:1187:e501:f936:b452")).toThrow(); - expect(() => - ipv6.parse("c359:f57c:21e5:39eb:1187:e501:f936:b4521") - ).toThrow(); - expect(() => ipv6.parse("213.174.246.205")).toThrow(); - expect(() => ulid.parse("01GW3D2QZJBYB6P1Z1AE997VPW!")).toThrow(); - expect(() => uuid.parse("808989fd-3a6e-4af2-b607-737323a176f6Z")).toThrow(); - expect(() => uuid.parse("Z808989fd-3a6e-4af2-b607-737323a176f6")).toThrow(); - expect(() => stringAToZ.parse("asdasdasd1")).toThrow(); - expect(() => stringAToZ.parse("1asdasdasd")).toThrow(); - expect(() => stringStartsWith.parse("ahello")).toThrow(); - expect(() => stringEndsWith.parse("worlda")).toThrow(); - expect(() => stringMax5.parse("123456")).toThrow(); - expect(() => stringMin5.parse("1234")).toThrow(); - expect(() => stringLen5.parse("123456")).toThrow(); - expect(() => stringLen5.parse("1234")).toThrow(); - expect(() => stringMin5Max10.parse("1234")).toThrow(); - expect(() => stringMin5Max10.parse("12345678901")).toThrow(); - expect(() => stringStartsWithMax5.parse("hello1")).toThrow(); - expect(() => stringStartsWithMax5.parse("1hell")).toThrow(); - expect(() => brandedString.parse("")).toThrow(); -}); - -test("template literal parsing - success - complex cases", () => { - url.parse("https://example.com"); - url.parse("https://speedtest.net"); - - measurement.parse(1); - measurement.parse(1.1); - measurement.parse(0); - measurement.parse(-1.1); - measurement.parse(-1); - measurement.parse("1"); - measurement.parse("1.1"); - measurement.parse("0"); - measurement.parse("-1"); - measurement.parse("-1.1"); - measurement.parse("1px"); - measurement.parse("1.1px"); - measurement.parse("0px"); - measurement.parse("-1px"); - measurement.parse("-1.1px"); - measurement.parse("1em"); - measurement.parse("1.1em"); - measurement.parse("0em"); - measurement.parse("-1em"); - measurement.parse("-1.1em"); - measurement.parse("1rem"); - measurement.parse("1.1rem"); - measurement.parse("0rem"); - measurement.parse("-1rem"); - measurement.parse("-1.1rem"); - measurement.parse("1vh"); - measurement.parse("1.1vh"); - measurement.parse("0vh"); - measurement.parse("-1vh"); - measurement.parse("-1.1vh"); - measurement.parse("1vw"); - measurement.parse("1.1vw"); - measurement.parse("0vw"); - measurement.parse("-1vw"); - measurement.parse("-1.1vw"); - measurement.parse("1vmin"); - measurement.parse("1.1vmin"); - measurement.parse("0vmin"); - measurement.parse("-1vmin"); - measurement.parse("-1.1vmin"); - measurement.parse("1vmax"); - measurement.parse("1.1vmax"); - measurement.parse("0vmax"); - measurement.parse("-1vmax"); - measurement.parse("-1.1vmax"); - - connectionString.parse("mongodb://host:1234"); - connectionString.parse("mongodb://host:1234/"); - connectionString.parse("mongodb://host:1234/defaultauthdb"); - connectionString.parse("mongodb://host:1234/defaultauthdb?authSource=admin"); - connectionString.parse( - "mongodb://host:1234/defaultauthdb?authSource=admin&connectTimeoutMS=300000" - ); - connectionString.parse("mongodb://host:1234/?authSource=admin"); - connectionString.parse( - "mongodb://host:1234/?authSource=admin&connectTimeoutMS=300000" - ); - connectionString.parse("mongodb://username:password@host:1234"); - connectionString.parse("mongodb://username:password@host:1234/"); - connectionString.parse("mongodb://username:password@host:1234/defaultauthdb"); - connectionString.parse( - "mongodb://username:password@host:1234/defaultauthdb?authSource=admin" - ); - connectionString.parse( - "mongodb://username:password@host:1234/defaultauthdb?authSource=admin&connectTimeoutMS=300000" - ); - connectionString.parse( - "mongodb://username:password@host:1234/?authSource=admin" - ); - connectionString.parse( - "mongodb://username:password@host:1234/?authSource=admin&connectTimeoutMS=300000" - ); -}); - -test("template literal parsing - failure - complex cases", () => { - expect(() => url.parse("http://example.com")).toThrow(); - expect(() => url.parse("https://.com")).toThrow(); - expect(() => url.parse("https://examplecom")).toThrow(); - expect(() => url.parse("https://example.org")).toThrow(); - expect(() => url.parse("https://example.net.il")).toThrow(); - - expect(() => measurement.parse("1.1.1")).toThrow(); - expect(() => measurement.parse("Infinity")).toThrow(); - expect(() => measurement.parse("-Infinity")).toThrow(); - expect(() => measurement.parse("NaN")).toThrow(); - expect(() => measurement.parse("1%")).toThrow(); - - expect(() => connectionString.parse("mongod://host:1234")).toThrow(); - expect(() => connectionString.parse("mongodb://:1234")).toThrow(); - expect(() => connectionString.parse("mongodb://host1234")).toThrow(); - expect(() => connectionString.parse("mongodb://host:d234")).toThrow(); - expect(() => connectionString.parse("mongodb://host:12.34")).toThrow(); - expect(() => connectionString.parse("mongodb://host:-1234")).toThrow(); - expect(() => connectionString.parse("mongodb://host:-12.34")).toThrow(); - expect(() => connectionString.parse("mongodb://host:")).toThrow(); - expect(() => - connectionString.parse("mongodb://:password@host:1234") - ).toThrow(); - expect(() => - connectionString.parse("mongodb://usernamepassword@host:1234") - ).toThrow(); - expect(() => - connectionString.parse("mongodb://username:@host:1234") - ).toThrow(); - expect(() => connectionString.parse("mongodb://@host:1234")).toThrow(); - expect(() => - connectionString.parse("mongodb://host:1234/defaultauthdb?authSourceadmin") - ).toThrow(); - expect(() => - connectionString.parse("mongodb://host:1234/?authSourceadmin") - ).toThrow(); - expect(() => - connectionString.parse( - "mongodb://host:1234/defaultauthdb?&authSource=admin" - ) - ).toThrow(); - expect(() => - connectionString.parse("mongodb://host:1234/?&authSource=admin") - ).toThrow(); -}); diff --git a/deno/lib/__tests__/transformer.test.ts b/deno/lib/__tests__/transformer.test.ts deleted file mode 100644 index 108b12e91..000000000 --- a/deno/lib/__tests__/transformer.test.ts +++ /dev/null @@ -1,234 +0,0 @@ -// @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"; - -const stringToNumber = z.string().transform((arg) => parseFloat(arg)); -// const numberToString = z -// .transformer(z.number()) -// .transform((n) => String(n)); -const asyncNumberToString = z.number().transform(async (n) => String(n)); - -test("transform ctx.addIssue with parse", () => { - const strs = ["foo", "bar"]; - - expect(() => { - z.string() - .transform((data, ctx) => { - const i = strs.indexOf(data); - if (i === -1) { - ctx.addIssue({ - code: "custom", - message: `${data} is not one of our allowed strings`, - }); - } - return data.length; - }) - .parse("asdf"); - }).toThrow( - JSON.stringify( - [ - { - code: "custom", - message: "asdf is not one of our allowed strings", - path: [], - }, - ], - null, - 2 - ) - ); -}); - -test("transform ctx.addIssue with parseAsync", async () => { - const strs = ["foo", "bar"]; - - const result = await z - .string() - .transform(async (data, ctx) => { - const i = strs.indexOf(data); - if (i === -1) { - ctx.addIssue({ - code: "custom", - message: `${data} is not one of our allowed strings`, - }); - } - return data.length; - }) - .safeParseAsync("asdf"); - - expect(JSON.parse(JSON.stringify(result))).toEqual({ - success: false, - error: { - issues: [ - { - code: "custom", - message: "asdf is not one of our allowed strings", - path: [], - }, - ], - name: "ZodError", - }, - }); -}); - -test("z.NEVER in transform", () => { - const foo = z - .number() - .optional() - .transform((val, ctx) => { - if (!val) { - ctx.addIssue({ code: z.ZodIssueCode.custom, message: "bad" }); - return z.NEVER; - } - return val; - }); - type foo = z.infer<typeof foo>; - util.assertEqual<foo, number>(true); - const arg = foo.safeParse(undefined); - if (!arg.success) { - expect(arg.error.issues[0].message).toEqual("bad"); - } -}); - -test("basic transformations", () => { - const r1 = z - .string() - .transform((data) => data.length) - .parse("asdf"); - expect(r1).toEqual(4); -}); - -test("coercion", () => { - const numToString = z.number().transform((n) => String(n)); - const data = z - .object({ - id: numToString, - }) - .parse({ id: 5 }); - - expect(data).toEqual({ id: "5" }); -}); - -test("async coercion", async () => { - const numToString = z.number().transform(async (n) => String(n)); - const data = await z - .object({ - id: numToString, - }) - .parseAsync({ id: 5 }); - - expect(data).toEqual({ id: "5" }); -}); - -test("sync coercion async error", async () => { - expect(() => - z - .object({ - id: asyncNumberToString, - }) - .parse({ id: 5 }) - ).toThrow(); - // expect(data).toEqual({ id: '5' }); -}); - -test("default", () => { - const data = z.string().default("asdf").parse(undefined); // => "asdf" - expect(data).toEqual("asdf"); -}); - -test("dynamic default", () => { - const data = z - .string() - .default(() => "string") - .parse(undefined); // => "asdf" - expect(data).toEqual("string"); -}); - -test("default when property is null or undefined", () => { - const data = z - .object({ - foo: z.boolean().nullable().default(true), - bar: z.boolean().default(true), - }) - .parse({ foo: null }); - - expect(data).toEqual({ foo: null, bar: true }); -}); - -test("default with falsy values", () => { - const schema = z.object({ - emptyStr: z.string().default("def"), - zero: z.number().default(5), - falseBoolean: z.boolean().default(true), - }); - const input = { emptyStr: "", zero: 0, falseBoolean: true }; - const output = schema.parse(input); - // defaults are not supposed to be used - expect(output).toEqual(input); -}); - -test("object typing", () => { - const t1 = z.object({ - stringToNumber, - }); - - type t1 = z.input<typeof t1>; - type t2 = z.output<typeof t1>; - - util.assertEqual<t1, { stringToNumber: string }>(true); - util.assertEqual<t2, { stringToNumber: number }>(true); -}); - -test("transform method overloads", () => { - const t1 = z.string().transform((val) => val.toUpperCase()); - expect(t1.parse("asdf")).toEqual("ASDF"); - - const t2 = z.string().transform((val) => val.length); - expect(t2.parse("asdf")).toEqual(4); -}); - -test("multiple transformers", () => { - const doubler = stringToNumber.transform((val) => { - return val * 2; - }); - expect(doubler.parse("5")).toEqual(10); -}); - -test("short circuit on dirty", () => { - const schema = z - .string() - .refine(() => false) - .transform((val) => val.toUpperCase()); - const result = schema.safeParse("asdf"); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.custom); - } - - const result2 = schema.safeParse(1234); - expect(result2.success).toEqual(false); - if (!result2.success) { - expect(result2.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_type); - } -}); - -test("async short circuit on dirty", async () => { - const schema = z - .string() - .refine(() => false) - .transform((val) => val.toUpperCase()); - const result = await schema.spa("asdf"); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues[0].code).toEqual(z.ZodIssueCode.custom); - } - - const result2 = await schema.spa(1234); - expect(result2.success).toEqual(false); - if (!result2.success) { - expect(result2.error.issues[0].code).toEqual(z.ZodIssueCode.invalid_type); - } -}); diff --git a/deno/lib/__tests__/tuple.test.ts b/deno/lib/__tests__/tuple.test.ts deleted file mode 100644 index 77d1845c0..000000000 --- a/deno/lib/__tests__/tuple.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -// @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 { ZodError } from "../ZodError.ts"; - -const testTuple = z.tuple([ - z.string(), - z.object({ name: z.literal("Rudy") }), - z.array(z.literal("blue")), -]); -const testData = ["asdf", { name: "Rudy" }, ["blue"]]; -const badData = [123, { name: "Rudy2" }, ["blue", "red"]]; - -test("tuple inference", () => { - const args1 = z.tuple([z.string()]); - const returns1 = z.number(); - const func1 = z.function(args1, returns1); - type func1 = z.TypeOf<typeof func1>; - util.assertEqual<func1, (k: string) => number>(true); -}); - -test("successful validation", () => { - const val = testTuple.parse(testData); - expect(val).toEqual(["asdf", { name: "Rudy" }, ["blue"]]); -}); - -test("successful async validation", async () => { - const val = await testTuple.parseAsync(testData); - return expect(val).toEqual(testData); -}); - -test("failed validation", () => { - const checker = () => { - testTuple.parse([123, { name: "Rudy2" }, ["blue", "red"]] as any); - }; - try { - checker(); - } catch (err) { - if (err instanceof ZodError) { - expect(err.issues.length).toEqual(3); - } - } -}); - -test("failed async validation", async () => { - const res = await testTuple.safeParse(badData); - expect(res.success).toEqual(false); - if (!res.success) { - expect(res.error.issues.length).toEqual(3); - } - // try { - // checker(); - // } catch (err) { - // if (err instanceof ZodError) { - // expect(err.issues.length).toEqual(3); - // } - // } -}); - -test("tuple with transformers", () => { - const stringToNumber = z.string().transform((val) => val.length); - const val = z.tuple([stringToNumber]); - - type t1 = z.input<typeof val>; - util.assertEqual<t1, [string]>(true); - type t2 = z.output<typeof val>; - util.assertEqual<t2, [number]>(true); - expect(val.parse(["1234"])).toEqual([4]); -}); - -test("tuple with rest schema", () => { - const myTuple = z.tuple([z.string(), z.number()]).rest(z.boolean()); - expect(myTuple.parse(["asdf", 1234, true, false, true])).toEqual([ - "asdf", - 1234, - true, - false, - true, - ]); - - expect(myTuple.parse(["asdf", 1234])).toEqual(["asdf", 1234]); - - expect(() => myTuple.parse(["asdf", 1234, "asdf"])).toThrow(); - type t1 = z.output<typeof myTuple>; - - util.assertEqual<t1, [string, number, ...boolean[]]>(true); -}); - -test("parse should fail given sparse array as tuple", () => { - expect(() => testTuple.parse(new Array(3))).toThrow(); -}); - -// test('tuple with optional elements', () => { -// const result = z -// .tuple([z.string(), z.number().optional()]) -// .safeParse(['asdf']); -// expect(result).toEqual(['asdf']); -// }); diff --git a/deno/lib/__tests__/unions.test.ts b/deno/lib/__tests__/unions.test.ts deleted file mode 100644 index 3a73d975f..000000000 --- a/deno/lib/__tests__/unions.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("function parsing", () => { - const schema = z.union([ - z.string().refine(() => false), - z.number().refine(() => false), - ]); - const result = schema.safeParse("asdf"); - expect(result.success).toEqual(false); -}); - -test("union 2", () => { - const result = z - .union([z.number(), z.string().refine(() => false)]) - .safeParse("a"); - expect(result.success).toEqual(false); -}); - -test("return valid over invalid", () => { - const schema = z.union([ - z.object({ - email: z.string().email(), - }), - z.string(), - ]); - expect(schema.parse("asdf")).toEqual("asdf"); - expect(schema.parse({ email: "asdlkjf@lkajsdf.com" })).toEqual({ - email: "asdlkjf@lkajsdf.com", - }); -}); - -test("return dirty result over aborted", () => { - const result = z - .union([z.number(), z.string().refine(() => false)]) - .safeParse("a"); - expect(result.success).toEqual(false); - if (!result.success) { - expect(result.error.issues).toEqual([ - { - code: "custom", - message: "Invalid input", - path: [], - }, - ]); - } -}); - -test("options getter", async () => { - const union = z.union([z.string(), z.number()]); - union.options[0].parse("asdf"); - union.options[1].parse(1234); - await union.options[0].parseAsync("asdf"); - await union.options[1].parseAsync(1234); -}); - -test("readonly union", async () => { - const options = [z.string(), z.number()] as const; - const union = z.union(options); - union.parse("asdf"); - union.parse(12); -}); diff --git a/deno/lib/__tests__/validations.test.ts b/deno/lib/__tests__/validations.test.ts deleted file mode 100644 index 7ebbaa3d1..000000000 --- a/deno/lib/__tests__/validations.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -// @ts-ignore TS6133 -import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts"; -const test = Deno.test; - -import * as z from "../index.ts"; - -test("array min", async () => { - try { - await z.array(z.string()).min(4).parseAsync([]); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "Array must contain at least 4 element(s)" - ); - } -}); - -test("array max", async () => { - try { - await z.array(z.string()).max(2).parseAsync(["asdf", "asdf", "asdf"]); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "Array must contain at most 2 element(s)" - ); - } -}); - -test("array length", async () => { - try { - await z.array(z.string()).length(2).parseAsync(["asdf", "asdf", "asdf"]); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "Array must contain exactly 2 element(s)" - ); - } - - try { - await z.array(z.string()).length(2).parseAsync(["asdf"]); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "Array must contain exactly 2 element(s)" - ); - } -}); - -test("string length", async () => { - try { - await z.string().length(4).parseAsync("asd"); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "String must contain exactly 4 character(s)" - ); - } - - try { - await z.string().length(4).parseAsync("asdaa"); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "String must contain exactly 4 character(s)" - ); - } -}); - -test("string min", async () => { - try { - await z.string().min(4).parseAsync("asd"); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "String must contain at least 4 character(s)" - ); - } -}); - -test("string max", async () => { - try { - await z.string().max(4).parseAsync("aasdfsdfsd"); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "String must contain at most 4 character(s)" - ); - } -}); - -test("number min", async () => { - try { - await z.number().gte(3).parseAsync(2); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "Number must be greater than or equal to 3" - ); - } -}); - -test("number max", async () => { - try { - await z.number().lte(3).parseAsync(4); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "Number must be less than or equal to 3" - ); - } -}); - -test("number nonnegative", async () => { - try { - await z.number().nonnegative().parseAsync(-1); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "Number must be greater than or equal to 0" - ); - } -}); - -test("number nonpositive", async () => { - try { - await z.number().nonpositive().parseAsync(1); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "Number must be less than or equal to 0" - ); - } -}); - -test("number negative", async () => { - try { - await z.number().negative().parseAsync(1); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "Number must be less than 0" - ); - } -}); - -test("number positive", async () => { - try { - await z.number().positive().parseAsync(-1); - } catch (err) { - expect((err as z.ZodError).issues[0].message).toEqual( - "Number must be greater than 0" - ); - } -}); - -test("instantiation", () => { - z.string().min(5); - z.string().max(5); - z.string().length(5); - z.string().email(); - z.string().url(); - z.string().uuid(); - z.string().min(5, { message: "Must be 5 or more characters long" }); - z.string().max(5, { message: "Must be 5 or fewer characters long" }); - z.string().length(5, { message: "Must be exactly 5 characters long" }); - z.string().email({ message: "Invalid email address." }); - z.string().url({ message: "Invalid url" }); - z.string().uuid({ message: "Invalid UUID" }); -}); - -test("int", async () => { - const int = z.number().int(); - int.parse(4); - expect(() => int.parse(3.5)).toThrow(); -}); diff --git a/deno/lib/__tests__/void.test.ts b/deno/lib/__tests__/void.test.ts deleted file mode 100644 index d6e5eeed1..000000000 --- a/deno/lib/__tests__/void.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -// @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"; -test("void", () => { - const v = z.void(); - v.parse(undefined); - - expect(() => v.parse(null)).toThrow(); - expect(() => v.parse("")).toThrow(); - - type v = z.infer<typeof v>; - util.assertEqual<v, void>(true); -}); diff --git a/deno/lib/benchmarks/discriminatedUnion.ts b/deno/lib/benchmarks/discriminatedUnion.ts deleted file mode 100644 index ba827dc30..000000000 --- a/deno/lib/benchmarks/discriminatedUnion.ts +++ /dev/null @@ -1,80 +0,0 @@ -import Benchmark from "benchmark"; - -import { z } from "../index.ts"; - -const doubleSuite = new Benchmark.Suite("z.discriminatedUnion: double"); -const manySuite = new Benchmark.Suite("z.discriminatedUnion: many"); - -const aSchema = z.object({ - type: z.literal("a"), -}); -const objA = { - type: "a", -}; - -const bSchema = z.object({ - type: z.literal("b"), -}); -const objB = { - type: "b", -}; - -const cSchema = z.object({ - type: z.literal("c"), -}); -const objC = { - type: "c", -}; - -const dSchema = z.object({ - type: z.literal("d"), -}); - -const double = z.discriminatedUnion("type", [aSchema, bSchema]); -const many = z.discriminatedUnion("type", [aSchema, bSchema, cSchema, dSchema]); - -doubleSuite - .add("valid: a", () => { - double.parse(objA); - }) - .add("valid: b", () => { - double.parse(objB); - }) - .add("invalid: null", () => { - try { - double.parse(null); - } catch (err) {} - }) - .add("invalid: wrong shape", () => { - try { - double.parse(objC); - } catch (err) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`${(doubleSuite as any).name}: ${e.target}`); - }); - -manySuite - .add("valid: a", () => { - many.parse(objA); - }) - .add("valid: c", () => { - many.parse(objC); - }) - .add("invalid: null", () => { - try { - many.parse(null); - } catch (err) {} - }) - .add("invalid: wrong shape", () => { - try { - many.parse({ type: "unknown" }); - } catch (err) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`${(manySuite as any).name}: ${e.target}`); - }); - -export default { - suites: [doubleSuite, manySuite], -}; diff --git a/deno/lib/benchmarks/index.ts b/deno/lib/benchmarks/index.ts deleted file mode 100644 index 1ce4e755e..000000000 --- a/deno/lib/benchmarks/index.ts +++ /dev/null @@ -1,45 +0,0 @@ -import Benchmark from "benchmark"; - -import discriminatedUnionBenchmarks from "./discriminatedUnion.ts"; -import objectBenchmarks from "./object.ts"; -import primitiveBenchmarks from "./primitives.ts"; -import realworld from "./realworld.ts"; -import stringBenchmarks from "./string.ts"; -import unionBenchmarks from "./union.ts"; - -const argv = process.argv.slice(2); -let suites: Benchmark.Suite[] = []; - -if (!argv.length) { - suites = [ - ...realworld.suites, - ...primitiveBenchmarks.suites, - ...stringBenchmarks.suites, - ...objectBenchmarks.suites, - ...unionBenchmarks.suites, - ...discriminatedUnionBenchmarks.suites, - ]; -} else { - if (argv.includes("--realworld")) { - suites.push(...realworld.suites); - } - if (argv.includes("--primitives")) { - suites.push(...primitiveBenchmarks.suites); - } - if (argv.includes("--string")) { - suites.push(...stringBenchmarks.suites); - } - if (argv.includes("--object")) { - suites.push(...objectBenchmarks.suites); - } - if (argv.includes("--union")) { - suites.push(...unionBenchmarks.suites); - } - if (argv.includes("--discriminatedUnion")) { - suites.push(...discriminatedUnionBenchmarks.suites); - } -} - -for (const suite of suites) { - suite.run(); -} diff --git a/deno/lib/benchmarks/object.ts b/deno/lib/benchmarks/object.ts deleted file mode 100644 index 49327f707..000000000 --- a/deno/lib/benchmarks/object.ts +++ /dev/null @@ -1,69 +0,0 @@ -import Benchmark from "benchmark"; - -import { z } from "../index.ts"; - -const emptySuite = new Benchmark.Suite("z.object: empty"); -const shortSuite = new Benchmark.Suite("z.object: short"); -const longSuite = new Benchmark.Suite("z.object: long"); - -const empty = z.object({}); -const short = z.object({ - string: z.string(), -}); -const long = z.object({ - string: z.string(), - number: z.number(), - boolean: z.boolean(), -}); - -emptySuite - .add("valid", () => { - empty.parse({}); - }) - .add("valid: extra keys", () => { - empty.parse({ string: "string" }); - }) - .add("invalid: null", () => { - try { - empty.parse(null); - } catch (err) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`${(emptySuite as any).name}: ${e.target}`); - }); - -shortSuite - .add("valid", () => { - short.parse({ string: "string" }); - }) - .add("valid: extra keys", () => { - short.parse({ string: "string", number: 42 }); - }) - .add("invalid: null", () => { - try { - short.parse(null); - } catch (err) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`${(shortSuite as any).name}: ${e.target}`); - }); - -longSuite - .add("valid", () => { - long.parse({ string: "string", number: 42, boolean: true }); - }) - .add("valid: extra keys", () => { - long.parse({ string: "string", number: 42, boolean: true, list: [] }); - }) - .add("invalid: null", () => { - try { - long.parse(null); - } catch (err) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`${(longSuite as any).name}: ${e.target}`); - }); - -export default { - suites: [emptySuite, shortSuite, longSuite], -}; diff --git a/deno/lib/benchmarks/primitives.ts b/deno/lib/benchmarks/primitives.ts deleted file mode 100644 index c91b50114..000000000 --- a/deno/lib/benchmarks/primitives.ts +++ /dev/null @@ -1,138 +0,0 @@ -import Benchmark from "benchmark"; - -import { Mocker } from "../__tests__/Mocker.ts"; -import { z } from "../index.ts"; - -const val = new Mocker(); - -const enumSuite = new Benchmark.Suite("z.enum"); -const enumSchema = z.enum(["a", "b", "c"]); - -enumSuite - .add("valid", () => { - enumSchema.parse("a"); - }) - .add("invalid", () => { - try { - enumSchema.parse("x"); - } catch (e) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`z.enum: ${e.target}`); - }); - -const undefinedSuite = new Benchmark.Suite("z.undefined"); -const undefinedSchema = z.undefined(); - -undefinedSuite - .add("valid", () => { - undefinedSchema.parse(undefined); - }) - .add("invalid", () => { - try { - undefinedSchema.parse(1); - } catch (e) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`z.undefined: ${e.target}`); - }); - -const literalSuite = new Benchmark.Suite("z.literal"); -const short = "short"; -const bad = "bad"; -const literalSchema = z.literal("short"); - -literalSuite - .add("valid", () => { - literalSchema.parse(short); - }) - .add("invalid", () => { - try { - literalSchema.parse(bad); - } catch (e) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`z.literal: ${e.target}`); - }); - -const numberSuite = new Benchmark.Suite("z.number"); -const numberSchema = z.number().int(); - -numberSuite - .add("valid", () => { - numberSchema.parse(1); - }) - .add("invalid type", () => { - try { - numberSchema.parse("bad"); - } catch (e) {} - }) - .add("invalid number", () => { - try { - numberSchema.parse(0.5); - } catch (e) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`z.number: ${e.target}`); - }); - -const dateSuite = new Benchmark.Suite("z.date"); - -const plainDate = z.date(); -const minMaxDate = z - .date() - .min(new Date("2021-01-01")) - .max(new Date("2030-01-01")); - -dateSuite - .add("valid", () => { - plainDate.parse(new Date()); - }) - .add("invalid", () => { - try { - plainDate.parse(1); - } catch (e) {} - }) - .add("valid min and max", () => { - minMaxDate.parse(new Date("2023-01-01")); - }) - .add("invalid min", () => { - try { - minMaxDate.parse(new Date("2019-01-01")); - } catch (e) {} - }) - .add("invalid max", () => { - try { - minMaxDate.parse(new Date("2031-01-01")); - } catch (e) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`z.date: ${e.target}`); - }); - -const symbolSuite = new Benchmark.Suite("z.symbol"); -const symbolSchema = z.symbol(); - -symbolSuite - .add("valid", () => { - symbolSchema.parse(val.symbol); - }) - .add("invalid", () => { - try { - symbolSchema.parse(1); - } catch (e) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`z.symbol: ${e.target}`); - }); - -export default { - suites: [ - enumSuite, - undefinedSuite, - literalSuite, - numberSuite, - dateSuite, - symbolSuite, - ], -}; diff --git a/deno/lib/benchmarks/realworld.ts b/deno/lib/benchmarks/realworld.ts deleted file mode 100644 index fa0a51586..000000000 --- a/deno/lib/benchmarks/realworld.ts +++ /dev/null @@ -1,63 +0,0 @@ -import Benchmark from "benchmark"; - -import { z } from "../index.ts"; - -const shortSuite = new Benchmark.Suite("realworld"); - -const People = z.array( - z.object({ - type: z.literal("person"), - hair: z.enum(["blue", "brown"]), - active: z.boolean(), - name: z.string(), - age: z.number().int(), - hobbies: z.array(z.string()), - address: z.object({ - street: z.string(), - zip: z.string(), - country: z.string(), - }), - }) -); - -let i = 0; - -function num() { - return ++i; -} - -function str() { - return (++i % 100).toString(16); -} - -function array<T>(fn: () => T): T[] { - return Array.from({ length: ++i % 10 }, () => fn()); -} - -const people = Array.from({ length: 100 }, () => { - return { - type: "person", - hair: i % 2 ? "blue" : "brown", - active: !!(i % 2), - name: str(), - age: num(), - hobbies: array(str), - address: { - street: str(), - zip: str(), - country: str(), - }, - }; -}); - -shortSuite - .add("valid", () => { - People.parse(people); - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`${(shortSuite as any).name}: ${e.target}`); - }); - -export default { - suites: [shortSuite], -}; diff --git a/deno/lib/benchmarks/string.ts b/deno/lib/benchmarks/string.ts deleted file mode 100644 index 7278eaf8f..000000000 --- a/deno/lib/benchmarks/string.ts +++ /dev/null @@ -1,55 +0,0 @@ -import Benchmark from "benchmark"; - -import { z } from "../index.ts"; - -const SUITE_NAME = "z.string"; -const suite = new Benchmark.Suite(SUITE_NAME); - -const empty = ""; -const short = "short"; -const long = "long".repeat(256); -const manual = (str: unknown) => { - if (typeof str !== "string") { - throw new Error("Not a string"); - } - - return str; -}; -const stringSchema = z.string(); -const optionalStringSchema = z.string().optional(); -const optionalNullableStringSchema = z.string().optional().nullable(); - -suite - .add("empty string", () => { - stringSchema.parse(empty); - }) - .add("short string", () => { - stringSchema.parse(short); - }) - .add("long string", () => { - stringSchema.parse(long); - }) - .add("optional string", () => { - optionalStringSchema.parse(long); - }) - .add("nullable string", () => { - optionalNullableStringSchema.parse(long); - }) - .add("nullable (null) string", () => { - optionalNullableStringSchema.parse(null); - }) - .add("invalid: null", () => { - try { - stringSchema.parse(null); - } catch (err) {} - }) - .add("manual parser: long", () => { - manual(long); - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`${SUITE_NAME}: ${e.target}`); - }); - -export default { - suites: [suite], -}; diff --git a/deno/lib/benchmarks/union.ts b/deno/lib/benchmarks/union.ts deleted file mode 100644 index 62f2df92a..000000000 --- a/deno/lib/benchmarks/union.ts +++ /dev/null @@ -1,80 +0,0 @@ -import Benchmark from "benchmark"; - -import { z } from "../index.ts"; - -const doubleSuite = new Benchmark.Suite("z.union: double"); -const manySuite = new Benchmark.Suite("z.union: many"); - -const aSchema = z.object({ - type: z.literal("a"), -}); -const objA = { - type: "a", -}; - -const bSchema = z.object({ - type: z.literal("b"), -}); -const objB = { - type: "b", -}; - -const cSchema = z.object({ - type: z.literal("c"), -}); -const objC = { - type: "c", -}; - -const dSchema = z.object({ - type: z.literal("d"), -}); - -const double = z.union([aSchema, bSchema]); -const many = z.union([aSchema, bSchema, cSchema, dSchema]); - -doubleSuite - .add("valid: a", () => { - double.parse(objA); - }) - .add("valid: b", () => { - double.parse(objB); - }) - .add("invalid: null", () => { - try { - double.parse(null); - } catch (err) {} - }) - .add("invalid: wrong shape", () => { - try { - double.parse(objC); - } catch (err) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`${(doubleSuite as any).name}: ${e.target}`); - }); - -manySuite - .add("valid: a", () => { - many.parse(objA); - }) - .add("valid: c", () => { - many.parse(objC); - }) - .add("invalid: null", () => { - try { - many.parse(null); - } catch (err) {} - }) - .add("invalid: wrong shape", () => { - try { - many.parse({ type: "unknown" }); - } catch (err) {} - }) - .on("cycle", (e: Benchmark.Event) => { - console.log(`${(manySuite as any).name}: ${e.target}`); - }); - -export default { - suites: [doubleSuite, manySuite], -}; diff --git a/deno/lib/errors.ts b/deno/lib/errors.ts deleted file mode 100644 index f3d1a17e9..000000000 --- a/deno/lib/errors.ts +++ /dev/null @@ -1,13 +0,0 @@ -import defaultErrorMap from "./locales/en.ts"; -import type { ZodErrorMap } from "./ZodError.ts"; - -let overrideErrorMap = defaultErrorMap; -export { defaultErrorMap }; - -export function setErrorMap(map: ZodErrorMap) { - overrideErrorMap = map; -} - -export function getErrorMap() { - return overrideErrorMap; -} diff --git a/deno/lib/external.ts b/deno/lib/external.ts deleted file mode 100644 index b2070f81c..000000000 --- a/deno/lib/external.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from "./errors.ts"; -export * from "./helpers/parseUtil.ts"; -export * from "./helpers/typeAliases.ts"; -export * from "./helpers/util.ts"; -export * from "./types.ts"; -export * from "./ZodError.ts"; diff --git a/deno/lib/helpers/enumUtil.ts b/deno/lib/helpers/enumUtil.ts deleted file mode 100644 index 205d26664..000000000 --- a/deno/lib/helpers/enumUtil.ts +++ /dev/null @@ -1,19 +0,0 @@ -export namespace enumUtil { - type UnionToIntersectionFn<T> = ( - T extends unknown ? (k: () => T) => void : never - ) extends (k: infer Intersection) => void - ? Intersection - : never; - - type GetUnionLast<T> = UnionToIntersectionFn<T> extends () => infer Last - ? Last - : never; - - type UnionToTuple<T, Tuple extends unknown[] = []> = [T] extends [never] - ? Tuple - : UnionToTuple<Exclude<T, GetUnionLast<T>>, [GetUnionLast<T>, ...Tuple]>; - - type CastToStringTuple<T> = T extends [string, ...string[]] ? T : never; - - export type UnionToTupleString<T> = CastToStringTuple<UnionToTuple<T>>; -} diff --git a/deno/lib/helpers/errorUtil.ts b/deno/lib/helpers/errorUtil.ts deleted file mode 100644 index 8d9afa2a8..000000000 --- a/deno/lib/helpers/errorUtil.ts +++ /dev/null @@ -1,7 +0,0 @@ -export namespace errorUtil { - export type ErrMessage = string | { message?: string }; - export const errToObj = (message?: ErrMessage) => - typeof message === "string" ? { message } : message || {}; - export const toString = (message?: ErrMessage): string | undefined => - typeof message === "string" ? message : message?.message; -} diff --git a/deno/lib/helpers/parseUtil.ts b/deno/lib/helpers/parseUtil.ts deleted file mode 100644 index 8df221464..000000000 --- a/deno/lib/helpers/parseUtil.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { getErrorMap } from "../errors.ts"; -import defaultErrorMap from "../locales/en.ts"; -import type { IssueData, ZodErrorMap, ZodIssue } from "../ZodError.ts"; -import type { ZodParsedType } from "./util.ts"; - -export const makeIssue = (params: { - data: any; - path: (string | number)[]; - errorMaps: ZodErrorMap[]; - issueData: IssueData; -}): ZodIssue => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...(issueData.path || [])]; - const fullIssue = { - ...issueData, - path: fullPath, - }; - - let errorMessage = ""; - const maps = errorMaps - .filter((m) => !!m) - .slice() - .reverse() as ZodErrorMap[]; - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - - return { - ...issueData, - path: fullPath, - message: issueData.message ?? errorMessage, - }; -}; - -export type ParseParams = { - path: (string | number)[]; - errorMap: ZodErrorMap; - async: boolean; -}; - -export type ParsePathComponent = string | number; -export type ParsePath = ParsePathComponent[]; -export const EMPTY_PATH: ParsePath = []; - -export interface ParseContext { - readonly common: { - readonly issues: ZodIssue[]; - readonly contextualErrorMap?: ZodErrorMap; - readonly async: boolean; - }; - readonly path: ParsePath; - readonly schemaErrorMap?: ZodErrorMap; - readonly parent: ParseContext | null; - readonly data: any; - readonly parsedType: ZodParsedType; -} - -export type ParseInput = { - data: any; - path: (string | number)[]; - parent: ParseContext; -}; - -export function addIssueToContext( - ctx: ParseContext, - issueData: IssueData -): void { - const issue = makeIssue({ - issueData: issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, // contextual error map is first priority - ctx.schemaErrorMap, // then schema-bound map if available - getErrorMap(), // then global override map - defaultErrorMap, // then global default map - ].filter((x) => !!x) as ZodErrorMap[], - }); - ctx.common.issues.push(issue); -} - -export type ObjectPair = { - key: SyncParseReturnType<any>; - value: SyncParseReturnType<any>; -}; -export class ParseStatus { - value: "aborted" | "dirty" | "valid" = "valid"; - dirty() { - if (this.value === "valid") this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") this.value = "aborted"; - } - - static mergeArray( - status: ParseStatus, - results: SyncParseReturnType<any>[] - ): SyncParseReturnType { - const arrayValue: any[] = []; - for (const s of results) { - if (s.status === "aborted") return INVALID; - if (s.status === "dirty") status.dirty(); - arrayValue.push(s.value); - } - - return { status: status.value, value: arrayValue }; - } - - static async mergeObjectAsync( - status: ParseStatus, - pairs: { key: ParseReturnType<any>; value: ParseReturnType<any> }[] - ): Promise<SyncParseReturnType<any>> { - const syncPairs: ObjectPair[] = []; - for (const pair of pairs) { - syncPairs.push({ - key: await pair.key, - value: await pair.value, - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - - static mergeObjectSync( - status: ParseStatus, - pairs: { - key: SyncParseReturnType<any>; - value: SyncParseReturnType<any>; - alwaysSet?: boolean; - }[] - ): SyncParseReturnType { - const finalObject: any = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") return INVALID; - if (value.status === "aborted") return INVALID; - if (key.status === "dirty") status.dirty(); - if (value.status === "dirty") status.dirty(); - - if ( - key.value !== "__proto__" && - (typeof value.value !== "undefined" || pair.alwaysSet) - ) { - finalObject[key.value] = value.value; - } - } - - return { status: status.value, value: finalObject }; - } -} -export interface ParseResult { - status: "aborted" | "dirty" | "valid"; - data: any; -} - -export type INVALID = { status: "aborted" }; -export const INVALID: INVALID = Object.freeze({ - status: "aborted", -}); - -export type DIRTY<T> = { status: "dirty"; value: T }; -export const DIRTY = <T>(value: T): DIRTY<T> => ({ status: "dirty", value }); - -export type OK<T> = { status: "valid"; value: T }; -export const OK = <T>(value: T): OK<T> => ({ status: "valid", value }); - -export type SyncParseReturnType<T = any> = OK<T> | DIRTY<T> | INVALID; -export type AsyncParseReturnType<T> = Promise<SyncParseReturnType<T>>; -export type ParseReturnType<T> = - | SyncParseReturnType<T> - | AsyncParseReturnType<T>; - -export const isAborted = (x: ParseReturnType<any>): x is INVALID => - (x as any).status === "aborted"; -export const isDirty = <T>(x: ParseReturnType<T>): x is OK<T> | DIRTY<T> => - (x as any).status === "dirty"; -export const isValid = <T>(x: ParseReturnType<T>): x is OK<T> => - (x as any).status === "valid"; -export const isAsync = <T>( - x: ParseReturnType<T> -): x is AsyncParseReturnType<T> => - typeof Promise !== "undefined" && x instanceof Promise; diff --git a/deno/lib/helpers/partialUtil.ts b/deno/lib/helpers/partialUtil.ts deleted file mode 100644 index b9de239fd..000000000 --- a/deno/lib/helpers/partialUtil.ts +++ /dev/null @@ -1,78 +0,0 @@ -import type { - ZodArray, - ZodNullable, - ZodObject, - ZodOptional, - ZodRawShape, - ZodTuple, - ZodTupleItems, - ZodTypeAny, -} from "../index.ts"; - -export namespace partialUtil { - // export type DeepPartial<T extends AnyZodObject> = T extends AnyZodObject - // ? ZodObject< - // { [k in keyof T["_shape"]]: InternalDeepPartial<T["_shape"][k]> }, - // T["_unknownKeys"], - // T["_catchall"] - // > - // : T extends ZodArray<infer Type, infer Card> - // ? ZodArray<InternalDeepPartial<Type>, Card> - // : ZodOptional<T>; - - // { - // // optional: T extends ZodOptional<ZodTypeAny> ? T : ZodOptional<T>; - // // array: T extends ZodArray<infer Type> ? ZodArray<DeepPartial<Type>> : never; - // object: T extends AnyZodObject - // ? ZodObject< - // { [k in keyof T["_shape"]]: DeepPartial<T["_shape"][k]> }, - // T["_unknownKeys"], - // T["_catchall"] - // > - // : never; - // rest: ReturnType<T["optional"]>; // ZodOptional<T>; - // }[T extends AnyZodObject - // ? "object" // T extends ZodOptional<any> // ? 'optional' // : - // : "rest"]; - - export type DeepPartial<T extends ZodTypeAny> = - T extends ZodObject<ZodRawShape> - ? ZodObject< - { [k in keyof T["shape"]]: ZodOptional<DeepPartial<T["shape"][k]>> }, - T["_def"]["unknownKeys"], - T["_def"]["catchall"] - > - : T extends ZodArray<infer Type, infer Card> - ? ZodArray<DeepPartial<Type>, Card> - : T extends ZodOptional<infer Type> - ? ZodOptional<DeepPartial<Type>> - : T extends ZodNullable<infer Type> - ? ZodNullable<DeepPartial<Type>> - : T extends ZodTuple<infer Items> - ? { - [k in keyof Items]: Items[k] extends ZodTypeAny - ? DeepPartial<Items[k]> - : never; - } extends infer PI - ? PI extends ZodTupleItems - ? ZodTuple<PI> - : never - : never - : T; - // { - // // optional: T extends ZodOptional<ZodTypeAny> ? T : ZodOptional<T>; - // // array: T extends ZodArray<infer Type> ? ZodArray<DeepPartial<Type>> : never; - // object: T extends ZodObject<infer Shape, infer Params, infer Catchall> - // ? ZodOptional< - // ZodObject< - // { [k in keyof Shape]: DeepPartial<Shape[k]> }, - // Params, - // Catchall - // > - // > - // : never; - // rest: ReturnType<T["optional"]>; - // }[T extends ZodObject<any> - // ? "object" // T extends ZodOptional<any> // ? 'optional' // : - // : "rest"]; -} diff --git a/deno/lib/helpers/typeAliases.ts b/deno/lib/helpers/typeAliases.ts deleted file mode 100644 index 3afd2bad0..000000000 --- a/deno/lib/helpers/typeAliases.ts +++ /dev/null @@ -1,9 +0,0 @@ -export type Primitive = - | string - | number - | symbol - | bigint - | boolean - | null - | undefined; -export type Scalars = Primitive | Primitive[]; diff --git a/deno/lib/helpers/util.ts b/deno/lib/helpers/util.ts deleted file mode 100644 index 39e1e8025..000000000 --- a/deno/lib/helpers/util.ts +++ /dev/null @@ -1,221 +0,0 @@ -export namespace util { - type AssertEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends < - V - >() => V extends U ? 1 : 2 - ? true - : false; - - export type isAny<T> = 0 extends 1 & T ? true : false; - export const assertEqual = <A, B>(val: AssertEqual<A, B>) => val; - export function assertIs<T>(_arg: T): void {} - export function assertNever(_x: never): never { - throw new Error(); - } - - export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; - export type OmitKeys<T, K extends string> = Pick<T, Exclude<keyof T, K>>; - export type MakePartial<T, K extends keyof T> = Omit<T, K> & - Partial<Pick<T, K>>; - - export const arrayToEnum = <T extends string, U extends [T, ...T[]]>( - items: U - ): { [k in U[number]]: k } => { - const obj: any = {}; - for (const item of items) { - obj[item] = item; - } - return obj as any; - }; - - export const getValidEnumValues = (obj: any) => { - const validKeys = objectKeys(obj).filter( - (k: any) => typeof obj[obj[k]] !== "number" - ); - const filtered: any = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return objectValues(filtered); - }; - - export const objectValues = (obj: any) => { - return objectKeys(obj).map(function (e) { - return obj[e]; - }); - }; - - export const objectKeys: ObjectConstructor["keys"] = - typeof Object.keys === "function" // eslint-disable-line ban/ban - ? (obj: any) => Object.keys(obj) // eslint-disable-line ban/ban - : (object: any) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - - export const find = <T>( - arr: T[], - checker: (arg: T) => any - ): T | undefined => { - for (const item of arr) { - if (checker(item)) return item; - } - return undefined; - }; - - export type identity<T> = objectUtil.identity<T>; - export type flatten<T> = objectUtil.flatten<T>; - - export type noUndefined<T> = T extends undefined ? never : T; - - export const isInteger: NumberConstructor["isInteger"] = - typeof Number.isInteger === "function" - ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban - : (val) => - typeof val === "number" && isFinite(val) && Math.floor(val) === val; - - export function joinValues<T extends any[]>( - array: T, - separator = " | " - ): string { - return array - .map((val) => (typeof val === "string" ? `'${val}'` : val)) - .join(separator); - } - - export const jsonStringifyReplacer = (_: string, value: any): any => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -} - -export namespace objectUtil { - export type MergeShapes<U, V> = { - [k in Exclude<keyof U, keyof V>]: U[k]; - } & V; - - type optionalKeys<T extends object> = { - [k in keyof T]: undefined extends T[k] ? k : never; - }[keyof T]; - - type requiredKeys<T extends object> = { - [k in keyof T]: undefined extends T[k] ? never : k; - }[keyof T]; - - // export type addQuestionMarks< - // T extends object, - // R extends keyof T = requiredKeys<T> - // > = Pick<Required<T>, R> & Partial<T>; - export type addQuestionMarks< - T extends object, - R extends keyof T = requiredKeys<T>, - O extends keyof T = optionalKeys<T> - > = Pick<T, R> & Partial<Pick<T, O>> & { [k in keyof T]?: unknown }; - - export type identity<T> = T; - export type flatten<T> = identity<{ [k in keyof T]: T[k] }>; - - export type noNeverKeys<T> = { - [k in keyof T]: [T[k]] extends [never] ? never : k; - }[keyof T]; - - export type noNever<T> = identity<{ - [k in noNeverKeys<T>]: k extends keyof T ? T[k] : never; - }>; - - export const mergeShapes = <U, T>(first: U, second: T): T & U => { - return { - ...first, - ...second, // second overwrites first - }; - }; - - export type extendShape<A, B> = flatten<Omit<A, keyof B> & B>; -} - -export const ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set", -]); - -export type ZodParsedType = keyof typeof ZodParsedType; - -export const getParsedType = (data: any): ZodParsedType => { - const t = typeof data; - - switch (t) { - case "undefined": - return ZodParsedType.undefined; - - case "string": - return ZodParsedType.string; - - case "number": - return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - - case "boolean": - return ZodParsedType.boolean; - - case "function": - return ZodParsedType.function; - - case "bigint": - return ZodParsedType.bigint; - - case "symbol": - return ZodParsedType.symbol; - - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if ( - data.then && - typeof data.then === "function" && - data.catch && - typeof data.catch === "function" - ) { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - - default: - return ZodParsedType.unknown; - } -}; diff --git a/deno/lib/index.ts b/deno/lib/index.ts deleted file mode 100644 index 36d6f0ed8..000000000 --- a/deno/lib/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import * as z from "./external.ts"; -export * from "./external.ts"; -export { z }; -export default z; diff --git a/deno/lib/locales/en.ts b/deno/lib/locales/en.ts deleted file mode 100644 index 0665af275..000000000 --- a/deno/lib/locales/en.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { util, ZodParsedType } from "../helpers/util.ts"; -import { ZodErrorMap, ZodIssueCode } from "../ZodError.ts"; - -const errorMap: ZodErrorMap = (issue, _ctx) => { - let message: string; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify( - issue.expected, - util.jsonStringifyReplacer - )}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues( - issue.keys, - ", " - )}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues( - issue.options - )}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues( - issue.options - )}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${ - issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than` - } ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${ - issue.exact ? "exactly" : issue.inclusive ? `at least` : `over` - } ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${ - issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than ` - }${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${ - issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than ` - }${new Date(Number(issue.minimum))}`; - else message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${ - issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than` - } ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${ - issue.exact ? `exactly` : issue.inclusive ? `at most` : `under` - } ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${ - issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than` - } ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${ - issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than` - } ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${ - issue.exact - ? `exactly` - : issue.inclusive - ? `smaller than or equal to` - : `smaller than` - } ${new Date(Number(issue.maximum))}`; - else message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue); - } - return { message }; -}; - -export default errorMap; diff --git a/deno/lib/mod.ts b/deno/lib/mod.ts deleted file mode 100644 index 41e22e465..000000000 --- a/deno/lib/mod.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./index.ts"; -export { default as default } from "./index.ts"; diff --git a/deno/lib/types.ts b/deno/lib/types.ts deleted file mode 100644 index 7ab1c23ed..000000000 --- a/deno/lib/types.ts +++ /dev/null @@ -1,5572 +0,0 @@ -import { defaultErrorMap, getErrorMap } from "./errors.ts"; -import { enumUtil } from "./helpers/enumUtil.ts"; -import { errorUtil } from "./helpers/errorUtil.ts"; -import { - addIssueToContext, - AsyncParseReturnType, - DIRTY, - INVALID, - isAborted, - isAsync, - isDirty, - isValid, - makeIssue, - OK, - ParseContext, - ParseInput, - ParseParams, - ParsePath, - ParseReturnType, - ParseStatus, - SyncParseReturnType, -} from "./helpers/parseUtil.ts"; -import { partialUtil } from "./helpers/partialUtil.ts"; -import { Primitive } from "./helpers/typeAliases.ts"; -import { getParsedType, objectUtil, util, ZodParsedType } from "./helpers/util.ts"; -import { - IssueData, - StringValidation, - ZodCustomIssue, - ZodError, - ZodErrorMap, - ZodIssue, - ZodIssueCode, - ZodTemplateLiteralUnsupportedCheckError, - ZodTemplateLiteralUnsupportedTypeError, -} from "./ZodError.ts"; - -/////////////////////////////////////// -/////////////////////////////////////// -////////// ////////// -////////// ZodType ////////// -////////// ////////// -/////////////////////////////////////// -/////////////////////////////////////// - -export type RefinementCtx = { - addIssue: (arg: IssueData) => void; - path: (string | number)[]; -}; -export type ZodRawShape = { [k: string]: ZodTypeAny }; -export type ZodTypeAny = ZodType<any, any, any>; -export type TypeOf<T extends ZodType<any, any, any>> = T["_output"]; -export type input<T extends ZodType<any, any, any>> = T["_input"]; -export type output<T extends ZodType<any, any, any>> = T["_output"]; -export type { TypeOf as infer }; - -export type CustomErrorParams = Partial<util.Omit<ZodCustomIssue, "code">>; -export interface ZodTypeDef { - errorMap?: ZodErrorMap; - description?: string; -} - -class ParseInputLazyPath implements ParseInput { - parent: ParseContext; - data: any; - _path: ParsePath; - _key: string | number | (string | number)[]; - _cachedPath: ParsePath = []; - constructor( - parent: ParseContext, - value: any, - path: ParsePath, - key: string | number | (string | number)[] - ) { - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - - return this._cachedPath; - } -} - -const handleResult = <Input, Output>( - ctx: ParseContext, - result: SyncParseReturnType<Output> -): - | { success: true; data: Output } - | { success: false; error: ZodError<Input> } => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - - return { - success: false, - get error() { - if ((this as any)._error) return (this as any)._error as Error; - const error = new ZodError(ctx.common.issues); - (this as any)._error = error; - return (this as any)._error; - }, - }; - } -}; - -export type RawCreateParams = - | { - errorMap?: ZodErrorMap; - invalid_type_error?: string; - required_error?: string; - description?: string; - } - | undefined; -export type ProcessedCreateParams = { - errorMap?: ZodErrorMap; - description?: string; -}; -function processCreateParams(params: RawCreateParams): ProcessedCreateParams { - if (!params) return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error( - `Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.` - ); - } - if (errorMap) return { errorMap: errorMap, description }; - const customMap: ZodErrorMap = (iss, ctx) => { - if (iss.code !== "invalid_type") return { message: ctx.defaultError }; - if (typeof ctx.data === "undefined") { - return { message: required_error ?? ctx.defaultError }; - } - return { message: invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} - -export type SafeParseSuccess<Output> = { - success: true; - data: Output; - error?: never; -}; -export type SafeParseError<Input> = { - success: false; - error: ZodError<Input>; - data?: never; -}; - -export type SafeParseReturnType<Input, Output> = - | SafeParseSuccess<Output> - | SafeParseError<Input>; - -export abstract class ZodType< - Output = any, - Def extends ZodTypeDef = ZodTypeDef, - Input = Output -> { - readonly _type!: Output; - readonly _output!: Output; - readonly _input!: Input; - readonly _def!: Def; - - get description() { - return this._def.description; - } - - abstract _parse(input: ParseInput): ParseReturnType<Output>; - - _getType(input: ParseInput): string { - return getParsedType(input.data); - } - - _getOrReturnCtx( - input: ParseInput, - ctx?: ParseContext | undefined - ): ParseContext { - return ( - ctx || { - common: input.parent.common, - data: input.data, - - parsedType: getParsedType(input.data), - - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - } - ); - } - - _processInputParams(input: ParseInput): { - status: ParseStatus; - ctx: ParseContext; - } { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - - parsedType: getParsedType(input.data), - - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; - } - - _parseSync(input: ParseInput): SyncParseReturnType<Output> { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - - _parseAsync(input: ParseInput): AsyncParseReturnType<Output> { - const result = this._parse(input); - return Promise.resolve(result); - } - - parse(data: unknown, params?: Partial<ParseParams>): Output { - const result = this.safeParse(data, params); - if (result.success) return result.data; - throw result.error; - } - - safeParse( - data: unknown, - params?: Partial<ParseParams> - ): SafeParseReturnType<Input, Output> { - const ctx: ParseContext = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap, - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - - return handleResult(ctx, result); - } - - async parseAsync( - data: unknown, - params?: Partial<ParseParams> - ): Promise<Output> { - const result = await this.safeParseAsync(data, params); - if (result.success) return result.data; - throw result.error; - } - - async safeParseAsync( - data: unknown, - params?: Partial<ParseParams> - ): Promise<SafeParseReturnType<Input, Output>> { - const ctx: ParseContext = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true, - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data), - }; - - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) - ? maybeAsyncResult - : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - - /** Alias of safeParseAsync */ - spa = this.safeParseAsync; - - refine<RefinedOutput extends Output>( - check: (arg: Output) => arg is RefinedOutput, - message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) - ): ZodEffects<this, RefinedOutput, Input>; - refine( - check: (arg: Output) => unknown | Promise<unknown>, - message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) - ): ZodEffects<this, Output, Input>; - refine( - check: (arg: Output) => unknown, - message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) - ): ZodEffects<this, Output, Input> { - const getIssueProperties = (val: Output) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => - ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val), - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - - refinement<RefinedOutput extends Output>( - check: (arg: Output) => arg is RefinedOutput, - refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) - ): ZodEffects<this, RefinedOutput, Input>; - refinement( - check: (arg: Output) => boolean, - refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) - ): ZodEffects<this, Output, Input>; - refinement( - check: (arg: Output) => unknown, - refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) - ): ZodEffects<this, Output, Input> { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue( - typeof refinementData === "function" - ? refinementData(val, ctx) - : refinementData - ); - return false; - } else { - return true; - } - }); - } - - _refinement( - refinement: RefinementEffect<Output>["refinement"] - ): ZodEffects<this, Output, Input> { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement }, - }); - } - - superRefine<RefinedOutput extends Output>( - refinement: (arg: Output, ctx: RefinementCtx) => arg is RefinedOutput - ): ZodEffects<this, RefinedOutput, Input>; - superRefine( - refinement: (arg: Output, ctx: RefinementCtx) => void - ): ZodEffects<this, Output, Input>; - superRefine( - refinement: (arg: Output, ctx: RefinementCtx) => Promise<void> - ): ZodEffects<this, Output, Input>; - superRefine( - refinement: (arg: Output, ctx: RefinementCtx) => unknown | Promise<unknown> - ): ZodEffects<this, Output, Input> { - return this._refinement(refinement); - } - - constructor(def: Def) { - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - } - - optional(): ZodOptional<this> { - return ZodOptional.create(this, this._def) as any; - } - nullable(): ZodNullable<this> { - return ZodNullable.create(this, this._def) as any; - } - nullish(): ZodOptional<ZodNullable<this>> { - return this.nullable().optional(); - } - array(): ZodArray<this> { - return ZodArray.create(this, this._def); - } - promise(): ZodPromise<this> { - return ZodPromise.create(this, this._def); - } - - or<T extends ZodTypeAny>(option: T): ZodUnion<[this, T]> { - return ZodUnion.create([this, option], this._def) as any; - } - - and<T extends ZodTypeAny>(incoming: T): ZodIntersection<this, T> { - return ZodIntersection.create(this, incoming, this._def); - } - - transform<NewOut>( - transform: (arg: Output, ctx: RefinementCtx) => NewOut | Promise<NewOut> - ): ZodEffects<this, NewOut> { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform }, - }) as any; - } - - default(def: util.noUndefined<Input>): ZodDefault<this>; - default(def: () => util.noUndefined<Input>): ZodDefault<this>; - default(def: any) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault, - }) as any; - } - - brand<B extends string | number | symbol>(brand?: B): ZodBranded<this, B>; - brand<B extends string | number | symbol>(): ZodBranded<this, B> { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def), - }); - } - - catch(def: Output): ZodCatch<this>; - catch( - def: (ctx: { error: ZodError; input: Input }) => Output - ): ZodCatch<this>; - catch(def: any) { - const catchValueFunc = typeof def === "function" ? def : () => def; - - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch, - }) as any; - } - - describe(description: string): this { - const This = (this as any).constructor; - return new This({ - ...this._def, - description, - }); - } - - pipe<T extends ZodTypeAny>(target: T): ZodPipeline<this, T> { - return ZodPipeline.create(this, target); - } - readonly(): ZodReadonly<this> { - return ZodReadonly.create(this); - } - - isOptional(): boolean { - return this.safeParse(undefined).success; - } - isNullable(): boolean { - return this.safeParse(null).success; - } -} - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodString ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// -export type IpVersion = "v4" | "v6"; -export type ZodStringCheck = - | { kind: "min"; value: number; message?: string } - | { kind: "max"; value: number; message?: string } - | { kind: "length"; value: number; message?: string } - | { kind: "email"; message?: string } - | { kind: "url"; message?: string } - | { kind: "emoji"; message?: string } - | { kind: "uuid"; message?: string } - | { kind: "cuid"; message?: string } - | { kind: "includes"; value: string; position?: number; message?: string } - | { kind: "cuid2"; message?: string } - | { kind: "ulid"; message?: string } - | { kind: "startsWith"; value: string; message?: string } - | { kind: "endsWith"; value: string; message?: string } - | { kind: "regex"; regex: RegExp; message?: string } - | { kind: "trim"; message?: string } - | { kind: "toLowerCase"; message?: string } - | { kind: "toUpperCase"; message?: string } - | { - kind: "datetime"; - offset: boolean; - precision: number | null; - message?: string; - } - | { kind: "ip"; version?: IpVersion; message?: string }; - -export interface ZodStringDef extends ZodTypeDef { - checks: ZodStringCheck[]; - typeName: ZodFirstPartyTypeKind.ZodString; - coerce: boolean; -} - -const cuidRegex = /^c[^\s-]{8,}$/i; -const cuid2Regex = /^[a-z][a-z0-9]*$/; -const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; -// const uuidRegex = -// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; -const uuidRegex = - /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -// from https://stackoverflow.com/a/46181/1550155 -// old version: too slow, didn't support unicode -// const 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; -//old email regex -// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; -// eslint-disable-next-line -// const emailRegex = -// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; -// const emailRegex = -// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// const emailRegex = -// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; -const emailRegex = - /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -// const emailRegex = -// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; - -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -let emojiRegex: RegExp; - -const ipv4Regex = - /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; - -const ipv6Regex = - /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; - -// Adapted from https://stackoverflow.com/a/3143231 -const datetimeRegex = (args: { precision: number | null; offset: boolean }) => { - if (args.precision) { - if (args.offset) { - return new RegExp( - `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$` - ); - } else { - return new RegExp( - `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$` - ); - } - } else if (args.precision === 0) { - if (args.offset) { - return new RegExp( - `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$` - ); - } else { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); - } - } else { - if (args.offset) { - return new RegExp( - `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$` - ); - } else { - return new RegExp( - `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$` - ); - } - } -}; - -function isValidIP(ip: string, version?: IpVersion) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - - return false; -} - -export class ZodString extends ZodType<string, ZodStringDef> { - _parse(input: ParseInput): ParseReturnType<string> { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - - if (parsedType !== ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext( - ctx, - { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx.parsedType, - } - // - ); - return INVALID; - } - - const status = new ParseStatus(); - let ctx: undefined | ParseContext = undefined; - - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!(input.data as string).includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!(input.data as string).startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!(input.data as string).endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - - return { status: status.value, value: input.data }; - } - - protected _regex( - regex: RegExp, - validation: StringValidation, - message?: errorUtil.ErrMessage - ) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message), - }); - } - - _addCheck(check: ZodStringCheck) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - - email(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - cuid(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - - ip(options?: string | { version?: "v4" | "v6"; message?: string }) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - - datetime( - options?: - | string - | { - message?: string | undefined; - precision?: number | null; - offset?: boolean; - } - ) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - message: options, - }); - } - return this._addCheck({ - kind: "datetime", - precision: - typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - ...errorUtil.errToObj(options?.message), - }); - } - - regex(regex: RegExp, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil.errToObj(message), - }); - } - - includes(value: string, options?: { message?: string; position?: number }) { - return this._addCheck({ - kind: "includes", - value: value, - position: options?.position, - ...errorUtil.errToObj(options?.message), - }); - } - - startsWith(value: string, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil.errToObj(message), - }); - } - - endsWith(value: string, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil.errToObj(message), - }); - } - - min(minLength: number, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message), - }); - } - - max(maxLength: number, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message), - }); - } - - length(len: number, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message), - }); - } - - /** - * @deprecated Use z.string().min(1) instead. - * @see {@link ZodString.min} - */ - nonempty(message?: errorUtil.ErrMessage) { - return this.min(1, errorUtil.errToObj(message)); - } - - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], - }); - } - - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], - }); - } - - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], - }); - } - - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - - get minLength() { - let min: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) min = ch.value; - } - } - return min; - } - get maxLength() { - let max: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) max = ch.value; - } - } - return max; - } - - static create = (params?: RawCreateParams & { coerce?: true }): ZodString => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params), - }); - }; -} - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodNumber ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// -export type ZodNumberCheck = - | { kind: "min"; value: number; inclusive: boolean; message?: string } - | { kind: "max"; value: number; inclusive: boolean; message?: string } - | { kind: "int"; message?: string } - | { kind: "multipleOf"; value: number; message?: string } - | { kind: "finite"; message?: string }; - -// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 -function floatSafeRemainder(val: number, step: number) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / Math.pow(10, decCount); -} - -export interface ZodNumberDef extends ZodTypeDef { - checks: ZodNumberCheck[]; - typeName: ZodFirstPartyTypeKind.ZodNumber; - coerce: boolean; -} - -export class ZodNumber extends ZodType<number, ZodNumberDef> { - _parse(input: ParseInput): ParseReturnType<number> { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx.parsedType, - }); - return INVALID; - } - - let ctx: undefined | ParseContext = undefined; - const status = new ParseStatus(); - - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message, - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - - return { status: status.value, value: input.data }; - } - - static create = ( - params?: RawCreateParams & { coerce?: boolean } - ): ZodNumber => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params), - }); - }; - - gte(value: number, message?: errorUtil.ErrMessage) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - min = this.gte; - - gt(value: number, message?: errorUtil.ErrMessage) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - - lte(value: number, message?: errorUtil.ErrMessage) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - max = this.lte; - - lt(value: number, message?: errorUtil.ErrMessage) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - - protected setLimit( - kind: "min" | "max", - value: number, - inclusive: boolean, - message?: string - ) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - - _addCheck(check: ZodNumberCheck) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - - int(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message), - }); - } - - positive(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); - } - - negative(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); - } - - nonpositive(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); - } - - nonnegative(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); - } - - multipleOf(value: number, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil.toString(message), - }); - } - step = this.multipleOf; - - finite(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message), - }); - } - - safe(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message), - }); - } - - get minValue() { - let min: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) min = ch.value; - } - } - return min; - } - - get maxValue() { - let max: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) max = ch.value; - } - } - return max; - } - - get isInt() { - return !!this._def.checks.find( - (ch) => - ch.kind === "int" || - (ch.kind === "multipleOf" && util.isInteger(ch.value)) - ); - } - - get isFinite() { - let max: number | null = null, - min: number | null = null; - for (const ch of this._def.checks) { - if ( - ch.kind === "finite" || - ch.kind === "int" || - ch.kind === "multipleOf" - ) { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodBigInt ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// -export type ZodBigIntCheck = - | { kind: "min"; value: bigint; inclusive: boolean; message?: string } - | { kind: "max"; value: bigint; inclusive: boolean; message?: string } - | { kind: "multipleOf"; value: bigint; message?: string }; - -export interface ZodBigIntDef extends ZodTypeDef { - checks: ZodBigIntCheck[]; - typeName: ZodFirstPartyTypeKind.ZodBigInt; - coerce: boolean; -} - -export class ZodBigInt extends ZodType<bigint, ZodBigIntDef> { - _parse(input: ParseInput): ParseReturnType<bigint> { - if (this._def.coerce) { - input.data = BigInt(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType, - }); - return INVALID; - } - - let ctx: undefined | ParseContext = undefined; - const status = new ParseStatus(); - - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - - return { status: status.value, value: input.data }; - } - - static create = ( - params?: RawCreateParams & { coerce?: boolean } - ): ZodBigInt => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params), - }); - }; - - gte(value: bigint, message?: errorUtil.ErrMessage) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - min = this.gte; - - gt(value: bigint, message?: errorUtil.ErrMessage) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - - lte(value: bigint, message?: errorUtil.ErrMessage) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - max = this.lte; - - lt(value: bigint, message?: errorUtil.ErrMessage) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - - protected setLimit( - kind: "min" | "max", - value: bigint, - inclusive: boolean, - message?: string - ) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - - _addCheck(check: ZodBigIntCheck) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - - positive(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); - } - - negative(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); - } - - nonpositive(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); - } - - nonnegative(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); - } - - multipleOf(value: bigint, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message), - }); - } - - get minValue() { - let min: bigint | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) min = ch.value; - } - } - return min; - } - - get maxValue() { - let max: bigint | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) max = ch.value; - } - } - return max; - } -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// /////////// -////////// ZodBoolean ////////// -////////// /////////// -////////////////////////////////////////// -////////////////////////////////////////// -export interface ZodBooleanDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodBoolean; - coerce: boolean; -} - -export class ZodBoolean extends ZodType<boolean, ZodBooleanDef> { - _parse(input: ParseInput): ParseReturnType<boolean> { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } - - static create = ( - params?: RawCreateParams & { coerce?: boolean } - ): ZodBoolean => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params), - }); - }; -} - -/////////////////////////////////////// -/////////////////////////////////////// -////////// //////// -////////// ZodDate //////// -////////// //////// -/////////////////////////////////////// -/////////////////////////////////////// -export type ZodDateCheck = - | { kind: "min"; value: number; message?: string } - | { kind: "max"; value: number; message?: string }; -export interface ZodDateDef extends ZodTypeDef { - checks: ZodDateCheck[]; - coerce: boolean; - typeName: ZodFirstPartyTypeKind.ZodDate; -} - -export class ZodDate extends ZodType<Date, ZodDateDef> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - - if (parsedType !== ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx.parsedType, - }); - return INVALID; - } - - if (isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_date, - }); - return INVALID; - } - - const status = new ParseStatus(); - let ctx: undefined | ParseContext = undefined; - - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - - return { - status: status.value, - value: new Date((input.data as Date).getTime()), - }; - } - - _addCheck(check: ZodDateCheck) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - - min(minDate: Date, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message), - }); - } - - max(maxDate: Date, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message), - }); - } - - get minDate() { - let min: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) min = ch.value; - } - } - - return min != null ? new Date(min) : null; - } - - get maxDate() { - let max: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) max = ch.value; - } - } - - return max != null ? new Date(max) : null; - } - - static create = ( - params?: RawCreateParams & { coerce?: boolean } - ): ZodDate => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params), - }); - }; -} - -//////////////////////////////////////////// -//////////////////////////////////////////// -////////// ////////// -////////// ZodSymbol ////////// -////////// ////////// -//////////////////////////////////////////// -//////////////////////////////////////////// -export interface ZodSymbolDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodSymbol; -} - -export class ZodSymbol extends ZodType<symbol, ZodSymbolDef, symbol> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType, - }); - return INVALID; - } - - return OK(input.data); - } - - static create = (params?: RawCreateParams): ZodSymbol => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); - }; -} - -//////////////////////////////////////////// -//////////////////////////////////////////// -////////// ////////// -////////// ZodUndefined ////////// -////////// ////////// -//////////////////////////////////////////// -//////////////////////////////////////////// -export interface ZodUndefinedDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodUndefined; -} - -export class ZodUndefined extends ZodType<undefined, ZodUndefinedDef> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } - params?: RawCreateParams; - - static create = (params?: RawCreateParams): ZodUndefined => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params), - }); - }; -} - -/////////////////////////////////////// -/////////////////////////////////////// -////////// ////////// -////////// ZodNull ////////// -////////// ////////// -/////////////////////////////////////// -/////////////////////////////////////// -export interface ZodNullDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodNull; -} - -export class ZodNull extends ZodType<null, ZodNullDef> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } - static create = (params?: RawCreateParams): ZodNull => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////// -////////////////////////////////////// -////////// ////////// -////////// ZodAny ////////// -////////// ////////// -////////////////////////////////////// -////////////////////////////////////// -export interface ZodAnyDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodAny; -} - -export class ZodAny extends ZodType<any, ZodAnyDef> { - // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. - _any = true as const; - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - return OK(input.data); - } - static create = (params?: RawCreateParams): ZodAny => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodUnknown ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// -export interface ZodUnknownDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodUnknown; -} - -export class ZodUnknown extends ZodType<unknown, ZodUnknownDef> { - // required - _unknown = true as const; - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - return OK(input.data); - } - - static create = (params?: RawCreateParams): ZodUnknown => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); - }; -} - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// ZodNever ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -export interface ZodNeverDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodNever; -} - -export class ZodNever extends ZodType<never, ZodNeverDef> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType, - }); - return INVALID; - } - static create = (params?: RawCreateParams): ZodNever => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); - }; -} - -/////////////////////////////////////// -/////////////////////////////////////// -////////// ////////// -////////// ZodVoid ////////// -////////// ////////// -/////////////////////////////////////// -/////////////////////////////////////// -export interface ZodVoidDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodVoid; -} - -export class ZodVoid extends ZodType<void, ZodVoidDef> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } - - static create = (params?: RawCreateParams): ZodVoid => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params), - }); - }; -} - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// ZodArray ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -export interface ZodArrayDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - type: T; - typeName: ZodFirstPartyTypeKind.ZodArray; - exactLength: { value: number; message?: string } | null; - minLength: { value: number; message?: string } | null; - maxLength: { value: number; message?: string } | null; -} - -export type ArrayCardinality = "many" | "atleastone"; -export type arrayOutputType< - T extends ZodTypeAny, - Cardinality extends ArrayCardinality = "many" -> = Cardinality extends "atleastone" - ? [T["_output"], ...T["_output"][]] - : T["_output"][]; - -export class ZodArray< - T extends ZodTypeAny, - Cardinality extends ArrayCardinality = "many" -> extends ZodType< - arrayOutputType<T, Cardinality>, - ZodArrayDef<T>, - Cardinality extends "atleastone" - ? [T["_input"], ...T["_input"][]] - : T["_input"][] -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx, status } = this._processInputParams(input); - - const def = this._def; - - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return INVALID; - } - - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined) as number, - maximum: (tooBig ? def.exactLength.value : undefined) as number, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } - } - - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); - } - } - - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); - } - } - - if (ctx.common.async) { - return Promise.all( - ([...ctx.data] as any[]).map((item, i) => { - return def.type._parseAsync( - new ParseInputLazyPath(ctx, item, ctx.path, i) - ); - }) - ).then((result) => { - return ParseStatus.mergeArray(status, result); - }); - } - - const result = ([...ctx.data] as any[]).map((item, i) => { - return def.type._parseSync( - new ParseInputLazyPath(ctx, item, ctx.path, i) - ); - }); - - return ParseStatus.mergeArray(status, result); - } - - get element() { - return this._def.type; - } - - min(minLength: number, message?: errorUtil.ErrMessage): this { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) }, - }) as any; - } - - max(maxLength: number, message?: errorUtil.ErrMessage): this { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) }, - }) as any; - } - - length(len: number, message?: errorUtil.ErrMessage): this { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) }, - }) as any; - } - - nonempty(message?: errorUtil.ErrMessage): ZodArray<T, "atleastone"> { - return this.min(1, message) as any; - } - - static create = <T extends ZodTypeAny>( - schema: T, - params?: RawCreateParams - ): ZodArray<T> => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params), - }); - }; -} - -export type ZodNonEmptyArray<T extends ZodTypeAny> = ZodArray<T, "atleastone">; - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodObject ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// - -export type UnknownKeysParam = "passthrough" | "strict" | "strip"; - -export interface ZodObjectDef< - T extends ZodRawShape = ZodRawShape, - UnknownKeys extends UnknownKeysParam = UnknownKeysParam, - Catchall extends ZodTypeAny = ZodTypeAny -> extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodObject; - shape: () => T; - catchall: Catchall; - unknownKeys: UnknownKeys; -} - -export type mergeTypes<A, B> = { - [k in keyof A | keyof B]: k extends keyof B - ? B[k] - : k extends keyof A - ? A[k] - : never; -}; - -export type objectOutputType< - Shape extends ZodRawShape, - Catchall extends ZodTypeAny, - UnknownKeys extends UnknownKeysParam = UnknownKeysParam -> = objectUtil.flatten< - objectUtil.addQuestionMarks<baseObjectOutputType<Shape>> -> & - CatchallOutput<Catchall> & - PassthroughType<UnknownKeys>; - -export type baseObjectOutputType<Shape extends ZodRawShape> = { - [k in keyof Shape]: Shape[k]["_output"]; -}; - -export type objectInputType< - Shape extends ZodRawShape, - Catchall extends ZodTypeAny, - UnknownKeys extends UnknownKeysParam = UnknownKeysParam -> = objectUtil.flatten<baseObjectInputType<Shape>> & - CatchallInput<Catchall> & - PassthroughType<UnknownKeys>; -export type baseObjectInputType<Shape extends ZodRawShape> = - objectUtil.addQuestionMarks<{ - [k in keyof Shape]: Shape[k]["_input"]; - }>; - -export type CatchallOutput<T extends ZodType> = ZodType extends T - ? unknown - : { [k: string]: T["_output"] }; - -export type CatchallInput<T extends ZodType> = ZodType extends T - ? unknown - : { [k: string]: T["_input"] }; - -export type PassthroughType<T extends UnknownKeysParam> = - T extends "passthrough" ? { [k: string]: unknown } : unknown; - -export type deoptional<T extends ZodTypeAny> = T extends ZodOptional<infer U> - ? deoptional<U> - : T extends ZodNullable<infer U> - ? ZodNullable<deoptional<U>> - : T; - -export type SomeZodObject = ZodObject< - ZodRawShape, - UnknownKeysParam, - ZodTypeAny ->; - -export type noUnrecognized<Obj extends object, Shape extends object> = { - [k in keyof Obj]: k extends keyof Shape ? Obj[k] : never; -}; - -function deepPartialify(schema: ZodTypeAny): any { - if (schema instanceof ZodObject) { - const newShape: any = {}; - - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, - }) as any; - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create( - schema.items.map((item: any) => deepPartialify(item)) - ); - } else { - return schema; - } -} - -export class ZodObject< - T extends ZodRawShape, - UnknownKeys extends UnknownKeysParam = UnknownKeysParam, - Catchall extends ZodTypeAny = ZodTypeAny, - Output = objectOutputType<T, Catchall, UnknownKeys>, - Input = objectInputType<T, Catchall, UnknownKeys> -> extends ZodType<Output, ZodObjectDef<T, UnknownKeys, Catchall>, Input> { - private _cached: { shape: T; keys: string[] } | null = null; - - _getCached(): { shape: T; keys: string[] } { - if (this._cached !== null) return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - return (this._cached = { shape, keys }); - } - - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - - const { status, ctx } = this._processInputParams(input); - - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys: string[] = []; - - if ( - !( - this._def.catchall instanceof ZodNever && - this._def.unknownKeys === "strip" - ) - ) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - - const pairs: { - key: ParseReturnType<any>; - value: ParseReturnType<any>; - alwaysSet?: boolean; - }[] = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - ), - alwaysSet: key in ctx.data, - }); - } - - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } - } else if (unknownKeys === "strip") { - } else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - // run catchall validation - const catchall = this._def.catchall; - - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data, - }); - } - } - - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs: any[] = []; - for (const pair of pairs) { - const key = await pair.key; - syncPairs.push({ - key, - value: await pair.value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs as any); - } - } - - get shape() { - return this._def.shape(); - } - - strict(message?: errorUtil.ErrMessage): ZodObject<T, "strict", Catchall> { - errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - const defaultError = - this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError, - }; - return { - message: defaultError, - }; - }, - } - : {}), - }) as any; - } - - strip(): ZodObject<T, "strip", Catchall> { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }) as any; - } - - passthrough(): ZodObject<T, "passthrough", Catchall> { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", - }) as any; - } - - /** - * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. - * If you want to pass through unknown properties, use `.passthrough()` instead. - */ - nonstrict = this.passthrough; - - // const AugmentFactory = - // <Def extends ZodObjectDef>(def: Def) => - // <Augmentation extends ZodRawShape>( - // augmentation: Augmentation - // ): ZodObject< - // extendShape<ReturnType<Def["shape"]>, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend<Augmentation extends ZodRawShape>( - augmentation: Augmentation - ): ZodObject<objectUtil.extendShape<T, Augmentation>, UnknownKeys, Catchall> { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), - }) as any; - } - // extend< - // Augmentation extends ZodRawShape, - // NewOutput extends util.flatten<{ - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }>, - // NewInput extends util.flatten<{ - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // }> - // >( - // augmentation: Augmentation - // ): ZodObject< - // extendShape<T, Augmentation>, - // UnknownKeys, - // Catchall, - // NewOutput, - // NewInput - // > { - // return new ZodObject({ - // ...this._def, - // shape: () => ({ - // ...this._def.shape(), - // ...augmentation, - // }), - // }) as any; - // } - /** - * @deprecated Use `.extend` instead - * */ - augment = this.extend; - - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge<Incoming extends AnyZodObject, Augmentation extends Incoming["shape"]>( - merging: Incoming - ): ZodObject< - objectUtil.extendShape<T, Augmentation>, - Incoming["_def"]["unknownKeys"], - Incoming["_def"]["catchall"] - > { - const merged: any = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, - }) as any; - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - - setKey<Key extends string, Schema extends ZodTypeAny>( - key: Key, - schema: Schema - ): ZodObject<T & { [k in Key]: Schema }, UnknownKeys, Catchall> { - return this.augment({ [key]: schema }) as any; - } - // merge<Incoming extends AnyZodObject>( - // merging: Incoming - // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => { - // ZodObject< - // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - - catchall<Index extends ZodTypeAny>( - index: Index - ): ZodObject<T, UnknownKeys, Index> { - return new ZodObject({ - ...this._def, - catchall: index, - }) as any; - } - - pick<Mask extends { [k in keyof T]?: true }>( - mask: Mask - ): ZodObject<Pick<T, Extract<keyof T, keyof Mask>>, UnknownKeys, Catchall> { - const shape: any = {}; - - util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - }); - - return new ZodObject({ - ...this._def, - shape: () => shape, - }) as any; - } - - omit<Mask extends { [k in keyof T]?: true }>( - mask: Mask - ): ZodObject<Omit<T, keyof Mask>, UnknownKeys, Catchall> { - const shape: any = {}; - - util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - }); - - return new ZodObject({ - ...this._def, - shape: () => shape, - }) as any; - } - - /** - * @deprecated - */ - deepPartial(): partialUtil.DeepPartial<this> { - return deepPartialify(this) as any; - } - - partial(): ZodObject< - { [k in keyof T]: ZodOptional<T[k]> }, - UnknownKeys, - Catchall - >; - partial<Mask extends { [k in keyof T]?: true }>( - mask: Mask - ): ZodObject< - objectUtil.noNever<{ - [k in keyof T]: k extends keyof Mask ? ZodOptional<T[k]> : T[k]; - }>, - UnknownKeys, - Catchall - >; - partial(mask?: any) { - const newShape: any = {}; - - util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - }); - - return new ZodObject({ - ...this._def, - shape: () => newShape, - }) as any; - } - - required(): ZodObject< - { [k in keyof T]: deoptional<T[k]> }, - UnknownKeys, - Catchall - >; - required<Mask extends { [k in keyof T]?: true }>( - mask: Mask - ): ZodObject< - objectUtil.noNever<{ - [k in keyof T]: k extends keyof Mask ? deoptional<T[k]> : T[k]; - }>, - UnknownKeys, - Catchall - >; - required(mask?: any) { - const newShape: any = {}; - - util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - - while (newField instanceof ZodOptional) { - newField = (newField as ZodOptional<any>)._def.innerType; - } - - newShape[key] = newField; - } - }); - - return new ZodObject({ - ...this._def, - shape: () => newShape, - }) as any; - } - - keyof(): ZodEnum<enumUtil.UnionToTupleString<keyof T>> { - return createZodEnum( - util.objectKeys(this.shape) as [string, ...string[]] - ) as any; - } - - static create = <T extends ZodRawShape>( - shape: T, - params?: RawCreateParams - ): ZodObject<T, "strip"> => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }) as any; - }; - - static strictCreate = <T extends ZodRawShape>( - shape: T, - params?: RawCreateParams - ): ZodObject<T, "strict"> => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }) as any; - }; - - static lazycreate = <T extends ZodRawShape>( - shape: () => T, - params?: RawCreateParams - ): ZodObject<T, "strip"> => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }) as any; - }; -} - -export type AnyZodObject = ZodObject<any, any, any>; - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// ZodUnion ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -export type ZodUnionOptions = Readonly<[ZodTypeAny, ...ZodTypeAny[]]>; -export interface ZodUnionDef< - T extends ZodUnionOptions = Readonly< - [ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]] - > -> extends ZodTypeDef { - options: T; - typeName: ZodFirstPartyTypeKind.ZodUnion; -} - -export class ZodUnion<T extends ZodUnionOptions> extends ZodType< - T[number]["_output"], - ZodUnionDef<T>, - T[number]["_input"] -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - - function handleResults( - results: { ctx: ParseContext; result: SyncParseReturnType<any> }[] - ) { - // return first issue-free validation if it exists - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - - for (const result of results) { - if (result.result.status === "dirty") { - // add issues from dirty option - - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - - // return invalid - const unionErrors = results.map( - (result) => new ZodError(result.ctx.common.issues) - ); - - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, - }); - return INVALID; - } - - if (ctx.common.async) { - return Promise.all( - options.map(async (option) => { - const childCtx: ParseContext = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - }) - ).then(handleResults); - } else { - let dirty: undefined | { result: DIRTY<any>; ctx: ParseContext } = - undefined; - const issues: ZodIssue[][] = []; - for (const option of options) { - const childCtx: ParseContext = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - - const unionErrors = issues.map((issues) => new ZodError(issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, - }); - - return INVALID; - } - } - - get options() { - return this._def.options; - } - - static create = < - T extends Readonly<[ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]]> - >( - types: T, - params?: RawCreateParams - ): ZodUnion<T> => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); - }; -} - -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -////////// ////////// -////////// ZodDiscriminatedUnion ////////// -////////// ////////// -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// - -const getDiscriminator = <T extends ZodTypeAny>(type: T): Primitive[] => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - // eslint-disable-next-line ban/ban - return util.objectValues(type.enum as any); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [undefined]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; - -export type ZodDiscriminatedUnionOption<Discriminator extends string> = - ZodObject< - { [key in Discriminator]: ZodTypeAny } & ZodRawShape, - UnknownKeysParam, - ZodTypeAny - >; - -export interface ZodDiscriminatedUnionDef< - Discriminator extends string, - Options extends ZodDiscriminatedUnionOption<string>[] = ZodDiscriminatedUnionOption<string>[] -> extends ZodTypeDef { - discriminator: Discriminator; - options: Options; - optionsMap: Map<Primitive, ZodDiscriminatedUnionOption<any>>; - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion; -} - -export class ZodDiscriminatedUnion< - Discriminator extends string, - Options extends ZodDiscriminatedUnionOption<Discriminator>[] -> extends ZodType< - output<Options[number]>, - ZodDiscriminatedUnionDef<Discriminator, Options>, - input<Options[number]> -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - - const discriminator = this.discriminator; - - const discriminatorValue: string = ctx.data[discriminator]; - - const option = this.optionsMap.get(discriminatorValue); - - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], - }); - return INVALID; - } - - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }) as any; - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }) as any; - } - } - - get discriminator() { - return this._def.discriminator; - } - - get options() { - return this._def.options; - } - - get optionsMap() { - return this._def.optionsMap; - } - - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create< - Discriminator extends string, - Types extends [ - ZodDiscriminatedUnionOption<Discriminator>, - ...ZodDiscriminatedUnionOption<Discriminator>[] - ] - >( - discriminator: Discriminator, - options: Types, - params?: RawCreateParams - ): ZodDiscriminatedUnion<Discriminator, Types> { - // Get all the valid discriminator values - const optionsMap: Map<Primitive, Types[number]> = new Map(); - - // try { - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error( - `A discriminator value for key \`${discriminator}\` could not be extracted from all schema options` - ); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error( - `Discriminator property ${String( - discriminator - )} has duplicate value ${String(value)}` - ); - } - - optionsMap.set(value, type); - } - } - - return new ZodDiscriminatedUnion< - Discriminator, - // DiscriminatorValue, - Types - >({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), - }); - } -} - -/////////////////////////////////////////////// -/////////////////////////////////////////////// -////////// ////////// -////////// ZodIntersection ////////// -////////// ////////// -/////////////////////////////////////////////// -/////////////////////////////////////////////// -export interface ZodIntersectionDef< - T extends ZodTypeAny = ZodTypeAny, - U extends ZodTypeAny = ZodTypeAny -> extends ZodTypeDef { - left: T; - right: U; - typeName: ZodFirstPartyTypeKind.ZodIntersection; -} - -function mergeValues( - a: any, - b: any -): { valid: true; data: any } | { valid: false } { - const aType = getParsedType(a); - const bType = getParsedType(b); - - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util - .objectKeys(a) - .filter((key) => bKeys.indexOf(key) !== -1); - - const newObj: any = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - - const newArray: unknown[] = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - - if (!sharedValue.valid) { - return { valid: false }; - } - - newArray.push(sharedValue.data); - } - - return { valid: true, data: newArray }; - } else if ( - aType === ZodParsedType.date && - bType === ZodParsedType.date && - +a === +b - ) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} - -export class ZodIntersection< - T extends ZodTypeAny, - U extends ZodTypeAny -> extends ZodType< - T["_output"] & U["_output"], - ZodIntersectionDef<T, U>, - T["_input"] & U["_input"] -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - const handleParsed = ( - parsedLeft: SyncParseReturnType, - parsedRight: SyncParseReturnType - ): SyncParseReturnType<T & U> => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - - const merged = mergeValues(parsedLeft.value, parsedRight.value); - - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types, - }); - return INVALID; - } - - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - - return { status: status.value, value: merged.data as any }; - }; - - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]: any) => handleParsed(left, right)); - } else { - return handleParsed( - this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }) - ); - } - } - - static create = <T extends ZodTypeAny, U extends ZodTypeAny>( - left: T, - right: U, - params?: RawCreateParams - ): ZodIntersection<T, U> => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params), - }); - }; -} - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// ZodTuple ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -export type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; -export type AssertArray<T> = T extends any[] ? T : never; -export type OutputTypeOfTuple<T extends ZodTupleItems | []> = AssertArray<{ - [k in keyof T]: T[k] extends ZodType<any, any> ? T[k]["_output"] : never; -}>; -export type OutputTypeOfTupleWithRest< - T extends ZodTupleItems | [], - Rest extends ZodTypeAny | null = null -> = Rest extends ZodTypeAny - ? [...OutputTypeOfTuple<T>, ...Rest["_output"][]] - : OutputTypeOfTuple<T>; - -export type InputTypeOfTuple<T extends ZodTupleItems | []> = AssertArray<{ - [k in keyof T]: T[k] extends ZodType<any, any> ? T[k]["_input"] : never; -}>; -export type InputTypeOfTupleWithRest< - T extends ZodTupleItems | [], - Rest extends ZodTypeAny | null = null -> = Rest extends ZodTypeAny - ? [...InputTypeOfTuple<T>, ...Rest["_input"][]] - : InputTypeOfTuple<T>; - -export interface ZodTupleDef< - T extends ZodTupleItems | [] = ZodTupleItems, - Rest extends ZodTypeAny | null = null -> extends ZodTypeDef { - items: T; - rest: Rest; - typeName: ZodFirstPartyTypeKind.ZodTuple; -} - -export type AnyZodTuple = ZodTuple< - [ZodTypeAny, ...ZodTypeAny[]] | [], - ZodTypeAny | null ->; -export class ZodTuple< - T extends [ZodTypeAny, ...ZodTypeAny[]] | [] = [ZodTypeAny, ...ZodTypeAny[]], - Rest extends ZodTypeAny | null = null -> extends ZodType< - OutputTypeOfTupleWithRest<T, Rest>, - ZodTupleDef<T, Rest>, - InputTypeOfTupleWithRest<T, Rest> -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return INVALID; - } - - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - - return INVALID; - } - - const rest = this._def.rest; - - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - - const items = ([...ctx.data] as any[]) - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) return null as any as SyncParseReturnType<any>; - return schema._parse( - new ParseInputLazyPath(ctx, item, ctx.path, itemIndex) - ); - }) - .filter((x) => !!x); // filter nulls - - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items as SyncParseReturnType[]); - } - } - - get items() { - return this._def.items; - } - - rest<Rest extends ZodTypeAny>(rest: Rest): ZodTuple<T, Rest> { - return new ZodTuple({ - ...this._def, - rest, - }); - } - - static create = <T extends [ZodTypeAny, ...ZodTypeAny[]] | []>( - schemas: T, - params?: RawCreateParams - ): ZodTuple<T, null> => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params), - }); - }; -} - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodRecord ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// -export interface ZodRecordDef< - Key extends KeySchema = ZodString, - Value extends ZodTypeAny = ZodTypeAny -> extends ZodTypeDef { - valueType: Value; - keyType: Key; - typeName: ZodFirstPartyTypeKind.ZodRecord; -} - -export type KeySchema = ZodType<string | number | symbol, any, any>; -export type RecordType<K extends string | number | symbol, V> = [ - string -] extends [K] - ? Record<K, V> - : [number] extends [K] - ? Record<K, V> - : [symbol] extends [K] - ? Record<K, V> - : [BRAND<string | number | symbol>] extends [K] - ? Record<K, V> - : Partial<Record<K, V>>; -export class ZodRecord< - Key extends KeySchema = ZodString, - Value extends ZodTypeAny = ZodTypeAny -> extends ZodType< - RecordType<Key["_output"], Value["_output"]>, - ZodRecordDef<Key, Value>, - RecordType<Key["_input"], Value["_input"]> -> { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - - const pairs: { - key: ParseReturnType<any>; - value: ParseReturnType<any>; - }[] = []; - - const keyType = this._def.keyType; - const valueType = this._def.valueType; - - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse( - new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key) - ), - }); - } - - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs as any); - } - } - - get element() { - return this._def.valueType; - } - - static create<Value extends ZodTypeAny>( - valueType: Value, - params?: RawCreateParams - ): ZodRecord<ZodString, Value>; - static create<Keys extends KeySchema, Value extends ZodTypeAny>( - keySchema: Keys, - valueType: Value, - params?: RawCreateParams - ): ZodRecord<Keys, Value>; - static create(first: any, second?: any, third?: any): ZodRecord<any, any> { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); - } - - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), - }); - } -} - -////////////////////////////////////// -////////////////////////////////////// -////////// ////////// -////////// ZodMap ////////// -////////// ////////// -////////////////////////////////////// -////////////////////////////////////// -export interface ZodMapDef< - Key extends ZodTypeAny = ZodTypeAny, - Value extends ZodTypeAny = ZodTypeAny -> extends ZodTypeDef { - valueType: Value; - keyType: Key; - typeName: ZodFirstPartyTypeKind.ZodMap; -} - -export class ZodMap< - Key extends ZodTypeAny = ZodTypeAny, - Value extends ZodTypeAny = ZodTypeAny -> extends ZodType< - Map<Key["_output"], Value["_output"]>, - ZodMapDef<Key, Value>, - Map<Key["_input"], Value["_input"]> -> { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType, - }); - return INVALID; - } - - const keyType = this._def.keyType; - const valueType = this._def.valueType; - - const pairs = [...(ctx.data as Map<unknown, unknown>).entries()].map( - ([key, value], index) => { - return { - key: keyType._parse( - new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"]) - ), - value: valueType._parse( - new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]) - ), - }; - } - ); - - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key as SyncParseReturnType; - const value = pair.value as SyncParseReturnType; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } - static create = < - Key extends ZodTypeAny = ZodTypeAny, - Value extends ZodTypeAny = ZodTypeAny - >( - keyType: Key, - valueType: Value, - params?: RawCreateParams - ): ZodMap<Key, Value> => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////// -////////////////////////////////////// -////////// ////////// -////////// ZodSet ////////// -////////// ////////// -////////////////////////////////////// -////////////////////////////////////// -export interface ZodSetDef<Value extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - valueType: Value; - typeName: ZodFirstPartyTypeKind.ZodSet; - minSize: { value: number; message?: string } | null; - maxSize: { value: number; message?: string } | null; -} - -export class ZodSet<Value extends ZodTypeAny = ZodTypeAny> extends ZodType< - Set<Value["_output"]>, - ZodSetDef<Value>, - Set<Value["_input"]> -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType, - }); - return INVALID; - } - - const def = this._def; - - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } - } - - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); - } - } - - const valueType = this._def.valueType; - - function finalizeSet(elements: SyncParseReturnType<any>[]) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") return INVALID; - if (element.status === "dirty") status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - - const elements = [...(ctx.data as Set<unknown>).values()].map((item, i) => - valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)) - ); - - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } else { - return finalizeSet(elements as SyncParseReturnType[]); - } - } - - min(minSize: number, message?: errorUtil.ErrMessage): this { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) }, - }) as any; - } - - max(maxSize: number, message?: errorUtil.ErrMessage): this { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) }, - }) as any; - } - - size(size: number, message?: errorUtil.ErrMessage): this { - return this.min(size, message).max(size, message) as any; - } - - nonempty(message?: errorUtil.ErrMessage): ZodSet<Value> { - return this.min(1, message) as any; - } - - static create = <Value extends ZodTypeAny = ZodTypeAny>( - valueType: Value, - params?: RawCreateParams - ): ZodSet<Value> => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params), - }); - }; -} - -/////////////////////////////////////////// -/////////////////////////////////////////// -////////// ////////// -////////// ZodFunction ////////// -////////// ////////// -/////////////////////////////////////////// -/////////////////////////////////////////// -export interface ZodFunctionDef< - Args extends ZodTuple<any, any> = ZodTuple<any, any>, - Returns extends ZodTypeAny = ZodTypeAny -> extends ZodTypeDef { - args: Args; - returns: Returns; - typeName: ZodFirstPartyTypeKind.ZodFunction; -} - -export type OuterTypeOfFunction< - Args extends ZodTuple<any, any>, - Returns extends ZodTypeAny -> = Args["_input"] extends Array<any> - ? (...args: Args["_input"]) => Returns["_output"] - : never; - -export type InnerTypeOfFunction< - Args extends ZodTuple<any, any>, - Returns extends ZodTypeAny -> = Args["_output"] extends Array<any> - ? (...args: Args["_output"]) => Returns["_input"] - : never; - -export class ZodFunction< - Args extends ZodTuple<any, any>, - Returns extends ZodTypeAny -> extends ZodType< - OuterTypeOfFunction<Args, Returns>, - ZodFunctionDef<Args, Returns>, - InnerTypeOfFunction<Args, Returns> -> { - _parse(input: ParseInput): ParseReturnType<any> { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType, - }); - return INVALID; - } - - function makeArgsIssue(args: any, error: ZodError): ZodIssue { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - defaultErrorMap, - ].filter((x) => !!x) as ZodErrorMap[], - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error, - }, - }); - } - - function makeReturnsIssue(returns: any, error: ZodError): ZodIssue { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - defaultErrorMap, - ].filter((x) => !!x) as ZodErrorMap[], - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, - }); - } - - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - - if (this._def.returns instanceof ZodPromise) { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(async function (this: any, ...args: any[]) { - const error = new ZodError([]); - const parsedArgs = await me._def.args - .parseAsync(args, params) - .catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs as any); - const parsedReturns = await ( - me._def.returns as unknown as ZodPromise<ZodTypeAny> - )._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(function (this: any, ...args: any[]) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }) as any; - } - } - - parameters() { - return this._def.args; - } - - returnType() { - return this._def.returns; - } - - args<Items extends Parameters<(typeof ZodTuple)["create"]>[0]>( - ...items: Items - ): ZodFunction<ZodTuple<Items, ZodUnknown>, Returns> { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) as any, - }); - } - - returns<NewReturnType extends ZodType<any, any>>( - returnType: NewReturnType - ): ZodFunction<Args, NewReturnType> { - return new ZodFunction({ - ...this._def, - returns: returnType, - }); - } - - implement<F extends InnerTypeOfFunction<Args, Returns>>( - func: F - ): ReturnType<F> extends Returns["_output"] - ? (...args: Args["_input"]) => ReturnType<F> - : OuterTypeOfFunction<Args, Returns> { - const validatedFunc = this.parse(func); - return validatedFunc as any; - } - - strictImplement( - func: InnerTypeOfFunction<Args, Returns> - ): InnerTypeOfFunction<Args, Returns> { - const validatedFunc = this.parse(func); - return validatedFunc as any; - } - - validate = this.implement; - - static create(): ZodFunction<ZodTuple<[], ZodUnknown>, ZodUnknown>; - static create<T extends AnyZodTuple = ZodTuple<[], ZodUnknown>>( - args: T - ): ZodFunction<T, ZodUnknown>; - static create<T extends AnyZodTuple, U extends ZodTypeAny>( - args: T, - returns: U - ): ZodFunction<T, U>; - static create< - T extends AnyZodTuple = ZodTuple<[], ZodUnknown>, - U extends ZodTypeAny = ZodUnknown - >(args: T, returns: U, params?: RawCreateParams): ZodFunction<T, U>; - static create( - args?: AnyZodTuple, - returns?: ZodTypeAny, - params?: RawCreateParams - ) { - return new ZodFunction({ - args: (args - ? args - : ZodTuple.create([]).rest(ZodUnknown.create())) as any, - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), - }) as any; - } -} - -/////////////////////////////////////// -/////////////////////////////////////// -////////// ////////// -////////// ZodLazy ////////// -////////// ////////// -/////////////////////////////////////// -/////////////////////////////////////// -export interface ZodLazyDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - getter: () => T; - typeName: ZodFirstPartyTypeKind.ZodLazy; -} - -export class ZodLazy<T extends ZodTypeAny> extends ZodType< - output<T>, - ZodLazyDef<T>, - input<T> -> { - get schema(): T { - return this._def.getter(); - } - - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } - - static create = <T extends ZodTypeAny>( - getter: () => T, - params?: RawCreateParams - ): ZodLazy<T> => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodLiteral ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// -export interface ZodLiteralDef<T = any> extends ZodTypeDef { - value: T; - typeName: ZodFirstPartyTypeKind.ZodLiteral; -} - -export class ZodLiteral<T> extends ZodType<T, ZodLiteralDef<T>> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - - get value() { - return this._def.value; - } - - static create = <T extends Primitive>( - value: T, - params?: RawCreateParams - ): ZodLiteral<T> => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); - }; -} - -/////////////////////////////////////// -/////////////////////////////////////// -////////// ////////// -////////// ZodEnum ////////// -////////// ////////// -/////////////////////////////////////// -/////////////////////////////////////// -export type ArrayKeys = keyof any[]; -export type Indices<T> = Exclude<keyof T, ArrayKeys>; - -export type EnumValues = [string, ...string[]]; - -export type Values<T extends EnumValues> = { - [k in T[number]]: k; -}; - -export interface ZodEnumDef<T extends EnumValues = EnumValues> - extends ZodTypeDef { - values: T; - typeName: ZodFirstPartyTypeKind.ZodEnum; -} - -export type Writeable<T> = { -readonly [P in keyof T]: T[P] }; - -export type FilterEnum<Values, ToExclude> = Values extends [] - ? [] - : Values extends [infer Head, ...infer Rest] - ? Head extends ToExclude - ? FilterEnum<Rest, ToExclude> - : [Head, ...FilterEnum<Rest, ToExclude>] - : never; - -export type typecast<A, T> = A extends T ? A : never; - -function createZodEnum<U extends string, T extends Readonly<[U, ...U[]]>>( - values: T, - params?: RawCreateParams -): ZodEnum<Writeable<T>>; -function createZodEnum<U extends string, T extends [U, ...U[]]>( - values: T, - params?: RawCreateParams -): ZodEnum<T>; -function createZodEnum( - values: [string, ...string[]], - params?: RawCreateParams -) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); -} - -export class ZodEnum<T extends [string, ...string[]]> extends ZodType< - T[number], - ZodEnumDef<T> -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues) as "string", - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return INVALID; - } - - if (this._def.values.indexOf(input.data) === -1) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return INVALID; - } - return OK(input.data); - } - - get options() { - return this._def.values; - } - - get enum(): Values<T> { - const enumValues: any = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues as any; - } - - get Values(): Values<T> { - const enumValues: any = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues as any; - } - - get Enum(): Values<T> { - const enumValues: any = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues as any; - } - - extract<ToExtract extends readonly [T[number], ...T[number][]]>( - values: ToExtract, - newDef: RawCreateParams = this._def - ): ZodEnum<Writeable<ToExtract>> { - return ZodEnum.create(values, { - ...this._def, - ...newDef, - }) as any; - } - - exclude<ToExclude extends readonly [T[number], ...T[number][]]>( - values: ToExclude, - newDef: RawCreateParams = this._def - ): ZodEnum< - typecast<Writeable<FilterEnum<T, ToExclude[number]>>, [string, ...string[]]> - > { - return ZodEnum.create( - this.options.filter((opt) => !values.includes(opt)) as FilterEnum< - T, - ToExclude[number] - >, - { - ...this._def, - ...newDef, - } - ) as any; - } - - static create = createZodEnum; -} - -///////////////////////////////////////////// -///////////////////////////////////////////// -////////// ////////// -////////// ZodNativeEnum ////////// -////////// ////////// -///////////////////////////////////////////// -///////////////////////////////////////////// -export interface ZodNativeEnumDef<T extends EnumLike = EnumLike> - extends ZodTypeDef { - values: T; - typeName: ZodFirstPartyTypeKind.ZodNativeEnum; -} - -export type EnumLike = { [k: string]: string | number; [nu: number]: string }; - -export class ZodNativeEnum<T extends EnumLike> extends ZodType< - T[keyof T], - ZodNativeEnumDef<T> -> { - _parse(input: ParseInput): ParseReturnType<T[keyof T]> { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - - const ctx = this._getOrReturnCtx(input); - if ( - ctx.parsedType !== ZodParsedType.string && - ctx.parsedType !== ZodParsedType.number - ) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues) as "string", - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return INVALID; - } - - if (nativeEnumValues.indexOf(input.data) === -1) { - const expectedValues = util.objectValues(nativeEnumValues); - - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return INVALID; - } - return OK(input.data as any); - } - - get enum() { - return this._def.values; - } - - static create = <T extends EnumLike>( - values: T, - params?: RawCreateParams - ): ZodNativeEnum<T> => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodPromise ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// -export interface ZodPromiseDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - type: T; - typeName: ZodFirstPartyTypeKind.ZodPromise; -} - -export class ZodPromise<T extends ZodTypeAny> extends ZodType< - Promise<T["_output"]>, - ZodPromiseDef<T>, - Promise<T["_input"]> -> { - unwrap() { - return this._def.type; - } - - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - if ( - ctx.parsedType !== ZodParsedType.promise && - ctx.common.async === false - ) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType, - }); - return INVALID; - } - - const promisified = - ctx.parsedType === ZodParsedType.promise - ? ctx.data - : Promise.resolve(ctx.data); - - return OK( - promisified.then((data: any) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - }) - ); - } - - static create = <T extends ZodTypeAny>( - schema: T, - params?: RawCreateParams - ): ZodPromise<T> => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////////////// -////////////////////////////////////////////// -////////// ////////// -////////// ZodEffects ////////// -////////// ////////// -////////////////////////////////////////////// -////////////////////////////////////////////// - -export type Refinement<T> = (arg: T, ctx: RefinementCtx) => any; -export type SuperRefinement<T> = ( - arg: T, - ctx: RefinementCtx -) => void | Promise<void>; - -export type RefinementEffect<T> = { - type: "refinement"; - refinement: (arg: T, ctx: RefinementCtx) => any; -}; -export type TransformEffect<T> = { - type: "transform"; - transform: (arg: T, ctx: RefinementCtx) => any; -}; -export type PreprocessEffect<T> = { - type: "preprocess"; - transform: (arg: T, ctx: RefinementCtx) => any; -}; -export type Effect<T> = - | RefinementEffect<T> - | TransformEffect<T> - | PreprocessEffect<T>; - -export interface ZodEffectsDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - schema: T; - typeName: ZodFirstPartyTypeKind.ZodEffects; - effect: Effect<any>; -} - -export class ZodEffects< - T extends ZodTypeAny, - Output = output<T>, - Input = input<T> -> extends ZodType<Output, ZodEffectsDef<T>, Input> { - innerType() { - return this._def.schema; - } - - sourceType(): T { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? (this._def.schema as unknown as ZodEffects<T>).sourceType() - : (this._def.schema as T); - } - - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - - const effect = this._def.effect || null; - - const checkCtx: RefinementCtx = { - addIssue: (arg: IssueData) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - }, - }; - - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") return INVALID; - - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") return INVALID; - if (result.status === "dirty") return DIRTY(result.value); - if (status.value === "dirty") return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") return INVALID; - if (result.status === "dirty") return DIRTY(result.value); - if (status.value === "dirty") return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc: unknown): any => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error( - "Async refinement encountered during synchronous parse operation. Use .parseAsync instead." - ); - } - return acc; - }; - - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") return INVALID; - if (inner.status === "dirty") status.dirty(); - - // return value is ignored - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((inner) => { - if (inner.status === "aborted") return INVALID; - if (inner.status === "dirty") status.dirty(); - - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - - if (!isValid(base)) return base; - - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error( - `Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.` - ); - } - - return { status: status.value, value: result }; - } else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((base) => { - if (!isValid(base)) return base; - - return Promise.resolve(effect.transform(base.value, checkCtx)).then( - (result) => ({ status: status.value, value: result }) - ); - }); - } - } - - util.assertNever(effect); - } - - static create = <I extends ZodTypeAny>( - schema: I, - effect: Effect<I["_output"]>, - params?: RawCreateParams - ): ZodEffects<I, I["_output"]> => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); - }; - - static createWithPreprocess = <I extends ZodTypeAny>( - preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, - schema: I, - params?: RawCreateParams - ): ZodEffects<I, I["_output"], unknown> => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params), - }); - }; -} - -export { ZodEffects as ZodTransformer }; - -/////////////////////////////////////////// -/////////////////////////////////////////// -////////// ////////// -////////// ZodOptional ////////// -////////// ////////// -/////////////////////////////////////////// -/////////////////////////////////////////// -export interface ZodOptionalDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - innerType: T; - typeName: ZodFirstPartyTypeKind.ZodOptional; -} - -export type ZodOptionalType<T extends ZodTypeAny> = ZodOptional<T>; - -export class ZodOptional<T extends ZodTypeAny> extends ZodType< - T["_output"] | undefined, - ZodOptionalDef<T>, - T["_input"] | undefined -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(undefined); - } - return this._def.innerType._parse(input); - } - - unwrap() { - return this._def.innerType; - } - - static create = <T extends ZodTypeAny>( - type: T, - params?: RawCreateParams - ): ZodOptional<T> => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }) as any; - }; -} - -/////////////////////////////////////////// -/////////////////////////////////////////// -////////// ////////// -////////// ZodNullable ////////// -////////// ////////// -/////////////////////////////////////////// -/////////////////////////////////////////// -export interface ZodNullableDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - innerType: T; - typeName: ZodFirstPartyTypeKind.ZodNullable; -} - -export type ZodNullableType<T extends ZodTypeAny> = ZodNullable<T>; - -export class ZodNullable<T extends ZodTypeAny> extends ZodType< - T["_output"] | null, - ZodNullableDef<T>, - T["_input"] | null -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - - unwrap() { - return this._def.innerType; - } - - static create = <T extends ZodTypeAny>( - type: T, - params?: RawCreateParams - ): ZodNullable<T> => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }) as any; - }; -} - -//////////////////////////////////////////// -//////////////////////////////////////////// -////////// ////////// -////////// ZodDefault ////////// -////////// ////////// -//////////////////////////////////////////// -//////////////////////////////////////////// -export interface ZodDefaultDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - innerType: T; - defaultValue: () => util.noUndefined<T["_input"]>; - typeName: ZodFirstPartyTypeKind.ZodDefault; -} - -export class ZodDefault<T extends ZodTypeAny> extends ZodType< - util.noUndefined<T["_output"]>, - ZodDefaultDef<T>, - T["_input"] | undefined -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - - removeDefault() { - return this._def.innerType; - } - - static create = <T extends ZodTypeAny>( - type: T, - params: RawCreateParams & { - default: T["_input"] | (() => util.noUndefined<T["_input"]>); - } - ): ZodDefault<T> => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: - typeof params.default === "function" - ? params.default - : () => params.default as any, - ...processCreateParams(params), - }) as any; - }; -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodCatch ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// -export interface ZodCatchDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - innerType: T; - catchValue: (ctx: { error: ZodError; input: unknown }) => T["_input"]; - typeName: ZodFirstPartyTypeKind.ZodCatch; -} - -export class ZodCatch<T extends ZodTypeAny> extends ZodType< - T["_output"], - ZodCatchDef<T>, - unknown // any input will pass validation // T["_input"] -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - - // newCtx is used to not collect issues from inner types in ctx - const newCtx: ParseContext = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - - if (isAsync(result)) { - return result.then((result) => { - return { - status: "valid", - value: - result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); - } else { - return { - status: "valid", - value: - result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - } - } - - removeCatch() { - return this._def.innerType; - } - - static create = <T extends ZodTypeAny>( - type: T, - params: RawCreateParams & { - catch: T["_output"] | (() => T["_output"]); - } - ): ZodCatch<T> => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: - typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); - }; -} - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodNaN ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// - -export interface ZodNaNDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodNaN; -} - -export class ZodNaN extends ZodType<number, ZodNaNDef> { - _parse(input: ParseInput): ParseReturnType<any> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType, - }); - return INVALID; - } - - return { status: "valid", value: input.data }; - } - - static create = (params?: RawCreateParams): ZodNaN => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodBranded ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// - -export interface ZodBrandedDef<T extends ZodTypeAny> extends ZodTypeDef { - type: T; - typeName: ZodFirstPartyTypeKind.ZodBranded; -} - -export const BRAND: unique symbol = Symbol("zod_brand"); -export type BRAND<T extends string | number | symbol> = { - [BRAND]: { [k in T]: true }; -}; - -export class ZodBranded< - T extends ZodTypeAny, - B extends string | number | symbol -> extends ZodType<T["_output"] & BRAND<B>, ZodBrandedDef<T>, T["_input"]> { - _parse(input: ParseInput): ParseReturnType<any> { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - - unwrap() { - return this._def.type; - } -} - -//////////////////////////////////////////// -//////////////////////////////////////////// -////////// ////////// -////////// ZodPipeline ////////// -////////// ////////// -//////////////////////////////////////////// -//////////////////////////////////////////// - -export interface ZodPipelineDef<A extends ZodTypeAny, B extends ZodTypeAny> - extends ZodTypeDef { - in: A; - out: B; - typeName: ZodFirstPartyTypeKind.ZodPipeline; -} - -export class ZodPipeline< - A extends ZodTypeAny, - B extends ZodTypeAny -> extends ZodType<B["_output"], ZodPipelineDef<A, B>, A["_input"]> { - _parse(input: ParseInput): ParseReturnType<any> { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - } - } - - static create<A extends ZodTypeAny, B extends ZodTypeAny>( - a: A, - b: B - ): ZodPipeline<A, B> { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, - }); - } -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodTemplateLiteral ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// - -type TemplateLiteralPrimitive = string | number | boolean | null | undefined; - -type TemplateLiteralInterpolatedPosition = ZodType< - TemplateLiteralPrimitive | bigint ->; - -type appendToTemplateLiteral< - Template extends string, - Suffix extends TemplateLiteralPrimitive | ZodType -> = Suffix extends TemplateLiteralPrimitive - ? `${Template}${Suffix}` - : Suffix extends ZodOptional<infer UnderlyingType> - ? Template | appendToTemplateLiteral<Template, UnderlyingType> - : Suffix extends ZodBranded<infer UnderlyingType, any> - ? appendToTemplateLiteral<Template, UnderlyingType> - : Suffix extends ZodType<infer Output, any, any> - ? Output extends TemplateLiteralPrimitive | bigint - ? `${Template}${Output}` - : never - : never; - -export interface ZodTemplateLiteralDef extends ZodTypeDef { - coerce: boolean; - parts: readonly ( - | TemplateLiteralPrimitive - | TemplateLiteralInterpolatedPosition - )[]; - regexString: string; - typeName: ZodFirstPartyTypeKind.ZodTemplateLiteral; -} - -export class ZodTemplateLiteral<Template extends string = ""> extends ZodType< - Template, - ZodTemplateLiteralDef -> { - interpolated<I extends TemplateLiteralInterpolatedPosition>( - type: Exclude<I, ZodNever | ZodNaN | ZodPipeline<any, any> | ZodLazy<any>> - ): ZodTemplateLiteral<appendToTemplateLiteral<Template, I>> { - return this._addPart(type) as any; - } - - literal<L extends TemplateLiteralPrimitive>( - literal: L - ): ZodTemplateLiteral<appendToTemplateLiteral<Template, L>> { - return this._addPart(literal) as any; - } - - _parse(input: ParseInput): ParseReturnType<Template> { - if (this._def.coerce) { - input.data = String(input.data); - } - - const parsedType = this._getType(input); - - if (parsedType !== ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx.parsedType, - }); - return INVALID; - } - - if (!new RegExp(this._def.regexString).test(input.data)) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - message: `does not match template literal with pattern /${this._def.regexString}/`, - path: ctx.path, - validation: "regex", - }); - return INVALID; - } - - return { status: "valid", value: input.data }; - } - - protected _addPart( - part: TemplateLiteralPrimitive | TemplateLiteralInterpolatedPosition - ): ZodTemplateLiteral { - const parts = [...this._def.parts, part]; - - return new ZodTemplateLiteral({ - ...this._def, - parts, - regexString: this._appendToRegexString(this._def.regexString, part), - }); - } - - protected _appendToRegexString( - regexString: string, - part: TemplateLiteralPrimitive | TemplateLiteralInterpolatedPosition - ): string { - return `^${this._unwrapRegExp( - regexString - )}${this._transformPartToRegexString(part)}$`; - } - - protected _transformPartToRegexString( - part: TemplateLiteralPrimitive | TemplateLiteralInterpolatedPosition - ): string { - if (!(part instanceof ZodType)) { - return this._escapeRegExp(part); - } - - if (part instanceof ZodLiteral) { - return this._escapeRegExp(part._def.value); - } - - if (part instanceof ZodString) { - return this._transformZodStringPartToRegexString(part); - } - - if (part instanceof ZodEnum || part instanceof ZodNativeEnum) { - const values = - part instanceof ZodEnum - ? part._def.values - : util.getValidEnumValues(part._def.values); - - return `(${values.map(this._escapeRegExp).join("|")})`; - } - - if (part instanceof ZodUnion) { - return `(${(part._def.options as any[]) - .map((option) => this._transformPartToRegexString(option)) - .join("|")})`; - } - - if (part instanceof ZodNumber) { - return this._transformZodNumberPartToRegexString(part); - } - - if (part instanceof ZodOptional) { - return `(${this._transformPartToRegexString(part.unwrap())})?`; - } - - if (part instanceof ZodTemplateLiteral) { - return this._unwrapRegExp(part._def.regexString); - } - - if (part instanceof ZodBigInt) { - // FIXME: include/exclude '-' based on min/max values after https://github.com/colinhacks/zod/pull/1711 is merged. - return "\\-?\\d+"; - } - - if (part instanceof ZodBoolean) { - return "(true|false)"; - } - - if (part instanceof ZodNullable) { - do { - part = part.unwrap(); - } while (part instanceof ZodNullable); - - return `(${this._transformPartToRegexString(part)}|null)${ - part instanceof ZodOptional ? "?" : "" - }`; - } - - if (part instanceof ZodBranded) { - return this._transformPartToRegexString(part.unwrap()); - } - - if (part instanceof ZodAny) { - return ".*"; - } - - if (part instanceof ZodNull) { - return "null"; - } - - if (part instanceof ZodUndefined) { - return "undefined"; - } - - throw new ZodTemplateLiteralUnsupportedTypeError(); - } - - // FIXME: we don't support transformations, so `.trim()` is not supported. - protected _transformZodStringPartToRegexString(part: ZodString): string { - let maxLength = Infinity, - minLength = 0, - endsWith = "", - startsWith = ""; - - for (const ch of part._def.checks) { - const regex = this._resolveRegexForStringCheck(ch); - - if (regex) { - return this._unwrapRegExp(regex); - } - - if (ch.kind === "endsWith") { - endsWith = ch.value; - } else if (ch.kind === "length") { - minLength = maxLength = ch.value; - } else if (ch.kind === "max") { - maxLength = Math.max(0, Math.min(maxLength, ch.value)); - } else if (ch.kind === "min") { - minLength = Math.max(minLength, ch.value); - } else if (ch.kind === "startsWith") { - startsWith = ch.value; - } else { - throw new ZodTemplateLiteralUnsupportedCheckError( - ZodFirstPartyTypeKind.ZodString, - ch.kind - ); - } - } - - const constrainedMinLength = Math.max( - 0, - minLength - startsWith.length - endsWith.length - ); - const constrainedMaxLength = Number.isFinite(maxLength) - ? Math.max(0, maxLength - startsWith.length - endsWith.length) - : Infinity; - - if ( - constrainedMaxLength === 0 || - constrainedMinLength > constrainedMaxLength - ) { - return `${startsWith}${endsWith}`; - } - - return `${startsWith}.${this._resolveRegexWildcardLength( - constrainedMinLength, - constrainedMaxLength - )}${endsWith}`; - } - - protected _resolveRegexForStringCheck(check: ZodStringCheck): RegExp | null { - return { - [check.kind]: null, - cuid: cuidRegex, - cuid2: cuid2Regex, - datetime: check.kind === "datetime" ? datetimeRegex(check) : null, - email: emailRegex, - ip: - check.kind === "ip" - ? { - any: new RegExp( - `^(${this._unwrapRegExp( - ipv4Regex.source - )})|(${this._unwrapRegExp(ipv6Regex.source)})$` - ), - v4: ipv4Regex, - v6: ipv6Regex, - }[check.version || "any"] - : null, - regex: check.kind === "regex" ? check.regex : null, - ulid: ulidRegex, - uuid: uuidRegex, - }[check.kind]; - } - - protected _resolveRegexWildcardLength( - minLength: number, - maxLength: number - ): string { - if (minLength === maxLength) { - return minLength === 1 ? "" : `{${minLength}}`; - } - - if (maxLength !== Infinity) { - return `{${minLength},${maxLength}}`; - } - - if (minLength === 0) { - return "*"; - } - - if (minLength === 1) { - return "+"; - } - - return `{${minLength},}`; - } - - // FIXME: we do not support exponent notation (e.g. 2e5) since it conflicts with `.int()`. - protected _transformZodNumberPartToRegexString(part: ZodNumber): string { - let canBeNegative = true, - canBePositive = true, - min = -Infinity, - max = Infinity, - canBeZero = true, - isFinite = false, - isInt = false, - acc = ""; - - for (const ch of part._def.checks) { - if (ch.kind === "finite") { - isFinite = true; - } else if (ch.kind === "int") { - isInt = true; - } else if (ch.kind === "max") { - max = Math.min(max, ch.value); - - if (ch.value <= 0) { - canBePositive = false; - - if (ch.value === 0 && !ch.inclusive) { - canBeZero = false; - } - } - } else if (ch.kind === "min") { - min = Math.max(min, ch.value); - - if (ch.value >= 0) { - canBeNegative = false; - - if (ch.value === 0 && !ch.inclusive) { - canBeZero = false; - } - } - } else { - throw new ZodTemplateLiteralUnsupportedCheckError( - ZodFirstPartyTypeKind.ZodNumber, - ch.kind - ); - } - } - - if (Number.isFinite(min) && Number.isFinite(max)) { - isFinite = true; - } - - if (canBeNegative) { - acc = `${acc}\\-`; - - if (canBePositive) { - acc = `${acc}?`; - } - } else if (!canBePositive) { - return "0+"; - } - - if (!isFinite) { - acc = `${acc}(Infinity|(`; - } - - if (!canBeZero) { - if (!isInt) { - acc = `${acc}((\\d*[1-9]\\d*(\\.\\d+)?)|(\\d+\\.\\d*[1-9]\\d*))`; - } else { - acc = `${acc}\\d*[1-9]\\d*`; - } - } else if (isInt) { - acc = `${acc}\\d+`; - } else { - acc = `${acc}\\d+(\\.\\d+)?`; - } - - if (!isFinite) { - acc = `${acc}))`; - } - - return acc; - } - - protected _unwrapRegExp(regex: RegExp | string): string { - const flags = typeof regex === "string" ? "" : regex.flags; - const source = typeof regex === "string" ? regex : regex.source; - - if (flags.includes("i")) { - return this._unwrapRegExp(this._makeRegexStringCaseInsensitive(source)); - } - - return source.replace(/(^\^)|(\$$)/g, ""); - } - - protected _makeRegexStringCaseInsensitive(regexString: string): string { - const isAlphabetic = (char: string) => char.match(/[a-z]/i) != null; - - let caseInsensitive = ""; - let inCharacterSet = false; - for (let i = 0; i < regexString.length; i++) { - const char = regexString.charAt(i); - const nextChar = regexString.charAt(i + 1); - - if (char === "\\") { - caseInsensitive += `${char}${nextChar}`; - i++; - continue; - } - - if (char === "[") { - inCharacterSet = true; - } else if (inCharacterSet && char === "]") { - inCharacterSet = false; - } - - if (!isAlphabetic(char)) { - caseInsensitive += char; - continue; - } - - if (!inCharacterSet) { - caseInsensitive += `[${char.toLowerCase()}${char.toUpperCase()}]`; - continue; - } - - const charAfterNext = regexString.charAt(i + 2); - - if (nextChar !== "-" || !isAlphabetic(charAfterNext)) { - caseInsensitive += `${char.toLowerCase()}${char.toUpperCase()}`; - continue; - } - - caseInsensitive += `${char.toLowerCase()}-${charAfterNext.toLowerCase()}${char.toUpperCase()}-${charAfterNext.toUpperCase()}`; - i += 2; - } - - return caseInsensitive; - } - - protected _escapeRegExp(str: unknown): string { - if (typeof str !== "string") { - str = `${str}`; - } - - return (str as string).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - } - - static create = ( - params?: RawCreateParams & { coerce?: true } - ): ZodTemplateLiteral => { - return new ZodTemplateLiteral({ - ...processCreateParams(params), - coerce: params?.coerce ?? false, - parts: [], - regexString: "^$", - typeName: ZodFirstPartyTypeKind.ZodTemplateLiteral, - }); - }; -} - -/////////////////////////////////////////// -/////////////////////////////////////////// -////////// ////////// -////////// ZodReadonly ////////// -////////// ////////// -/////////////////////////////////////////// -/////////////////////////////////////////// -type BuiltIn = - | (((...args: any[]) => any) | (new (...args: any[]) => any)) - | { readonly [Symbol.toStringTag]: string } - | Date - | Error - | Generator - | Promise<unknown> - | RegExp; - -type MakeReadonly<T> = T extends Map<infer K, infer V> - ? ReadonlyMap<K, V> - : T extends Set<infer V> - ? ReadonlySet<V> - : T extends [infer Head, ...infer Tail] - ? readonly [Head, ...Tail] - : T extends Array<infer V> - ? ReadonlyArray<V> - : T extends BuiltIn - ? T - : Readonly<T>; - -export interface ZodReadonlyDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - innerType: T; - typeName: ZodFirstPartyTypeKind.ZodReadonly; -} - -export class ZodReadonly<T extends ZodTypeAny> extends ZodType< - MakeReadonly<T["_output"]>, - ZodReadonlyDef<T>, - MakeReadonly<T["_input"]> -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const result = this._def.innerType._parse(input); - if (isValid(result)) { - result.value = Object.freeze(result.value); - } - return result; - } - - static create = <T extends ZodTypeAny>( - type: T, - params?: RawCreateParams - ): ZodReadonly<T> => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params), - }) as any; - }; - - unwrap() { - return this._def.innerType; - } -} - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// z.custom ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -type CustomParams = CustomErrorParams & { fatal?: boolean }; -export const custom = <T>( - check?: (data: unknown) => any, - params: string | CustomParams | ((input: any) => CustomParams) = {}, - /** - * @deprecated - * - * Pass `fatal` into the params object instead: - * - * ```ts - * z.string().custom((val) => val.length > 5, { fatal: false }) - * ``` - * - */ - fatal?: boolean -): ZodType<T> => { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - if (!check(data)) { - const p = - typeof params === "function" - ? params(data) - : typeof params === "string" - ? { message: params } - : params; - const _fatal = p.fatal ?? fatal ?? true; - const p2 = typeof p === "string" ? { message: p } : p; - ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); - } - }); - return ZodAny.create(); -}; - -export { ZodType as Schema, ZodType as ZodSchema }; - -export const late = { - object: ZodObject.lazycreate, -}; - -export enum ZodFirstPartyTypeKind { - ZodString = "ZodString", - ZodNumber = "ZodNumber", - ZodNaN = "ZodNaN", - ZodBigInt = "ZodBigInt", - ZodBoolean = "ZodBoolean", - ZodDate = "ZodDate", - ZodSymbol = "ZodSymbol", - ZodUndefined = "ZodUndefined", - ZodNull = "ZodNull", - ZodAny = "ZodAny", - ZodUnknown = "ZodUnknown", - ZodNever = "ZodNever", - ZodVoid = "ZodVoid", - ZodArray = "ZodArray", - ZodObject = "ZodObject", - ZodUnion = "ZodUnion", - ZodDiscriminatedUnion = "ZodDiscriminatedUnion", - ZodIntersection = "ZodIntersection", - ZodTuple = "ZodTuple", - ZodRecord = "ZodRecord", - ZodMap = "ZodMap", - ZodSet = "ZodSet", - ZodFunction = "ZodFunction", - ZodLazy = "ZodLazy", - ZodLiteral = "ZodLiteral", - ZodEnum = "ZodEnum", - ZodEffects = "ZodEffects", - ZodNativeEnum = "ZodNativeEnum", - ZodOptional = "ZodOptional", - ZodNullable = "ZodNullable", - ZodDefault = "ZodDefault", - ZodCatch = "ZodCatch", - ZodPromise = "ZodPromise", - ZodBranded = "ZodBranded", - ZodPipeline = "ZodPipeline", - ZodTemplateLiteral = "ZodTemplateLiteral", - ZodReadonly = "ZodReadonly", -} -export type ZodFirstPartySchemaTypes = - | ZodString - | ZodNumber - | ZodNaN - | ZodBigInt - | ZodBoolean - | ZodDate - | ZodUndefined - | ZodNull - | ZodAny - | ZodUnknown - | ZodNever - | ZodVoid - | ZodArray<any, any> - | ZodObject<any, any, any> - | ZodUnion<any> - | ZodDiscriminatedUnion<any, any> - | ZodIntersection<any, any> - | ZodTuple<any, any> - | ZodRecord<any, any> - | ZodMap<any> - | ZodSet<any> - | ZodFunction<any, any> - | ZodLazy<any> - | ZodLiteral<any> - | ZodEnum<any> - | ZodEffects<any, any, any> - | ZodNativeEnum<any> - | ZodOptional<any> - | ZodNullable<any> - | ZodDefault<any> - | ZodCatch<any> - | ZodPromise<any> - | ZodBranded<any, any> - | ZodPipeline<any, any> - | ZodReadonly<any> - | ZodSymbol - | ZodTemplateLiteral<any>; - -// requires TS 4.4+ -abstract class Class { - constructor(..._: any[]) {} -} -const instanceOfType = <T extends typeof Class>( - // const instanceOfType = <T extends new (...args: any[]) => any>( - cls: T, - params: CustomParams = { - message: `Input not instance of ${cls.name}`, - } -) => custom<InstanceType<T>>((data) => data instanceof cls, params); - -const stringType = ZodString.create; -const numberType = ZodNumber.create; -const nanType = ZodNaN.create; -const bigIntType = ZodBigInt.create; -const booleanType = ZodBoolean.create; -const dateType = ZodDate.create; -const symbolType = ZodSymbol.create; -const undefinedType = ZodUndefined.create; -const nullType = ZodNull.create; -const anyType = ZodAny.create; -const unknownType = ZodUnknown.create; -const neverType = ZodNever.create; -const voidType = ZodVoid.create; -const arrayType = ZodArray.create; -const objectType = ZodObject.create; -const strictObjectType = ZodObject.strictCreate; -const unionType = ZodUnion.create; -const discriminatedUnionType = ZodDiscriminatedUnion.create; -const intersectionType = ZodIntersection.create; -const tupleType = ZodTuple.create; -const recordType = ZodRecord.create; -const mapType = ZodMap.create; -const setType = ZodSet.create; -const functionType = ZodFunction.create; -const lazyType = ZodLazy.create; -const literalType = ZodLiteral.create; -const enumType = ZodEnum.create; -const nativeEnumType = ZodNativeEnum.create; -const promiseType = ZodPromise.create; -const effectsType = ZodEffects.create; -const optionalType = ZodOptional.create; -const nullableType = ZodNullable.create; -const preprocessType = ZodEffects.createWithPreprocess; -const pipelineType = ZodPipeline.create; -const templateLiteralType = ZodTemplateLiteral.create; -const ostring = () => stringType().optional(); -const onumber = () => numberType().optional(); -const oboolean = () => booleanType().optional(); - -export const coerce = { - string: ((arg) => - ZodString.create({ ...arg, coerce: true })) as (typeof ZodString)["create"], - number: ((arg) => - ZodNumber.create({ ...arg, coerce: true })) as (typeof ZodNumber)["create"], - boolean: ((arg) => - ZodBoolean.create({ - ...arg, - coerce: true, - })) as (typeof ZodBoolean)["create"], - bigint: ((arg) => - ZodBigInt.create({ ...arg, coerce: true })) as (typeof ZodBigInt)["create"], - date: ((arg) => - ZodDate.create({ ...arg, coerce: true })) as (typeof ZodDate)["create"], - templateLiteral: ((arg) => - ZodTemplateLiteral.create({ - ...arg, - coerce: true, - })) as (typeof ZodTemplateLiteral)["create"], -}; - -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, - pipelineType as pipeline, - preprocessType as preprocess, - promiseType as promise, - recordType as record, - setType as set, - strictObjectType as strictObject, - stringType as string, - symbolType as symbol, - templateLiteralType as templateLiteral, - effectsType as transformer, - tupleType as tuple, - undefinedType as undefined, - unionType as union, - unknownType as unknown, - voidType as void, -}; - -export const NEVER = INVALID as never; diff --git a/package.json b/package.json index 4574a6f1d..2de399677 100644 --- a/package.json +++ b/package.json @@ -89,7 +89,6 @@ "fix": "yarn lint:fix && yarn prettier:fix", "clean": "rm -rf lib/* deno/lib/*", "build": "yarn run clean && npm run build:cjs && npm run build:esm && npm run build:deno", - "build:deno": "node ./deno-build.mjs && cp ./README.md ./deno/lib", "build:esm": "rollup --config ./configs/rollup.config.js", "build:cjs": "tsc -p ./configs/tsconfig.cjs.json", "build:types": "tsc -p ./configs/tsconfig.types.json", @@ -101,7 +100,6 @@ "test:vitest": "npx vitest --config ./configs/vitest.config.ts", "test:ts-jest": "npx jest --config ./configs/ts-jest.config.json", "test:swc": "npx jest --config ./configs/swc-jest.config.json", - "test:deno": "cd deno && deno test", "prepublishOnly": "npm run test && npm run build && npm run build:deno", "play": "nodemon -e ts -w . -x tsx playground.ts", "depcruise": "depcruise -c .dependency-cruiser.js src", @@ -115,4 +113,4 @@ } }, "types": "./index.d.ts" -} +} \ No newline at end of file From df70e1e9fa01e2183fa61dfcd4c9385657d2670f Mon Sep 17 00:00:00 2001 From: Charles Catta <charles.catta@botpress.com> Date: Thu, 4 Apr 2024 11:26:50 -0400 Subject: [PATCH 2/3] WIP --- package.json | 2 +- playground.ts | 11 +- src/__tests__/error.test.ts | 2 +- src/__tests__/refine.test.ts | 2 +- src/__tests__/tuple.test.ts | 2 +- src/defs.ts | 96 + src/errors.ts | 13 - src/external.ts | 10 +- src/types.ts | 5572 ----------------- src/types/any.ts | 26 + src/types/array.ts | 169 + src/types/basetype.ts | 485 ++ src/types/bigint.ts | 219 + src/types/boolean.ts | 45 + src/types/branded.ts | 33 + src/types/catch.ts | 100 + src/types/custom.ts | 36 + src/types/date.ts | 144 + src/types/default.ts | 58 + src/types/discriminatedUnion.ts | 209 + src/types/enum.ts | 155 + src/{ZodError.ts => types/error/index.ts} | 22 +- src/{ => types/error}/locales/en.ts | 8 +- src/types/function.ts | 216 + src/types/helpers/partialUtil.ts | 33 + src/types/index.ts | 56 + src/types/intersection.ts | 158 + src/types/lazy.ts | 50 + src/types/literal.ts | 45 + src/types/map.ts | 116 + src/types/nan.ts | 45 + src/types/nativeEnum.ts | 73 + src/types/never.ts | 31 + src/types/null.ts | 36 + src/types/nullable.ts | 48 + src/types/number.ts | 301 + src/types/object.ts | 645 ++ src/types/optional.ts | 48 + src/types/pipeline.ts | 70 + src/types/promise.ts | 74 + src/types/readonly.ts | 65 + src/types/record.ts | 121 + src/types/set.ts | 129 + src/types/string.ts | 553 ++ src/types/symbol.ts | 38 + src/types/templateLiteral.ts | 478 ++ src/types/transformer.ts | 216 + src/types/tuple.ts | 141 + src/types/undefined.ts | 38 + src/types/union.ts | 153 + src/types/unknown.ts | 22 + src/{helpers => types/utils}/enumUtil.ts | 0 src/{helpers => types/utils}/errorUtil.ts | 0 src/{helpers/util.ts => types/utils/index.ts} | 27 +- src/{helpers => types/utils}/parseUtil.ts | 7 +- src/{helpers => types/utils}/partialUtil.ts | 16 +- src/{helpers => types/utils}/typeAliases.ts | 0 src/types/void.ts | 37 + src/z.ts | 205 + 59 files changed, 6092 insertions(+), 5618 deletions(-) create mode 100644 src/defs.ts delete mode 100644 src/errors.ts delete mode 100644 src/types.ts create mode 100644 src/types/any.ts create mode 100644 src/types/array.ts create mode 100644 src/types/basetype.ts create mode 100644 src/types/bigint.ts create mode 100644 src/types/boolean.ts create mode 100644 src/types/branded.ts create mode 100644 src/types/catch.ts create mode 100644 src/types/custom.ts create mode 100644 src/types/date.ts create mode 100644 src/types/default.ts create mode 100644 src/types/discriminatedUnion.ts create mode 100644 src/types/enum.ts rename src/{ZodError.ts => types/error/index.ts} (96%) rename src/{ => types/error}/locales/en.ts (97%) create mode 100644 src/types/function.ts create mode 100644 src/types/helpers/partialUtil.ts create mode 100644 src/types/index.ts create mode 100644 src/types/intersection.ts create mode 100644 src/types/lazy.ts create mode 100644 src/types/literal.ts create mode 100644 src/types/map.ts create mode 100644 src/types/nan.ts create mode 100644 src/types/nativeEnum.ts create mode 100644 src/types/never.ts create mode 100644 src/types/null.ts create mode 100644 src/types/nullable.ts create mode 100644 src/types/number.ts create mode 100644 src/types/object.ts create mode 100644 src/types/optional.ts create mode 100644 src/types/pipeline.ts create mode 100644 src/types/promise.ts create mode 100644 src/types/readonly.ts create mode 100644 src/types/record.ts create mode 100644 src/types/set.ts create mode 100644 src/types/string.ts create mode 100644 src/types/symbol.ts create mode 100644 src/types/templateLiteral.ts create mode 100644 src/types/transformer.ts create mode 100644 src/types/tuple.ts create mode 100644 src/types/undefined.ts create mode 100644 src/types/union.ts create mode 100644 src/types/unknown.ts rename src/{helpers => types/utils}/enumUtil.ts (100%) rename src/{helpers => types/utils}/errorUtil.ts (100%) rename src/{helpers/util.ts => types/utils/index.ts} (85%) rename src/{helpers => types/utils}/parseUtil.ts (96%) rename src/{helpers => types/utils}/partialUtil.ts (90%) rename src/{helpers => types/utils}/typeAliases.ts (100%) create mode 100644 src/types/void.ts create mode 100644 src/z.ts diff --git a/package.json b/package.json index 2de399677..1af47616d 100644 --- a/package.json +++ b/package.json @@ -88,7 +88,7 @@ "check": "yarn lint:check && yarn prettier:check", "fix": "yarn lint:fix && yarn prettier:fix", "clean": "rm -rf lib/* deno/lib/*", - "build": "yarn run clean && npm run build:cjs && npm run build:esm && npm run build:deno", + "build": "yarn run clean && npm run build:cjs && npm run build:esm", "build:esm": "rollup --config ./configs/rollup.config.js", "build:cjs": "tsc -p ./configs/tsconfig.cjs.json", "build:types": "tsc -p ./configs/tsconfig.types.json", diff --git a/playground.ts b/playground.ts index 4e01473b6..1bacf6580 100644 --- a/playground.ts +++ b/playground.ts @@ -1,3 +1,12 @@ import { z } from "./src"; -z; +z.string(); + +z.array( + z.object({ + name: z.string(), + age: z.number(), + }) +); + +z.coerce.bigint(); diff --git a/src/__tests__/error.test.ts b/src/__tests__/error.test.ts index 69acd5575..29cf4cf84 100644 --- a/src/__tests__/error.test.ts +++ b/src/__tests__/error.test.ts @@ -3,7 +3,7 @@ import { expect, test } from "@jest/globals"; import { ZodParsedType } from "../helpers/util"; import * as z from "../index"; -import { ZodError, ZodIssueCode } from "../ZodError"; +import { ZodError, ZodIssueCode } from "../types/error"; test("error creation", () => { const err1 = ZodError.create([]); diff --git a/src/__tests__/refine.test.ts b/src/__tests__/refine.test.ts index 4d03439ba..2decb2324 100644 --- a/src/__tests__/refine.test.ts +++ b/src/__tests__/refine.test.ts @@ -3,7 +3,7 @@ import { expect, test } from "@jest/globals"; import { util } from "../helpers/util"; import * as z from "../index"; -import { ZodIssueCode } from "../ZodError"; +import { ZodIssueCode } from "../types/error"; test("refinement", () => { const obj1 = z.object({ diff --git a/src/__tests__/tuple.test.ts b/src/__tests__/tuple.test.ts index 364881c4e..9363c0928 100644 --- a/src/__tests__/tuple.test.ts +++ b/src/__tests__/tuple.test.ts @@ -3,7 +3,7 @@ import { expect, test } from "@jest/globals"; import { util } from "../helpers/util"; import * as z from "../index"; -import { ZodError } from "../ZodError"; +import { ZodError } from "../types/error"; const testTuple = z.tuple([ z.string(), diff --git a/src/defs.ts b/src/defs.ts new file mode 100644 index 000000000..d10b8f09f --- /dev/null +++ b/src/defs.ts @@ -0,0 +1,96 @@ +import type { ZodAnyDef } from "./types/any"; +import type { ZodArrayDef } from "./types/array"; +import type { ZodBigIntDef } from "./types/bigint"; +import type { ZodBooleanDef } from "./types/boolean"; +import type { ZodDateDef } from "./types/date"; +import type { ZodEnumDef } from "./types/enum"; +import type { ZodFunctionDef } from "./types/function"; +import type { ZodIntersectionDef } from "./types/intersection"; +import type { ZodLazyDef } from "./types/lazy"; +import type { ZodLiteralDef } from "./types/literal"; +import type { ZodMapDef } from "./types/map"; +import type { ZodNativeEnumDef } from "./types/nativeEnum"; +import type { ZodNeverDef } from "./types/never"; +import type { ZodNullDef } from "./types/null"; +import type { ZodNullableDef } from "./types/nullable"; +import type { ZodNumberDef } from "./types/number"; +import type { ZodObjectDef } from "./types/object"; +import type { ZodOptionalDef } from "./types/optional"; +import type { ZodPromiseDef } from "./types/promise"; +import type { ZodRecordDef } from "./types/record"; +import type { ZodStringDef } from "./types/string"; +import type { ZodEffectsDef as ZodTransformerDef } from "./types/transformer"; +import type { ZodTupleDef } from "./types/tuple"; +import type { ZodUndefinedDef } from "./types/undefined"; +import type { ZodUnionDef } from "./types/union"; +import type { ZodUnknownDef } from "./types/unknown"; +import type { ZodVoidDef } from "./types/void"; + +export type ZodDef = + | ZodStringDef + | ZodNumberDef + | ZodBigIntDef + | ZodBooleanDef + | ZodDateDef + | ZodUndefinedDef + | ZodNullDef + | ZodAnyDef + | ZodUnknownDef + | ZodNeverDef + | ZodVoidDef + | ZodArrayDef + | ZodObjectDef + | ZodUnionDef + | ZodIntersectionDef + | ZodTupleDef + | ZodRecordDef + | ZodMapDef + | ZodFunctionDef + | ZodLazyDef + | ZodLiteralDef + | ZodEnumDef + | ZodTransformerDef + | ZodNativeEnumDef + | ZodOptionalDef + | ZodNullableDef + | ZodPromiseDef; + +export enum ZodFirstPartyTypeKind { + ZodString = "ZodString", + ZodNumber = "ZodNumber", + ZodNaN = "ZodNaN", + ZodBigInt = "ZodBigInt", + ZodBoolean = "ZodBoolean", + ZodDate = "ZodDate", + ZodSymbol = "ZodSymbol", + ZodUndefined = "ZodUndefined", + ZodNull = "ZodNull", + ZodAny = "ZodAny", + ZodUnknown = "ZodUnknown", + ZodNever = "ZodNever", + ZodVoid = "ZodVoid", + ZodArray = "ZodArray", + ZodObject = "ZodObject", + ZodUnion = "ZodUnion", + ZodDiscriminatedUnion = "ZodDiscriminatedUnion", + ZodIntersection = "ZodIntersection", + ZodTuple = "ZodTuple", + ZodRecord = "ZodRecord", + ZodMap = "ZodMap", + ZodSet = "ZodSet", + ZodFunction = "ZodFunction", + ZodLazy = "ZodLazy", + ZodLiteral = "ZodLiteral", + ZodEnum = "ZodEnum", + ZodEffects = "ZodEffects", + ZodNativeEnum = "ZodNativeEnum", + ZodOptional = "ZodOptional", + ZodNullable = "ZodNullable", + ZodDefault = "ZodDefault", + ZodCatch = "ZodCatch", + ZodPromise = "ZodPromise", + ZodBranded = "ZodBranded", + ZodPipeline = "ZodPipeline", + ZodTemplateLiteral = "ZodTemplateLiteral", + ZodReadonly = "ZodReadonly", +} diff --git a/src/errors.ts b/src/errors.ts deleted file mode 100644 index 17e7404b8..000000000 --- a/src/errors.ts +++ /dev/null @@ -1,13 +0,0 @@ -import defaultErrorMap from "./locales/en"; -import type { ZodErrorMap } from "./ZodError"; - -let overrideErrorMap = defaultErrorMap; -export { defaultErrorMap }; - -export function setErrorMap(map: ZodErrorMap) { - overrideErrorMap = map; -} - -export function getErrorMap() { - return overrideErrorMap; -} diff --git a/src/external.ts b/src/external.ts index 002e17d9c..c66be1c32 100644 --- a/src/external.ts +++ b/src/external.ts @@ -1,6 +1,6 @@ -export * from "./errors"; -export * from "./helpers/parseUtil"; -export * from "./helpers/typeAliases"; -export * from "./helpers/util"; export * from "./types"; -export * from "./ZodError"; +export * from "./types/error"; +export * from "./types/utils"; +export * from "./types/utils/parseUtil"; +export * from "./types/utils/typeAliases"; +export * from "./z"; diff --git a/src/types.ts b/src/types.ts deleted file mode 100644 index 3636a4167..000000000 --- a/src/types.ts +++ /dev/null @@ -1,5572 +0,0 @@ -import { defaultErrorMap, getErrorMap } from "./errors"; -import { enumUtil } from "./helpers/enumUtil"; -import { errorUtil } from "./helpers/errorUtil"; -import { - addIssueToContext, - AsyncParseReturnType, - DIRTY, - INVALID, - isAborted, - isAsync, - isDirty, - isValid, - makeIssue, - OK, - ParseContext, - ParseInput, - ParseParams, - ParsePath, - ParseReturnType, - ParseStatus, - SyncParseReturnType, -} from "./helpers/parseUtil"; -import { partialUtil } from "./helpers/partialUtil"; -import { Primitive } from "./helpers/typeAliases"; -import { getParsedType, objectUtil, util, ZodParsedType } from "./helpers/util"; -import { - IssueData, - StringValidation, - ZodCustomIssue, - ZodError, - ZodErrorMap, - ZodIssue, - ZodIssueCode, - ZodTemplateLiteralUnsupportedCheckError, - ZodTemplateLiteralUnsupportedTypeError, -} from "./ZodError"; - -/////////////////////////////////////// -/////////////////////////////////////// -////////// ////////// -////////// ZodType ////////// -////////// ////////// -/////////////////////////////////////// -/////////////////////////////////////// - -export type RefinementCtx = { - addIssue: (arg: IssueData) => void; - path: (string | number)[]; -}; -export type ZodRawShape = { [k: string]: ZodTypeAny }; -export type ZodTypeAny = ZodType<any, any, any>; -export type TypeOf<T extends ZodType<any, any, any>> = T["_output"]; -export type input<T extends ZodType<any, any, any>> = T["_input"]; -export type output<T extends ZodType<any, any, any>> = T["_output"]; -export type { TypeOf as infer }; - -export type CustomErrorParams = Partial<util.Omit<ZodCustomIssue, "code">>; -export interface ZodTypeDef { - errorMap?: ZodErrorMap; - description?: string; -} - -class ParseInputLazyPath implements ParseInput { - parent: ParseContext; - data: any; - _path: ParsePath; - _key: string | number | (string | number)[]; - _cachedPath: ParsePath = []; - constructor( - parent: ParseContext, - value: any, - path: ParsePath, - key: string | number | (string | number)[] - ) { - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - - return this._cachedPath; - } -} - -const handleResult = <Input, Output>( - ctx: ParseContext, - result: SyncParseReturnType<Output> -): - | { success: true; data: Output } - | { success: false; error: ZodError<Input> } => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - - return { - success: false, - get error() { - if ((this as any)._error) return (this as any)._error as Error; - const error = new ZodError(ctx.common.issues); - (this as any)._error = error; - return (this as any)._error; - }, - }; - } -}; - -export type RawCreateParams = - | { - errorMap?: ZodErrorMap; - invalid_type_error?: string; - required_error?: string; - description?: string; - } - | undefined; -export type ProcessedCreateParams = { - errorMap?: ZodErrorMap; - description?: string; -}; -function processCreateParams(params: RawCreateParams): ProcessedCreateParams { - if (!params) return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error( - `Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.` - ); - } - if (errorMap) return { errorMap: errorMap, description }; - const customMap: ZodErrorMap = (iss, ctx) => { - if (iss.code !== "invalid_type") return { message: ctx.defaultError }; - if (typeof ctx.data === "undefined") { - return { message: required_error ?? ctx.defaultError }; - } - return { message: invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} - -export type SafeParseSuccess<Output> = { - success: true; - data: Output; - error?: never; -}; -export type SafeParseError<Input> = { - success: false; - error: ZodError<Input>; - data?: never; -}; - -export type SafeParseReturnType<Input, Output> = - | SafeParseSuccess<Output> - | SafeParseError<Input>; - -export abstract class ZodType< - Output = any, - Def extends ZodTypeDef = ZodTypeDef, - Input = Output -> { - readonly _type!: Output; - readonly _output!: Output; - readonly _input!: Input; - readonly _def!: Def; - - get description() { - return this._def.description; - } - - abstract _parse(input: ParseInput): ParseReturnType<Output>; - - _getType(input: ParseInput): string { - return getParsedType(input.data); - } - - _getOrReturnCtx( - input: ParseInput, - ctx?: ParseContext | undefined - ): ParseContext { - return ( - ctx || { - common: input.parent.common, - data: input.data, - - parsedType: getParsedType(input.data), - - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - } - ); - } - - _processInputParams(input: ParseInput): { - status: ParseStatus; - ctx: ParseContext; - } { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - - parsedType: getParsedType(input.data), - - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; - } - - _parseSync(input: ParseInput): SyncParseReturnType<Output> { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - - _parseAsync(input: ParseInput): AsyncParseReturnType<Output> { - const result = this._parse(input); - return Promise.resolve(result); - } - - parse(data: unknown, params?: Partial<ParseParams>): Output { - const result = this.safeParse(data, params); - if (result.success) return result.data; - throw result.error; - } - - safeParse( - data: unknown, - params?: Partial<ParseParams> - ): SafeParseReturnType<Input, Output> { - const ctx: ParseContext = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap, - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - - return handleResult(ctx, result); - } - - async parseAsync( - data: unknown, - params?: Partial<ParseParams> - ): Promise<Output> { - const result = await this.safeParseAsync(data, params); - if (result.success) return result.data; - throw result.error; - } - - async safeParseAsync( - data: unknown, - params?: Partial<ParseParams> - ): Promise<SafeParseReturnType<Input, Output>> { - const ctx: ParseContext = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true, - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data), - }; - - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) - ? maybeAsyncResult - : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - - /** Alias of safeParseAsync */ - spa = this.safeParseAsync; - - refine<RefinedOutput extends Output>( - check: (arg: Output) => arg is RefinedOutput, - message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) - ): ZodEffects<this, RefinedOutput, Input>; - refine( - check: (arg: Output) => unknown | Promise<unknown>, - message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) - ): ZodEffects<this, Output, Input>; - refine( - check: (arg: Output) => unknown, - message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) - ): ZodEffects<this, Output, Input> { - const getIssueProperties = (val: Output) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => - ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val), - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - - refinement<RefinedOutput extends Output>( - check: (arg: Output) => arg is RefinedOutput, - refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) - ): ZodEffects<this, RefinedOutput, Input>; - refinement( - check: (arg: Output) => boolean, - refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) - ): ZodEffects<this, Output, Input>; - refinement( - check: (arg: Output) => unknown, - refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) - ): ZodEffects<this, Output, Input> { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue( - typeof refinementData === "function" - ? refinementData(val, ctx) - : refinementData - ); - return false; - } else { - return true; - } - }); - } - - _refinement( - refinement: RefinementEffect<Output>["refinement"] - ): ZodEffects<this, Output, Input> { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement }, - }); - } - - superRefine<RefinedOutput extends Output>( - refinement: (arg: Output, ctx: RefinementCtx) => arg is RefinedOutput - ): ZodEffects<this, RefinedOutput, Input>; - superRefine( - refinement: (arg: Output, ctx: RefinementCtx) => void - ): ZodEffects<this, Output, Input>; - superRefine( - refinement: (arg: Output, ctx: RefinementCtx) => Promise<void> - ): ZodEffects<this, Output, Input>; - superRefine( - refinement: (arg: Output, ctx: RefinementCtx) => unknown | Promise<unknown> - ): ZodEffects<this, Output, Input> { - return this._refinement(refinement); - } - - constructor(def: Def) { - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - } - - optional(): ZodOptional<this> { - return ZodOptional.create(this, this._def) as any; - } - nullable(): ZodNullable<this> { - return ZodNullable.create(this, this._def) as any; - } - nullish(): ZodOptional<ZodNullable<this>> { - return this.nullable().optional(); - } - array(): ZodArray<this> { - return ZodArray.create(this, this._def); - } - promise(): ZodPromise<this> { - return ZodPromise.create(this, this._def); - } - - or<T extends ZodTypeAny>(option: T): ZodUnion<[this, T]> { - return ZodUnion.create([this, option], this._def) as any; - } - - and<T extends ZodTypeAny>(incoming: T): ZodIntersection<this, T> { - return ZodIntersection.create(this, incoming, this._def); - } - - transform<NewOut>( - transform: (arg: Output, ctx: RefinementCtx) => NewOut | Promise<NewOut> - ): ZodEffects<this, NewOut> { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform }, - }) as any; - } - - default(def: util.noUndefined<Input>): ZodDefault<this>; - default(def: () => util.noUndefined<Input>): ZodDefault<this>; - default(def: any) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault, - }) as any; - } - - brand<B extends string | number | symbol>(brand?: B): ZodBranded<this, B>; - brand<B extends string | number | symbol>(): ZodBranded<this, B> { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def), - }); - } - - catch(def: Output): ZodCatch<this>; - catch( - def: (ctx: { error: ZodError; input: Input }) => Output - ): ZodCatch<this>; - catch(def: any) { - const catchValueFunc = typeof def === "function" ? def : () => def; - - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch, - }) as any; - } - - describe(description: string): this { - const This = (this as any).constructor; - return new This({ - ...this._def, - description, - }); - } - - pipe<T extends ZodTypeAny>(target: T): ZodPipeline<this, T> { - return ZodPipeline.create(this, target); - } - readonly(): ZodReadonly<this> { - return ZodReadonly.create(this); - } - - isOptional(): boolean { - return this.safeParse(undefined).success; - } - isNullable(): boolean { - return this.safeParse(null).success; - } -} - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodString ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// -export type IpVersion = "v4" | "v6"; -export type ZodStringCheck = - | { kind: "min"; value: number; message?: string } - | { kind: "max"; value: number; message?: string } - | { kind: "length"; value: number; message?: string } - | { kind: "email"; message?: string } - | { kind: "url"; message?: string } - | { kind: "emoji"; message?: string } - | { kind: "uuid"; message?: string } - | { kind: "cuid"; message?: string } - | { kind: "includes"; value: string; position?: number; message?: string } - | { kind: "cuid2"; message?: string } - | { kind: "ulid"; message?: string } - | { kind: "startsWith"; value: string; message?: string } - | { kind: "endsWith"; value: string; message?: string } - | { kind: "regex"; regex: RegExp; message?: string } - | { kind: "trim"; message?: string } - | { kind: "toLowerCase"; message?: string } - | { kind: "toUpperCase"; message?: string } - | { - kind: "datetime"; - offset: boolean; - precision: number | null; - message?: string; - } - | { kind: "ip"; version?: IpVersion; message?: string }; - -export interface ZodStringDef extends ZodTypeDef { - checks: ZodStringCheck[]; - typeName: ZodFirstPartyTypeKind.ZodString; - coerce: boolean; -} - -const cuidRegex = /^c[^\s-]{8,}$/i; -const cuid2Regex = /^[a-z][a-z0-9]*$/; -const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; -// const uuidRegex = -// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; -const uuidRegex = - /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -// from https://stackoverflow.com/a/46181/1550155 -// old version: too slow, didn't support unicode -// const 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; -//old email regex -// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; -// eslint-disable-next-line -// const emailRegex = -// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; -// const emailRegex = -// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// const emailRegex = -// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; -const emailRegex = - /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -// const emailRegex = -// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; - -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -let emojiRegex: RegExp; - -const ipv4Regex = - /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; - -const ipv6Regex = - /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; - -// Adapted from https://stackoverflow.com/a/3143231 -const datetimeRegex = (args: { precision: number | null; offset: boolean }) => { - if (args.precision) { - if (args.offset) { - return new RegExp( - `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$` - ); - } else { - return new RegExp( - `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$` - ); - } - } else if (args.precision === 0) { - if (args.offset) { - return new RegExp( - `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$` - ); - } else { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); - } - } else { - if (args.offset) { - return new RegExp( - `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$` - ); - } else { - return new RegExp( - `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$` - ); - } - } -}; - -function isValidIP(ip: string, version?: IpVersion) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - - return false; -} - -export class ZodString extends ZodType<string, ZodStringDef> { - _parse(input: ParseInput): ParseReturnType<string> { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - - if (parsedType !== ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext( - ctx, - { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx.parsedType, - } - // - ); - return INVALID; - } - - const status = new ParseStatus(); - let ctx: undefined | ParseContext = undefined; - - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!(input.data as string).includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!(input.data as string).startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!(input.data as string).endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - - return { status: status.value, value: input.data }; - } - - protected _regex( - regex: RegExp, - validation: StringValidation, - message?: errorUtil.ErrMessage - ) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message), - }); - } - - _addCheck(check: ZodStringCheck) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - - email(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - cuid(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message?: errorUtil.ErrMessage) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - - ip(options?: string | { version?: "v4" | "v6"; message?: string }) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - - datetime( - options?: - | string - | { - message?: string | undefined; - precision?: number | null; - offset?: boolean; - } - ) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - message: options, - }); - } - return this._addCheck({ - kind: "datetime", - precision: - typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - ...errorUtil.errToObj(options?.message), - }); - } - - regex(regex: RegExp, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil.errToObj(message), - }); - } - - includes(value: string, options?: { message?: string; position?: number }) { - return this._addCheck({ - kind: "includes", - value: value, - position: options?.position, - ...errorUtil.errToObj(options?.message), - }); - } - - startsWith(value: string, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil.errToObj(message), - }); - } - - endsWith(value: string, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil.errToObj(message), - }); - } - - min(minLength: number, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message), - }); - } - - max(maxLength: number, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message), - }); - } - - length(len: number, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message), - }); - } - - /** - * @deprecated Use z.string().min(1) instead. - * @see {@link ZodString.min} - */ - nonempty(message?: errorUtil.ErrMessage) { - return this.min(1, errorUtil.errToObj(message)); - } - - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], - }); - } - - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], - }); - } - - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], - }); - } - - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - - get minLength() { - let min: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) min = ch.value; - } - } - return min; - } - get maxLength() { - let max: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) max = ch.value; - } - } - return max; - } - - static create = (params?: RawCreateParams & { coerce?: true }): ZodString => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params), - }); - }; -} - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodNumber ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// -export type ZodNumberCheck = - | { kind: "min"; value: number; inclusive: boolean; message?: string } - | { kind: "max"; value: number; inclusive: boolean; message?: string } - | { kind: "int"; message?: string } - | { kind: "multipleOf"; value: number; message?: string } - | { kind: "finite"; message?: string }; - -// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 -function floatSafeRemainder(val: number, step: number) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / Math.pow(10, decCount); -} - -export interface ZodNumberDef extends ZodTypeDef { - checks: ZodNumberCheck[]; - typeName: ZodFirstPartyTypeKind.ZodNumber; - coerce: boolean; -} - -export class ZodNumber extends ZodType<number, ZodNumberDef> { - _parse(input: ParseInput): ParseReturnType<number> { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx.parsedType, - }); - return INVALID; - } - - let ctx: undefined | ParseContext = undefined; - const status = new ParseStatus(); - - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message, - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - - return { status: status.value, value: input.data }; - } - - static create = ( - params?: RawCreateParams & { coerce?: boolean } - ): ZodNumber => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params), - }); - }; - - gte(value: number, message?: errorUtil.ErrMessage) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - min = this.gte; - - gt(value: number, message?: errorUtil.ErrMessage) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - - lte(value: number, message?: errorUtil.ErrMessage) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - max = this.lte; - - lt(value: number, message?: errorUtil.ErrMessage) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - - protected setLimit( - kind: "min" | "max", - value: number, - inclusive: boolean, - message?: string - ) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - - _addCheck(check: ZodNumberCheck) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - - int(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message), - }); - } - - positive(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); - } - - negative(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); - } - - nonpositive(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); - } - - nonnegative(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); - } - - multipleOf(value: number, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil.toString(message), - }); - } - step = this.multipleOf; - - finite(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message), - }); - } - - safe(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message), - }); - } - - get minValue() { - let min: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) min = ch.value; - } - } - return min; - } - - get maxValue() { - let max: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) max = ch.value; - } - } - return max; - } - - get isInt() { - return !!this._def.checks.find( - (ch) => - ch.kind === "int" || - (ch.kind === "multipleOf" && util.isInteger(ch.value)) - ); - } - - get isFinite() { - let max: number | null = null, - min: number | null = null; - for (const ch of this._def.checks) { - if ( - ch.kind === "finite" || - ch.kind === "int" || - ch.kind === "multipleOf" - ) { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodBigInt ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// -export type ZodBigIntCheck = - | { kind: "min"; value: bigint; inclusive: boolean; message?: string } - | { kind: "max"; value: bigint; inclusive: boolean; message?: string } - | { kind: "multipleOf"; value: bigint; message?: string }; - -export interface ZodBigIntDef extends ZodTypeDef { - checks: ZodBigIntCheck[]; - typeName: ZodFirstPartyTypeKind.ZodBigInt; - coerce: boolean; -} - -export class ZodBigInt extends ZodType<bigint, ZodBigIntDef> { - _parse(input: ParseInput): ParseReturnType<bigint> { - if (this._def.coerce) { - input.data = BigInt(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType, - }); - return INVALID; - } - - let ctx: undefined | ParseContext = undefined; - const status = new ParseStatus(); - - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - - return { status: status.value, value: input.data }; - } - - static create = ( - params?: RawCreateParams & { coerce?: boolean } - ): ZodBigInt => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params), - }); - }; - - gte(value: bigint, message?: errorUtil.ErrMessage) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - min = this.gte; - - gt(value: bigint, message?: errorUtil.ErrMessage) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - - lte(value: bigint, message?: errorUtil.ErrMessage) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - max = this.lte; - - lt(value: bigint, message?: errorUtil.ErrMessage) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - - protected setLimit( - kind: "min" | "max", - value: bigint, - inclusive: boolean, - message?: string - ) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - - _addCheck(check: ZodBigIntCheck) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - - positive(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); - } - - negative(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); - } - - nonpositive(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); - } - - nonnegative(message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); - } - - multipleOf(value: bigint, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message), - }); - } - - get minValue() { - let min: bigint | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) min = ch.value; - } - } - return min; - } - - get maxValue() { - let max: bigint | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) max = ch.value; - } - } - return max; - } -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// /////////// -////////// ZodBoolean ////////// -////////// /////////// -////////////////////////////////////////// -////////////////////////////////////////// -export interface ZodBooleanDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodBoolean; - coerce: boolean; -} - -export class ZodBoolean extends ZodType<boolean, ZodBooleanDef> { - _parse(input: ParseInput): ParseReturnType<boolean> { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } - - static create = ( - params?: RawCreateParams & { coerce?: boolean } - ): ZodBoolean => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params), - }); - }; -} - -/////////////////////////////////////// -/////////////////////////////////////// -////////// //////// -////////// ZodDate //////// -////////// //////// -/////////////////////////////////////// -/////////////////////////////////////// -export type ZodDateCheck = - | { kind: "min"; value: number; message?: string } - | { kind: "max"; value: number; message?: string }; -export interface ZodDateDef extends ZodTypeDef { - checks: ZodDateCheck[]; - coerce: boolean; - typeName: ZodFirstPartyTypeKind.ZodDate; -} - -export class ZodDate extends ZodType<Date, ZodDateDef> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - - if (parsedType !== ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx.parsedType, - }); - return INVALID; - } - - if (isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_date, - }); - return INVALID; - } - - const status = new ParseStatus(); - let ctx: undefined | ParseContext = undefined; - - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - - return { - status: status.value, - value: new Date((input.data as Date).getTime()), - }; - } - - _addCheck(check: ZodDateCheck) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - - min(minDate: Date, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message), - }); - } - - max(maxDate: Date, message?: errorUtil.ErrMessage) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message), - }); - } - - get minDate() { - let min: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) min = ch.value; - } - } - - return min != null ? new Date(min) : null; - } - - get maxDate() { - let max: number | null = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) max = ch.value; - } - } - - return max != null ? new Date(max) : null; - } - - static create = ( - params?: RawCreateParams & { coerce?: boolean } - ): ZodDate => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params), - }); - }; -} - -//////////////////////////////////////////// -//////////////////////////////////////////// -////////// ////////// -////////// ZodSymbol ////////// -////////// ////////// -//////////////////////////////////////////// -//////////////////////////////////////////// -export interface ZodSymbolDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodSymbol; -} - -export class ZodSymbol extends ZodType<symbol, ZodSymbolDef, symbol> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType, - }); - return INVALID; - } - - return OK(input.data); - } - - static create = (params?: RawCreateParams): ZodSymbol => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); - }; -} - -//////////////////////////////////////////// -//////////////////////////////////////////// -////////// ////////// -////////// ZodUndefined ////////// -////////// ////////// -//////////////////////////////////////////// -//////////////////////////////////////////// -export interface ZodUndefinedDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodUndefined; -} - -export class ZodUndefined extends ZodType<undefined, ZodUndefinedDef> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } - params?: RawCreateParams; - - static create = (params?: RawCreateParams): ZodUndefined => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params), - }); - }; -} - -/////////////////////////////////////// -/////////////////////////////////////// -////////// ////////// -////////// ZodNull ////////// -////////// ////////// -/////////////////////////////////////// -/////////////////////////////////////// -export interface ZodNullDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodNull; -} - -export class ZodNull extends ZodType<null, ZodNullDef> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } - static create = (params?: RawCreateParams): ZodNull => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////// -////////////////////////////////////// -////////// ////////// -////////// ZodAny ////////// -////////// ////////// -////////////////////////////////////// -////////////////////////////////////// -export interface ZodAnyDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodAny; -} - -export class ZodAny extends ZodType<any, ZodAnyDef> { - // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. - _any = true as const; - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - return OK(input.data); - } - static create = (params?: RawCreateParams): ZodAny => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodUnknown ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// -export interface ZodUnknownDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodUnknown; -} - -export class ZodUnknown extends ZodType<unknown, ZodUnknownDef> { - // required - _unknown = true as const; - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - return OK(input.data); - } - - static create = (params?: RawCreateParams): ZodUnknown => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); - }; -} - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// ZodNever ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -export interface ZodNeverDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodNever; -} - -export class ZodNever extends ZodType<never, ZodNeverDef> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType, - }); - return INVALID; - } - static create = (params?: RawCreateParams): ZodNever => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); - }; -} - -/////////////////////////////////////// -/////////////////////////////////////// -////////// ////////// -////////// ZodVoid ////////// -////////// ////////// -/////////////////////////////////////// -/////////////////////////////////////// -export interface ZodVoidDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodVoid; -} - -export class ZodVoid extends ZodType<void, ZodVoidDef> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } - - static create = (params?: RawCreateParams): ZodVoid => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params), - }); - }; -} - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// ZodArray ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -export interface ZodArrayDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - type: T; - typeName: ZodFirstPartyTypeKind.ZodArray; - exactLength: { value: number; message?: string } | null; - minLength: { value: number; message?: string } | null; - maxLength: { value: number; message?: string } | null; -} - -export type ArrayCardinality = "many" | "atleastone"; -export type arrayOutputType< - T extends ZodTypeAny, - Cardinality extends ArrayCardinality = "many" -> = Cardinality extends "atleastone" - ? [T["_output"], ...T["_output"][]] - : T["_output"][]; - -export class ZodArray< - T extends ZodTypeAny, - Cardinality extends ArrayCardinality = "many" -> extends ZodType< - arrayOutputType<T, Cardinality>, - ZodArrayDef<T>, - Cardinality extends "atleastone" - ? [T["_input"], ...T["_input"][]] - : T["_input"][] -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx, status } = this._processInputParams(input); - - const def = this._def; - - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return INVALID; - } - - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined) as number, - maximum: (tooBig ? def.exactLength.value : undefined) as number, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } - } - - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); - } - } - - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); - } - } - - if (ctx.common.async) { - return Promise.all( - ([...ctx.data] as any[]).map((item, i) => { - return def.type._parseAsync( - new ParseInputLazyPath(ctx, item, ctx.path, i) - ); - }) - ).then((result) => { - return ParseStatus.mergeArray(status, result); - }); - } - - const result = ([...ctx.data] as any[]).map((item, i) => { - return def.type._parseSync( - new ParseInputLazyPath(ctx, item, ctx.path, i) - ); - }); - - return ParseStatus.mergeArray(status, result); - } - - get element() { - return this._def.type; - } - - min(minLength: number, message?: errorUtil.ErrMessage): this { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) }, - }) as any; - } - - max(maxLength: number, message?: errorUtil.ErrMessage): this { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) }, - }) as any; - } - - length(len: number, message?: errorUtil.ErrMessage): this { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) }, - }) as any; - } - - nonempty(message?: errorUtil.ErrMessage): ZodArray<T, "atleastone"> { - return this.min(1, message) as any; - } - - static create = <T extends ZodTypeAny>( - schema: T, - params?: RawCreateParams - ): ZodArray<T> => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params), - }); - }; -} - -export type ZodNonEmptyArray<T extends ZodTypeAny> = ZodArray<T, "atleastone">; - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodObject ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// - -export type UnknownKeysParam = "passthrough" | "strict" | "strip"; - -export interface ZodObjectDef< - T extends ZodRawShape = ZodRawShape, - UnknownKeys extends UnknownKeysParam = UnknownKeysParam, - Catchall extends ZodTypeAny = ZodTypeAny -> extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodObject; - shape: () => T; - catchall: Catchall; - unknownKeys: UnknownKeys; -} - -export type mergeTypes<A, B> = { - [k in keyof A | keyof B]: k extends keyof B - ? B[k] - : k extends keyof A - ? A[k] - : never; -}; - -export type objectOutputType< - Shape extends ZodRawShape, - Catchall extends ZodTypeAny, - UnknownKeys extends UnknownKeysParam = UnknownKeysParam -> = objectUtil.flatten< - objectUtil.addQuestionMarks<baseObjectOutputType<Shape>> -> & - CatchallOutput<Catchall> & - PassthroughType<UnknownKeys>; - -export type baseObjectOutputType<Shape extends ZodRawShape> = { - [k in keyof Shape]: Shape[k]["_output"]; -}; - -export type objectInputType< - Shape extends ZodRawShape, - Catchall extends ZodTypeAny, - UnknownKeys extends UnknownKeysParam = UnknownKeysParam -> = objectUtil.flatten<baseObjectInputType<Shape>> & - CatchallInput<Catchall> & - PassthroughType<UnknownKeys>; -export type baseObjectInputType<Shape extends ZodRawShape> = - objectUtil.addQuestionMarks<{ - [k in keyof Shape]: Shape[k]["_input"]; - }>; - -export type CatchallOutput<T extends ZodType> = ZodType extends T - ? unknown - : { [k: string]: T["_output"] }; - -export type CatchallInput<T extends ZodType> = ZodType extends T - ? unknown - : { [k: string]: T["_input"] }; - -export type PassthroughType<T extends UnknownKeysParam> = - T extends "passthrough" ? { [k: string]: unknown } : unknown; - -export type deoptional<T extends ZodTypeAny> = T extends ZodOptional<infer U> - ? deoptional<U> - : T extends ZodNullable<infer U> - ? ZodNullable<deoptional<U>> - : T; - -export type SomeZodObject = ZodObject< - ZodRawShape, - UnknownKeysParam, - ZodTypeAny ->; - -export type noUnrecognized<Obj extends object, Shape extends object> = { - [k in keyof Obj]: k extends keyof Shape ? Obj[k] : never; -}; - -function deepPartialify(schema: ZodTypeAny): any { - if (schema instanceof ZodObject) { - const newShape: any = {}; - - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, - }) as any; - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create( - schema.items.map((item: any) => deepPartialify(item)) - ); - } else { - return schema; - } -} - -export class ZodObject< - T extends ZodRawShape, - UnknownKeys extends UnknownKeysParam = UnknownKeysParam, - Catchall extends ZodTypeAny = ZodTypeAny, - Output = objectOutputType<T, Catchall, UnknownKeys>, - Input = objectInputType<T, Catchall, UnknownKeys> -> extends ZodType<Output, ZodObjectDef<T, UnknownKeys, Catchall>, Input> { - private _cached: { shape: T; keys: string[] } | null = null; - - _getCached(): { shape: T; keys: string[] } { - if (this._cached !== null) return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - return (this._cached = { shape, keys }); - } - - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - - const { status, ctx } = this._processInputParams(input); - - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys: string[] = []; - - if ( - !( - this._def.catchall instanceof ZodNever && - this._def.unknownKeys === "strip" - ) - ) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - - const pairs: { - key: ParseReturnType<any>; - value: ParseReturnType<any>; - alwaysSet?: boolean; - }[] = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - ), - alwaysSet: key in ctx.data, - }); - } - - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } - } else if (unknownKeys === "strip") { - } else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - // run catchall validation - const catchall = this._def.catchall; - - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data, - }); - } - } - - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs: any[] = []; - for (const pair of pairs) { - const key = await pair.key; - syncPairs.push({ - key, - value: await pair.value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs as any); - } - } - - get shape() { - return this._def.shape(); - } - - strict(message?: errorUtil.ErrMessage): ZodObject<T, "strict", Catchall> { - errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - const defaultError = - this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError, - }; - return { - message: defaultError, - }; - }, - } - : {}), - }) as any; - } - - strip(): ZodObject<T, "strip", Catchall> { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }) as any; - } - - passthrough(): ZodObject<T, "passthrough", Catchall> { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", - }) as any; - } - - /** - * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. - * If you want to pass through unknown properties, use `.passthrough()` instead. - */ - nonstrict = this.passthrough; - - // const AugmentFactory = - // <Def extends ZodObjectDef>(def: Def) => - // <Augmentation extends ZodRawShape>( - // augmentation: Augmentation - // ): ZodObject< - // extendShape<ReturnType<Def["shape"]>, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend<Augmentation extends ZodRawShape>( - augmentation: Augmentation - ): ZodObject<objectUtil.extendShape<T, Augmentation>, UnknownKeys, Catchall> { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), - }) as any; - } - // extend< - // Augmentation extends ZodRawShape, - // NewOutput extends util.flatten<{ - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }>, - // NewInput extends util.flatten<{ - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // }> - // >( - // augmentation: Augmentation - // ): ZodObject< - // extendShape<T, Augmentation>, - // UnknownKeys, - // Catchall, - // NewOutput, - // NewInput - // > { - // return new ZodObject({ - // ...this._def, - // shape: () => ({ - // ...this._def.shape(), - // ...augmentation, - // }), - // }) as any; - // } - /** - * @deprecated Use `.extend` instead - * */ - augment = this.extend; - - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge<Incoming extends AnyZodObject, Augmentation extends Incoming["shape"]>( - merging: Incoming - ): ZodObject< - objectUtil.extendShape<T, Augmentation>, - Incoming["_def"]["unknownKeys"], - Incoming["_def"]["catchall"] - > { - const merged: any = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, - }) as any; - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - - setKey<Key extends string, Schema extends ZodTypeAny>( - key: Key, - schema: Schema - ): ZodObject<T & { [k in Key]: Schema }, UnknownKeys, Catchall> { - return this.augment({ [key]: schema }) as any; - } - // merge<Incoming extends AnyZodObject>( - // merging: Incoming - // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => { - // ZodObject< - // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - - catchall<Index extends ZodTypeAny>( - index: Index - ): ZodObject<T, UnknownKeys, Index> { - return new ZodObject({ - ...this._def, - catchall: index, - }) as any; - } - - pick<Mask extends { [k in keyof T]?: true }>( - mask: Mask - ): ZodObject<Pick<T, Extract<keyof T, keyof Mask>>, UnknownKeys, Catchall> { - const shape: any = {}; - - util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - }); - - return new ZodObject({ - ...this._def, - shape: () => shape, - }) as any; - } - - omit<Mask extends { [k in keyof T]?: true }>( - mask: Mask - ): ZodObject<Omit<T, keyof Mask>, UnknownKeys, Catchall> { - const shape: any = {}; - - util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - }); - - return new ZodObject({ - ...this._def, - shape: () => shape, - }) as any; - } - - /** - * @deprecated - */ - deepPartial(): partialUtil.DeepPartial<this> { - return deepPartialify(this) as any; - } - - partial(): ZodObject< - { [k in keyof T]: ZodOptional<T[k]> }, - UnknownKeys, - Catchall - >; - partial<Mask extends { [k in keyof T]?: true }>( - mask: Mask - ): ZodObject< - objectUtil.noNever<{ - [k in keyof T]: k extends keyof Mask ? ZodOptional<T[k]> : T[k]; - }>, - UnknownKeys, - Catchall - >; - partial(mask?: any) { - const newShape: any = {}; - - util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - }); - - return new ZodObject({ - ...this._def, - shape: () => newShape, - }) as any; - } - - required(): ZodObject< - { [k in keyof T]: deoptional<T[k]> }, - UnknownKeys, - Catchall - >; - required<Mask extends { [k in keyof T]?: true }>( - mask: Mask - ): ZodObject< - objectUtil.noNever<{ - [k in keyof T]: k extends keyof Mask ? deoptional<T[k]> : T[k]; - }>, - UnknownKeys, - Catchall - >; - required(mask?: any) { - const newShape: any = {}; - - util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - - while (newField instanceof ZodOptional) { - newField = (newField as ZodOptional<any>)._def.innerType; - } - - newShape[key] = newField; - } - }); - - return new ZodObject({ - ...this._def, - shape: () => newShape, - }) as any; - } - - keyof(): ZodEnum<enumUtil.UnionToTupleString<keyof T>> { - return createZodEnum( - util.objectKeys(this.shape) as [string, ...string[]] - ) as any; - } - - static create = <T extends ZodRawShape>( - shape: T, - params?: RawCreateParams - ): ZodObject<T, "strip"> => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }) as any; - }; - - static strictCreate = <T extends ZodRawShape>( - shape: T, - params?: RawCreateParams - ): ZodObject<T, "strict"> => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }) as any; - }; - - static lazycreate = <T extends ZodRawShape>( - shape: () => T, - params?: RawCreateParams - ): ZodObject<T, "strip"> => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }) as any; - }; -} - -export type AnyZodObject = ZodObject<any, any, any>; - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// ZodUnion ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -export type ZodUnionOptions = Readonly<[ZodTypeAny, ...ZodTypeAny[]]>; -export interface ZodUnionDef< - T extends ZodUnionOptions = Readonly< - [ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]] - > -> extends ZodTypeDef { - options: T; - typeName: ZodFirstPartyTypeKind.ZodUnion; -} - -export class ZodUnion<T extends ZodUnionOptions> extends ZodType< - T[number]["_output"], - ZodUnionDef<T>, - T[number]["_input"] -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - - function handleResults( - results: { ctx: ParseContext; result: SyncParseReturnType<any> }[] - ) { - // return first issue-free validation if it exists - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - - for (const result of results) { - if (result.result.status === "dirty") { - // add issues from dirty option - - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - - // return invalid - const unionErrors = results.map( - (result) => new ZodError(result.ctx.common.issues) - ); - - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, - }); - return INVALID; - } - - if (ctx.common.async) { - return Promise.all( - options.map(async (option) => { - const childCtx: ParseContext = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - }) - ).then(handleResults); - } else { - let dirty: undefined | { result: DIRTY<any>; ctx: ParseContext } = - undefined; - const issues: ZodIssue[][] = []; - for (const option of options) { - const childCtx: ParseContext = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - - const unionErrors = issues.map((issues) => new ZodError(issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, - }); - - return INVALID; - } - } - - get options() { - return this._def.options; - } - - static create = < - T extends Readonly<[ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]]> - >( - types: T, - params?: RawCreateParams - ): ZodUnion<T> => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); - }; -} - -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -////////// ////////// -////////// ZodDiscriminatedUnion ////////// -////////// ////////// -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// - -const getDiscriminator = <T extends ZodTypeAny>(type: T): Primitive[] => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - // eslint-disable-next-line ban/ban - return util.objectValues(type.enum as any); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [undefined]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; - -export type ZodDiscriminatedUnionOption<Discriminator extends string> = - ZodObject< - { [key in Discriminator]: ZodTypeAny } & ZodRawShape, - UnknownKeysParam, - ZodTypeAny - >; - -export interface ZodDiscriminatedUnionDef< - Discriminator extends string, - Options extends ZodDiscriminatedUnionOption<string>[] = ZodDiscriminatedUnionOption<string>[] -> extends ZodTypeDef { - discriminator: Discriminator; - options: Options; - optionsMap: Map<Primitive, ZodDiscriminatedUnionOption<any>>; - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion; -} - -export class ZodDiscriminatedUnion< - Discriminator extends string, - Options extends ZodDiscriminatedUnionOption<Discriminator>[] -> extends ZodType< - output<Options[number]>, - ZodDiscriminatedUnionDef<Discriminator, Options>, - input<Options[number]> -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - - const discriminator = this.discriminator; - - const discriminatorValue: string = ctx.data[discriminator]; - - const option = this.optionsMap.get(discriminatorValue); - - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], - }); - return INVALID; - } - - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }) as any; - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }) as any; - } - } - - get discriminator() { - return this._def.discriminator; - } - - get options() { - return this._def.options; - } - - get optionsMap() { - return this._def.optionsMap; - } - - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create< - Discriminator extends string, - Types extends [ - ZodDiscriminatedUnionOption<Discriminator>, - ...ZodDiscriminatedUnionOption<Discriminator>[] - ] - >( - discriminator: Discriminator, - options: Types, - params?: RawCreateParams - ): ZodDiscriminatedUnion<Discriminator, Types> { - // Get all the valid discriminator values - const optionsMap: Map<Primitive, Types[number]> = new Map(); - - // try { - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error( - `A discriminator value for key \`${discriminator}\` could not be extracted from all schema options` - ); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error( - `Discriminator property ${String( - discriminator - )} has duplicate value ${String(value)}` - ); - } - - optionsMap.set(value, type); - } - } - - return new ZodDiscriminatedUnion< - Discriminator, - // DiscriminatorValue, - Types - >({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), - }); - } -} - -/////////////////////////////////////////////// -/////////////////////////////////////////////// -////////// ////////// -////////// ZodIntersection ////////// -////////// ////////// -/////////////////////////////////////////////// -/////////////////////////////////////////////// -export interface ZodIntersectionDef< - T extends ZodTypeAny = ZodTypeAny, - U extends ZodTypeAny = ZodTypeAny -> extends ZodTypeDef { - left: T; - right: U; - typeName: ZodFirstPartyTypeKind.ZodIntersection; -} - -function mergeValues( - a: any, - b: any -): { valid: true; data: any } | { valid: false } { - const aType = getParsedType(a); - const bType = getParsedType(b); - - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util - .objectKeys(a) - .filter((key) => bKeys.indexOf(key) !== -1); - - const newObj: any = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - - const newArray: unknown[] = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - - if (!sharedValue.valid) { - return { valid: false }; - } - - newArray.push(sharedValue.data); - } - - return { valid: true, data: newArray }; - } else if ( - aType === ZodParsedType.date && - bType === ZodParsedType.date && - +a === +b - ) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} - -export class ZodIntersection< - T extends ZodTypeAny, - U extends ZodTypeAny -> extends ZodType< - T["_output"] & U["_output"], - ZodIntersectionDef<T, U>, - T["_input"] & U["_input"] -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - const handleParsed = ( - parsedLeft: SyncParseReturnType, - parsedRight: SyncParseReturnType - ): SyncParseReturnType<T & U> => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - - const merged = mergeValues(parsedLeft.value, parsedRight.value); - - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types, - }); - return INVALID; - } - - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - - return { status: status.value, value: merged.data as any }; - }; - - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]: any) => handleParsed(left, right)); - } else { - return handleParsed( - this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }) - ); - } - } - - static create = <T extends ZodTypeAny, U extends ZodTypeAny>( - left: T, - right: U, - params?: RawCreateParams - ): ZodIntersection<T, U> => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params), - }); - }; -} - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// ZodTuple ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -export type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; -export type AssertArray<T> = T extends any[] ? T : never; -export type OutputTypeOfTuple<T extends ZodTupleItems | []> = AssertArray<{ - [k in keyof T]: T[k] extends ZodType<any, any> ? T[k]["_output"] : never; -}>; -export type OutputTypeOfTupleWithRest< - T extends ZodTupleItems | [], - Rest extends ZodTypeAny | null = null -> = Rest extends ZodTypeAny - ? [...OutputTypeOfTuple<T>, ...Rest["_output"][]] - : OutputTypeOfTuple<T>; - -export type InputTypeOfTuple<T extends ZodTupleItems | []> = AssertArray<{ - [k in keyof T]: T[k] extends ZodType<any, any> ? T[k]["_input"] : never; -}>; -export type InputTypeOfTupleWithRest< - T extends ZodTupleItems | [], - Rest extends ZodTypeAny | null = null -> = Rest extends ZodTypeAny - ? [...InputTypeOfTuple<T>, ...Rest["_input"][]] - : InputTypeOfTuple<T>; - -export interface ZodTupleDef< - T extends ZodTupleItems | [] = ZodTupleItems, - Rest extends ZodTypeAny | null = null -> extends ZodTypeDef { - items: T; - rest: Rest; - typeName: ZodFirstPartyTypeKind.ZodTuple; -} - -export type AnyZodTuple = ZodTuple< - [ZodTypeAny, ...ZodTypeAny[]] | [], - ZodTypeAny | null ->; -export class ZodTuple< - T extends [ZodTypeAny, ...ZodTypeAny[]] | [] = [ZodTypeAny, ...ZodTypeAny[]], - Rest extends ZodTypeAny | null = null -> extends ZodType< - OutputTypeOfTupleWithRest<T, Rest>, - ZodTupleDef<T, Rest>, - InputTypeOfTupleWithRest<T, Rest> -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return INVALID; - } - - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - - return INVALID; - } - - const rest = this._def.rest; - - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - - const items = ([...ctx.data] as any[]) - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) return null as any as SyncParseReturnType<any>; - return schema._parse( - new ParseInputLazyPath(ctx, item, ctx.path, itemIndex) - ); - }) - .filter((x) => !!x); // filter nulls - - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items as SyncParseReturnType[]); - } - } - - get items() { - return this._def.items; - } - - rest<Rest extends ZodTypeAny>(rest: Rest): ZodTuple<T, Rest> { - return new ZodTuple({ - ...this._def, - rest, - }); - } - - static create = <T extends [ZodTypeAny, ...ZodTypeAny[]] | []>( - schemas: T, - params?: RawCreateParams - ): ZodTuple<T, null> => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params), - }); - }; -} - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodRecord ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// -export interface ZodRecordDef< - Key extends KeySchema = ZodString, - Value extends ZodTypeAny = ZodTypeAny -> extends ZodTypeDef { - valueType: Value; - keyType: Key; - typeName: ZodFirstPartyTypeKind.ZodRecord; -} - -export type KeySchema = ZodType<string | number | symbol, any, any>; -export type RecordType<K extends string | number | symbol, V> = [ - string -] extends [K] - ? Record<K, V> - : [number] extends [K] - ? Record<K, V> - : [symbol] extends [K] - ? Record<K, V> - : [BRAND<string | number | symbol>] extends [K] - ? Record<K, V> - : Partial<Record<K, V>>; -export class ZodRecord< - Key extends KeySchema = ZodString, - Value extends ZodTypeAny = ZodTypeAny -> extends ZodType< - RecordType<Key["_output"], Value["_output"]>, - ZodRecordDef<Key, Value>, - RecordType<Key["_input"], Value["_input"]> -> { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - - const pairs: { - key: ParseReturnType<any>; - value: ParseReturnType<any>; - }[] = []; - - const keyType = this._def.keyType; - const valueType = this._def.valueType; - - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse( - new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key) - ), - }); - } - - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs as any); - } - } - - get element() { - return this._def.valueType; - } - - static create<Value extends ZodTypeAny>( - valueType: Value, - params?: RawCreateParams - ): ZodRecord<ZodString, Value>; - static create<Keys extends KeySchema, Value extends ZodTypeAny>( - keySchema: Keys, - valueType: Value, - params?: RawCreateParams - ): ZodRecord<Keys, Value>; - static create(first: any, second?: any, third?: any): ZodRecord<any, any> { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); - } - - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), - }); - } -} - -////////////////////////////////////// -////////////////////////////////////// -////////// ////////// -////////// ZodMap ////////// -////////// ////////// -////////////////////////////////////// -////////////////////////////////////// -export interface ZodMapDef< - Key extends ZodTypeAny = ZodTypeAny, - Value extends ZodTypeAny = ZodTypeAny -> extends ZodTypeDef { - valueType: Value; - keyType: Key; - typeName: ZodFirstPartyTypeKind.ZodMap; -} - -export class ZodMap< - Key extends ZodTypeAny = ZodTypeAny, - Value extends ZodTypeAny = ZodTypeAny -> extends ZodType< - Map<Key["_output"], Value["_output"]>, - ZodMapDef<Key, Value>, - Map<Key["_input"], Value["_input"]> -> { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType, - }); - return INVALID; - } - - const keyType = this._def.keyType; - const valueType = this._def.valueType; - - const pairs = [...(ctx.data as Map<unknown, unknown>).entries()].map( - ([key, value], index) => { - return { - key: keyType._parse( - new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"]) - ), - value: valueType._parse( - new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]) - ), - }; - } - ); - - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key as SyncParseReturnType; - const value = pair.value as SyncParseReturnType; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } - static create = < - Key extends ZodTypeAny = ZodTypeAny, - Value extends ZodTypeAny = ZodTypeAny - >( - keyType: Key, - valueType: Value, - params?: RawCreateParams - ): ZodMap<Key, Value> => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////// -////////////////////////////////////// -////////// ////////// -////////// ZodSet ////////// -////////// ////////// -////////////////////////////////////// -////////////////////////////////////// -export interface ZodSetDef<Value extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - valueType: Value; - typeName: ZodFirstPartyTypeKind.ZodSet; - minSize: { value: number; message?: string } | null; - maxSize: { value: number; message?: string } | null; -} - -export class ZodSet<Value extends ZodTypeAny = ZodTypeAny> extends ZodType< - Set<Value["_output"]>, - ZodSetDef<Value>, - Set<Value["_input"]> -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType, - }); - return INVALID; - } - - const def = this._def; - - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } - } - - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); - } - } - - const valueType = this._def.valueType; - - function finalizeSet(elements: SyncParseReturnType<any>[]) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") return INVALID; - if (element.status === "dirty") status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - - const elements = [...(ctx.data as Set<unknown>).values()].map((item, i) => - valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)) - ); - - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } else { - return finalizeSet(elements as SyncParseReturnType[]); - } - } - - min(minSize: number, message?: errorUtil.ErrMessage): this { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) }, - }) as any; - } - - max(maxSize: number, message?: errorUtil.ErrMessage): this { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) }, - }) as any; - } - - size(size: number, message?: errorUtil.ErrMessage): this { - return this.min(size, message).max(size, message) as any; - } - - nonempty(message?: errorUtil.ErrMessage): ZodSet<Value> { - return this.min(1, message) as any; - } - - static create = <Value extends ZodTypeAny = ZodTypeAny>( - valueType: Value, - params?: RawCreateParams - ): ZodSet<Value> => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params), - }); - }; -} - -/////////////////////////////////////////// -/////////////////////////////////////////// -////////// ////////// -////////// ZodFunction ////////// -////////// ////////// -/////////////////////////////////////////// -/////////////////////////////////////////// -export interface ZodFunctionDef< - Args extends ZodTuple<any, any> = ZodTuple<any, any>, - Returns extends ZodTypeAny = ZodTypeAny -> extends ZodTypeDef { - args: Args; - returns: Returns; - typeName: ZodFirstPartyTypeKind.ZodFunction; -} - -export type OuterTypeOfFunction< - Args extends ZodTuple<any, any>, - Returns extends ZodTypeAny -> = Args["_input"] extends Array<any> - ? (...args: Args["_input"]) => Returns["_output"] - : never; - -export type InnerTypeOfFunction< - Args extends ZodTuple<any, any>, - Returns extends ZodTypeAny -> = Args["_output"] extends Array<any> - ? (...args: Args["_output"]) => Returns["_input"] - : never; - -export class ZodFunction< - Args extends ZodTuple<any, any>, - Returns extends ZodTypeAny -> extends ZodType< - OuterTypeOfFunction<Args, Returns>, - ZodFunctionDef<Args, Returns>, - InnerTypeOfFunction<Args, Returns> -> { - _parse(input: ParseInput): ParseReturnType<any> { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType, - }); - return INVALID; - } - - function makeArgsIssue(args: any, error: ZodError): ZodIssue { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - defaultErrorMap, - ].filter((x) => !!x) as ZodErrorMap[], - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error, - }, - }); - } - - function makeReturnsIssue(returns: any, error: ZodError): ZodIssue { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - defaultErrorMap, - ].filter((x) => !!x) as ZodErrorMap[], - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, - }); - } - - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - - if (this._def.returns instanceof ZodPromise) { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(async function (this: any, ...args: any[]) { - const error = new ZodError([]); - const parsedArgs = await me._def.args - .parseAsync(args, params) - .catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs as any); - const parsedReturns = await ( - me._def.returns as unknown as ZodPromise<ZodTypeAny> - )._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(function (this: any, ...args: any[]) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }) as any; - } - } - - parameters() { - return this._def.args; - } - - returnType() { - return this._def.returns; - } - - args<Items extends Parameters<(typeof ZodTuple)["create"]>[0]>( - ...items: Items - ): ZodFunction<ZodTuple<Items, ZodUnknown>, Returns> { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) as any, - }); - } - - returns<NewReturnType extends ZodType<any, any>>( - returnType: NewReturnType - ): ZodFunction<Args, NewReturnType> { - return new ZodFunction({ - ...this._def, - returns: returnType, - }); - } - - implement<F extends InnerTypeOfFunction<Args, Returns>>( - func: F - ): ReturnType<F> extends Returns["_output"] - ? (...args: Args["_input"]) => ReturnType<F> - : OuterTypeOfFunction<Args, Returns> { - const validatedFunc = this.parse(func); - return validatedFunc as any; - } - - strictImplement( - func: InnerTypeOfFunction<Args, Returns> - ): InnerTypeOfFunction<Args, Returns> { - const validatedFunc = this.parse(func); - return validatedFunc as any; - } - - validate = this.implement; - - static create(): ZodFunction<ZodTuple<[], ZodUnknown>, ZodUnknown>; - static create<T extends AnyZodTuple = ZodTuple<[], ZodUnknown>>( - args: T - ): ZodFunction<T, ZodUnknown>; - static create<T extends AnyZodTuple, U extends ZodTypeAny>( - args: T, - returns: U - ): ZodFunction<T, U>; - static create< - T extends AnyZodTuple = ZodTuple<[], ZodUnknown>, - U extends ZodTypeAny = ZodUnknown - >(args: T, returns: U, params?: RawCreateParams): ZodFunction<T, U>; - static create( - args?: AnyZodTuple, - returns?: ZodTypeAny, - params?: RawCreateParams - ) { - return new ZodFunction({ - args: (args - ? args - : ZodTuple.create([]).rest(ZodUnknown.create())) as any, - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), - }) as any; - } -} - -/////////////////////////////////////// -/////////////////////////////////////// -////////// ////////// -////////// ZodLazy ////////// -////////// ////////// -/////////////////////////////////////// -/////////////////////////////////////// -export interface ZodLazyDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - getter: () => T; - typeName: ZodFirstPartyTypeKind.ZodLazy; -} - -export class ZodLazy<T extends ZodTypeAny> extends ZodType< - output<T>, - ZodLazyDef<T>, - input<T> -> { - get schema(): T { - return this._def.getter(); - } - - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } - - static create = <T extends ZodTypeAny>( - getter: () => T, - params?: RawCreateParams - ): ZodLazy<T> => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodLiteral ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// -export interface ZodLiteralDef<T = any> extends ZodTypeDef { - value: T; - typeName: ZodFirstPartyTypeKind.ZodLiteral; -} - -export class ZodLiteral<T> extends ZodType<T, ZodLiteralDef<T>> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - - get value() { - return this._def.value; - } - - static create = <T extends Primitive>( - value: T, - params?: RawCreateParams - ): ZodLiteral<T> => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); - }; -} - -/////////////////////////////////////// -/////////////////////////////////////// -////////// ////////// -////////// ZodEnum ////////// -////////// ////////// -/////////////////////////////////////// -/////////////////////////////////////// -export type ArrayKeys = keyof any[]; -export type Indices<T> = Exclude<keyof T, ArrayKeys>; - -export type EnumValues = [string, ...string[]]; - -export type Values<T extends EnumValues> = { - [k in T[number]]: k; -}; - -export interface ZodEnumDef<T extends EnumValues = EnumValues> - extends ZodTypeDef { - values: T; - typeName: ZodFirstPartyTypeKind.ZodEnum; -} - -export type Writeable<T> = { -readonly [P in keyof T]: T[P] }; - -export type FilterEnum<Values, ToExclude> = Values extends [] - ? [] - : Values extends [infer Head, ...infer Rest] - ? Head extends ToExclude - ? FilterEnum<Rest, ToExclude> - : [Head, ...FilterEnum<Rest, ToExclude>] - : never; - -export type typecast<A, T> = A extends T ? A : never; - -function createZodEnum<U extends string, T extends Readonly<[U, ...U[]]>>( - values: T, - params?: RawCreateParams -): ZodEnum<Writeable<T>>; -function createZodEnum<U extends string, T extends [U, ...U[]]>( - values: T, - params?: RawCreateParams -): ZodEnum<T>; -function createZodEnum( - values: [string, ...string[]], - params?: RawCreateParams -) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); -} - -export class ZodEnum<T extends [string, ...string[]]> extends ZodType< - T[number], - ZodEnumDef<T> -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues) as "string", - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return INVALID; - } - - if (this._def.values.indexOf(input.data) === -1) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return INVALID; - } - return OK(input.data); - } - - get options() { - return this._def.values; - } - - get enum(): Values<T> { - const enumValues: any = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues as any; - } - - get Values(): Values<T> { - const enumValues: any = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues as any; - } - - get Enum(): Values<T> { - const enumValues: any = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues as any; - } - - extract<ToExtract extends readonly [T[number], ...T[number][]]>( - values: ToExtract, - newDef: RawCreateParams = this._def - ): ZodEnum<Writeable<ToExtract>> { - return ZodEnum.create(values, { - ...this._def, - ...newDef, - }) as any; - } - - exclude<ToExclude extends readonly [T[number], ...T[number][]]>( - values: ToExclude, - newDef: RawCreateParams = this._def - ): ZodEnum< - typecast<Writeable<FilterEnum<T, ToExclude[number]>>, [string, ...string[]]> - > { - return ZodEnum.create( - this.options.filter((opt) => !values.includes(opt)) as FilterEnum< - T, - ToExclude[number] - >, - { - ...this._def, - ...newDef, - } - ) as any; - } - - static create = createZodEnum; -} - -///////////////////////////////////////////// -///////////////////////////////////////////// -////////// ////////// -////////// ZodNativeEnum ////////// -////////// ////////// -///////////////////////////////////////////// -///////////////////////////////////////////// -export interface ZodNativeEnumDef<T extends EnumLike = EnumLike> - extends ZodTypeDef { - values: T; - typeName: ZodFirstPartyTypeKind.ZodNativeEnum; -} - -export type EnumLike = { [k: string]: string | number; [nu: number]: string }; - -export class ZodNativeEnum<T extends EnumLike> extends ZodType< - T[keyof T], - ZodNativeEnumDef<T> -> { - _parse(input: ParseInput): ParseReturnType<T[keyof T]> { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - - const ctx = this._getOrReturnCtx(input); - if ( - ctx.parsedType !== ZodParsedType.string && - ctx.parsedType !== ZodParsedType.number - ) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues) as "string", - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return INVALID; - } - - if (nativeEnumValues.indexOf(input.data) === -1) { - const expectedValues = util.objectValues(nativeEnumValues); - - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return INVALID; - } - return OK(input.data as any); - } - - get enum() { - return this._def.values; - } - - static create = <T extends EnumLike>( - values: T, - params?: RawCreateParams - ): ZodNativeEnum<T> => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodPromise ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// -export interface ZodPromiseDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - type: T; - typeName: ZodFirstPartyTypeKind.ZodPromise; -} - -export class ZodPromise<T extends ZodTypeAny> extends ZodType< - Promise<T["_output"]>, - ZodPromiseDef<T>, - Promise<T["_input"]> -> { - unwrap() { - return this._def.type; - } - - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - if ( - ctx.parsedType !== ZodParsedType.promise && - ctx.common.async === false - ) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType, - }); - return INVALID; - } - - const promisified = - ctx.parsedType === ZodParsedType.promise - ? ctx.data - : Promise.resolve(ctx.data); - - return OK( - promisified.then((data: any) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - }) - ); - } - - static create = <T extends ZodTypeAny>( - schema: T, - params?: RawCreateParams - ): ZodPromise<T> => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////////////// -////////////////////////////////////////////// -////////// ////////// -////////// ZodEffects ////////// -////////// ////////// -////////////////////////////////////////////// -////////////////////////////////////////////// - -export type Refinement<T> = (arg: T, ctx: RefinementCtx) => any; -export type SuperRefinement<T> = ( - arg: T, - ctx: RefinementCtx -) => void | Promise<void>; - -export type RefinementEffect<T> = { - type: "refinement"; - refinement: (arg: T, ctx: RefinementCtx) => any; -}; -export type TransformEffect<T> = { - type: "transform"; - transform: (arg: T, ctx: RefinementCtx) => any; -}; -export type PreprocessEffect<T> = { - type: "preprocess"; - transform: (arg: T, ctx: RefinementCtx) => any; -}; -export type Effect<T> = - | RefinementEffect<T> - | TransformEffect<T> - | PreprocessEffect<T>; - -export interface ZodEffectsDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - schema: T; - typeName: ZodFirstPartyTypeKind.ZodEffects; - effect: Effect<any>; -} - -export class ZodEffects< - T extends ZodTypeAny, - Output = output<T>, - Input = input<T> -> extends ZodType<Output, ZodEffectsDef<T>, Input> { - innerType() { - return this._def.schema; - } - - sourceType(): T { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? (this._def.schema as unknown as ZodEffects<T>).sourceType() - : (this._def.schema as T); - } - - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { status, ctx } = this._processInputParams(input); - - const effect = this._def.effect || null; - - const checkCtx: RefinementCtx = { - addIssue: (arg: IssueData) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - }, - }; - - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") return INVALID; - - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") return INVALID; - if (result.status === "dirty") return DIRTY(result.value); - if (status.value === "dirty") return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") return INVALID; - if (result.status === "dirty") return DIRTY(result.value); - if (status.value === "dirty") return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc: unknown): any => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error( - "Async refinement encountered during synchronous parse operation. Use .parseAsync instead." - ); - } - return acc; - }; - - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") return INVALID; - if (inner.status === "dirty") status.dirty(); - - // return value is ignored - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((inner) => { - if (inner.status === "aborted") return INVALID; - if (inner.status === "dirty") status.dirty(); - - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - - if (!isValid(base)) return base; - - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error( - `Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.` - ); - } - - return { status: status.value, value: result }; - } else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((base) => { - if (!isValid(base)) return base; - - return Promise.resolve(effect.transform(base.value, checkCtx)).then( - (result) => ({ status: status.value, value: result }) - ); - }); - } - } - - util.assertNever(effect); - } - - static create = <I extends ZodTypeAny>( - schema: I, - effect: Effect<I["_output"]>, - params?: RawCreateParams - ): ZodEffects<I, I["_output"]> => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); - }; - - static createWithPreprocess = <I extends ZodTypeAny>( - preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, - schema: I, - params?: RawCreateParams - ): ZodEffects<I, I["_output"], unknown> => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params), - }); - }; -} - -export { ZodEffects as ZodTransformer }; - -/////////////////////////////////////////// -/////////////////////////////////////////// -////////// ////////// -////////// ZodOptional ////////// -////////// ////////// -/////////////////////////////////////////// -/////////////////////////////////////////// -export interface ZodOptionalDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - innerType: T; - typeName: ZodFirstPartyTypeKind.ZodOptional; -} - -export type ZodOptionalType<T extends ZodTypeAny> = ZodOptional<T>; - -export class ZodOptional<T extends ZodTypeAny> extends ZodType< - T["_output"] | undefined, - ZodOptionalDef<T>, - T["_input"] | undefined -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(undefined); - } - return this._def.innerType._parse(input); - } - - unwrap() { - return this._def.innerType; - } - - static create = <T extends ZodTypeAny>( - type: T, - params?: RawCreateParams - ): ZodOptional<T> => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }) as any; - }; -} - -/////////////////////////////////////////// -/////////////////////////////////////////// -////////// ////////// -////////// ZodNullable ////////// -////////// ////////// -/////////////////////////////////////////// -/////////////////////////////////////////// -export interface ZodNullableDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - innerType: T; - typeName: ZodFirstPartyTypeKind.ZodNullable; -} - -export type ZodNullableType<T extends ZodTypeAny> = ZodNullable<T>; - -export class ZodNullable<T extends ZodTypeAny> extends ZodType< - T["_output"] | null, - ZodNullableDef<T>, - T["_input"] | null -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - - unwrap() { - return this._def.innerType; - } - - static create = <T extends ZodTypeAny>( - type: T, - params?: RawCreateParams - ): ZodNullable<T> => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }) as any; - }; -} - -//////////////////////////////////////////// -//////////////////////////////////////////// -////////// ////////// -////////// ZodDefault ////////// -////////// ////////// -//////////////////////////////////////////// -//////////////////////////////////////////// -export interface ZodDefaultDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - innerType: T; - defaultValue: () => util.noUndefined<T["_input"]>; - typeName: ZodFirstPartyTypeKind.ZodDefault; -} - -export class ZodDefault<T extends ZodTypeAny> extends ZodType< - util.noUndefined<T["_output"]>, - ZodDefaultDef<T>, - T["_input"] | undefined -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - - removeDefault() { - return this._def.innerType; - } - - static create = <T extends ZodTypeAny>( - type: T, - params: RawCreateParams & { - default: T["_input"] | (() => util.noUndefined<T["_input"]>); - } - ): ZodDefault<T> => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: - typeof params.default === "function" - ? params.default - : () => params.default as any, - ...processCreateParams(params), - }) as any; - }; -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodCatch ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// -export interface ZodCatchDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - innerType: T; - catchValue: (ctx: { error: ZodError; input: unknown }) => T["_input"]; - typeName: ZodFirstPartyTypeKind.ZodCatch; -} - -export class ZodCatch<T extends ZodTypeAny> extends ZodType< - T["_output"], - ZodCatchDef<T>, - unknown // any input will pass validation // T["_input"] -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const { ctx } = this._processInputParams(input); - - // newCtx is used to not collect issues from inner types in ctx - const newCtx: ParseContext = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - - if (isAsync(result)) { - return result.then((result) => { - return { - status: "valid", - value: - result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); - } else { - return { - status: "valid", - value: - result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - } - } - - removeCatch() { - return this._def.innerType; - } - - static create = <T extends ZodTypeAny>( - type: T, - params: RawCreateParams & { - catch: T["_output"] | (() => T["_output"]); - } - ): ZodCatch<T> => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: - typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); - }; -} - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodNaN ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// - -export interface ZodNaNDef extends ZodTypeDef { - typeName: ZodFirstPartyTypeKind.ZodNaN; -} - -export class ZodNaN extends ZodType<number, ZodNaNDef> { - _parse(input: ParseInput): ParseReturnType<any> { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType, - }); - return INVALID; - } - - return { status: "valid", value: input.data }; - } - - static create = (params?: RawCreateParams): ZodNaN => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), - }); - }; -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodBranded ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// - -export interface ZodBrandedDef<T extends ZodTypeAny> extends ZodTypeDef { - type: T; - typeName: ZodFirstPartyTypeKind.ZodBranded; -} - -export const BRAND: unique symbol = Symbol("zod_brand"); -export type BRAND<T extends string | number | symbol> = { - [BRAND]: { [k in T]: true }; -}; - -export class ZodBranded< - T extends ZodTypeAny, - B extends string | number | symbol -> extends ZodType<T["_output"] & BRAND<B>, ZodBrandedDef<T>, T["_input"]> { - _parse(input: ParseInput): ParseReturnType<any> { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - - unwrap() { - return this._def.type; - } -} - -//////////////////////////////////////////// -//////////////////////////////////////////// -////////// ////////// -////////// ZodPipeline ////////// -////////// ////////// -//////////////////////////////////////////// -//////////////////////////////////////////// - -export interface ZodPipelineDef<A extends ZodTypeAny, B extends ZodTypeAny> - extends ZodTypeDef { - in: A; - out: B; - typeName: ZodFirstPartyTypeKind.ZodPipeline; -} - -export class ZodPipeline< - A extends ZodTypeAny, - B extends ZodTypeAny -> extends ZodType<B["_output"], ZodPipelineDef<A, B>, A["_input"]> { - _parse(input: ParseInput): ParseReturnType<any> { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - } - } - - static create<A extends ZodTypeAny, B extends ZodTypeAny>( - a: A, - b: B - ): ZodPipeline<A, B> { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, - }); - } -} - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodTemplateLiteral ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// - -type TemplateLiteralPrimitive = string | number | boolean | null | undefined; - -type TemplateLiteralInterpolatedPosition = ZodType< - TemplateLiteralPrimitive | bigint ->; - -type appendToTemplateLiteral< - Template extends string, - Suffix extends TemplateLiteralPrimitive | ZodType -> = Suffix extends TemplateLiteralPrimitive - ? `${Template}${Suffix}` - : Suffix extends ZodOptional<infer UnderlyingType> - ? Template | appendToTemplateLiteral<Template, UnderlyingType> - : Suffix extends ZodBranded<infer UnderlyingType, any> - ? appendToTemplateLiteral<Template, UnderlyingType> - : Suffix extends ZodType<infer Output, any, any> - ? Output extends TemplateLiteralPrimitive | bigint - ? `${Template}${Output}` - : never - : never; - -export interface ZodTemplateLiteralDef extends ZodTypeDef { - coerce: boolean; - parts: readonly ( - | TemplateLiteralPrimitive - | TemplateLiteralInterpolatedPosition - )[]; - regexString: string; - typeName: ZodFirstPartyTypeKind.ZodTemplateLiteral; -} - -export class ZodTemplateLiteral<Template extends string = ""> extends ZodType< - Template, - ZodTemplateLiteralDef -> { - interpolated<I extends TemplateLiteralInterpolatedPosition>( - type: Exclude<I, ZodNever | ZodNaN | ZodPipeline<any, any> | ZodLazy<any>> - ): ZodTemplateLiteral<appendToTemplateLiteral<Template, I>> { - return this._addPart(type) as any; - } - - literal<L extends TemplateLiteralPrimitive>( - literal: L - ): ZodTemplateLiteral<appendToTemplateLiteral<Template, L>> { - return this._addPart(literal) as any; - } - - _parse(input: ParseInput): ParseReturnType<Template> { - if (this._def.coerce) { - input.data = String(input.data); - } - - const parsedType = this._getType(input); - - if (parsedType !== ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx.parsedType, - }); - return INVALID; - } - - if (!new RegExp(this._def.regexString).test(input.data)) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - message: `does not match template literal with pattern /${this._def.regexString}/`, - path: ctx.path, - validation: "regex", - }); - return INVALID; - } - - return { status: "valid", value: input.data }; - } - - protected _addPart( - part: TemplateLiteralPrimitive | TemplateLiteralInterpolatedPosition - ): ZodTemplateLiteral { - const parts = [...this._def.parts, part]; - - return new ZodTemplateLiteral({ - ...this._def, - parts, - regexString: this._appendToRegexString(this._def.regexString, part), - }); - } - - protected _appendToRegexString( - regexString: string, - part: TemplateLiteralPrimitive | TemplateLiteralInterpolatedPosition - ): string { - return `^${this._unwrapRegExp( - regexString - )}${this._transformPartToRegexString(part)}$`; - } - - protected _transformPartToRegexString( - part: TemplateLiteralPrimitive | TemplateLiteralInterpolatedPosition - ): string { - if (!(part instanceof ZodType)) { - return this._escapeRegExp(part); - } - - if (part instanceof ZodLiteral) { - return this._escapeRegExp(part._def.value); - } - - if (part instanceof ZodString) { - return this._transformZodStringPartToRegexString(part); - } - - if (part instanceof ZodEnum || part instanceof ZodNativeEnum) { - const values = - part instanceof ZodEnum - ? part._def.values - : util.getValidEnumValues(part._def.values); - - return `(${values.map(this._escapeRegExp).join("|")})`; - } - - if (part instanceof ZodUnion) { - return `(${(part._def.options as any[]) - .map((option) => this._transformPartToRegexString(option)) - .join("|")})`; - } - - if (part instanceof ZodNumber) { - return this._transformZodNumberPartToRegexString(part); - } - - if (part instanceof ZodOptional) { - return `(${this._transformPartToRegexString(part.unwrap())})?`; - } - - if (part instanceof ZodTemplateLiteral) { - return this._unwrapRegExp(part._def.regexString); - } - - if (part instanceof ZodBigInt) { - // FIXME: include/exclude '-' based on min/max values after https://github.com/colinhacks/zod/pull/1711 is merged. - return "\\-?\\d+"; - } - - if (part instanceof ZodBoolean) { - return "(true|false)"; - } - - if (part instanceof ZodNullable) { - do { - part = part.unwrap(); - } while (part instanceof ZodNullable); - - return `(${this._transformPartToRegexString(part)}|null)${ - part instanceof ZodOptional ? "?" : "" - }`; - } - - if (part instanceof ZodBranded) { - return this._transformPartToRegexString(part.unwrap()); - } - - if (part instanceof ZodAny) { - return ".*"; - } - - if (part instanceof ZodNull) { - return "null"; - } - - if (part instanceof ZodUndefined) { - return "undefined"; - } - - throw new ZodTemplateLiteralUnsupportedTypeError(); - } - - // FIXME: we don't support transformations, so `.trim()` is not supported. - protected _transformZodStringPartToRegexString(part: ZodString): string { - let maxLength = Infinity, - minLength = 0, - endsWith = "", - startsWith = ""; - - for (const ch of part._def.checks) { - const regex = this._resolveRegexForStringCheck(ch); - - if (regex) { - return this._unwrapRegExp(regex); - } - - if (ch.kind === "endsWith") { - endsWith = ch.value; - } else if (ch.kind === "length") { - minLength = maxLength = ch.value; - } else if (ch.kind === "max") { - maxLength = Math.max(0, Math.min(maxLength, ch.value)); - } else if (ch.kind === "min") { - minLength = Math.max(minLength, ch.value); - } else if (ch.kind === "startsWith") { - startsWith = ch.value; - } else { - throw new ZodTemplateLiteralUnsupportedCheckError( - ZodFirstPartyTypeKind.ZodString, - ch.kind - ); - } - } - - const constrainedMinLength = Math.max( - 0, - minLength - startsWith.length - endsWith.length - ); - const constrainedMaxLength = Number.isFinite(maxLength) - ? Math.max(0, maxLength - startsWith.length - endsWith.length) - : Infinity; - - if ( - constrainedMaxLength === 0 || - constrainedMinLength > constrainedMaxLength - ) { - return `${startsWith}${endsWith}`; - } - - return `${startsWith}.${this._resolveRegexWildcardLength( - constrainedMinLength, - constrainedMaxLength - )}${endsWith}`; - } - - protected _resolveRegexForStringCheck(check: ZodStringCheck): RegExp | null { - return { - [check.kind]: null, - cuid: cuidRegex, - cuid2: cuid2Regex, - datetime: check.kind === "datetime" ? datetimeRegex(check) : null, - email: emailRegex, - ip: - check.kind === "ip" - ? { - any: new RegExp( - `^(${this._unwrapRegExp( - ipv4Regex.source - )})|(${this._unwrapRegExp(ipv6Regex.source)})$` - ), - v4: ipv4Regex, - v6: ipv6Regex, - }[check.version || "any"] - : null, - regex: check.kind === "regex" ? check.regex : null, - ulid: ulidRegex, - uuid: uuidRegex, - }[check.kind]; - } - - protected _resolveRegexWildcardLength( - minLength: number, - maxLength: number - ): string { - if (minLength === maxLength) { - return minLength === 1 ? "" : `{${minLength}}`; - } - - if (maxLength !== Infinity) { - return `{${minLength},${maxLength}}`; - } - - if (minLength === 0) { - return "*"; - } - - if (minLength === 1) { - return "+"; - } - - return `{${minLength},}`; - } - - // FIXME: we do not support exponent notation (e.g. 2e5) since it conflicts with `.int()`. - protected _transformZodNumberPartToRegexString(part: ZodNumber): string { - let canBeNegative = true, - canBePositive = true, - min = -Infinity, - max = Infinity, - canBeZero = true, - isFinite = false, - isInt = false, - acc = ""; - - for (const ch of part._def.checks) { - if (ch.kind === "finite") { - isFinite = true; - } else if (ch.kind === "int") { - isInt = true; - } else if (ch.kind === "max") { - max = Math.min(max, ch.value); - - if (ch.value <= 0) { - canBePositive = false; - - if (ch.value === 0 && !ch.inclusive) { - canBeZero = false; - } - } - } else if (ch.kind === "min") { - min = Math.max(min, ch.value); - - if (ch.value >= 0) { - canBeNegative = false; - - if (ch.value === 0 && !ch.inclusive) { - canBeZero = false; - } - } - } else { - throw new ZodTemplateLiteralUnsupportedCheckError( - ZodFirstPartyTypeKind.ZodNumber, - ch.kind - ); - } - } - - if (Number.isFinite(min) && Number.isFinite(max)) { - isFinite = true; - } - - if (canBeNegative) { - acc = `${acc}\\-`; - - if (canBePositive) { - acc = `${acc}?`; - } - } else if (!canBePositive) { - return "0+"; - } - - if (!isFinite) { - acc = `${acc}(Infinity|(`; - } - - if (!canBeZero) { - if (!isInt) { - acc = `${acc}((\\d*[1-9]\\d*(\\.\\d+)?)|(\\d+\\.\\d*[1-9]\\d*))`; - } else { - acc = `${acc}\\d*[1-9]\\d*`; - } - } else if (isInt) { - acc = `${acc}\\d+`; - } else { - acc = `${acc}\\d+(\\.\\d+)?`; - } - - if (!isFinite) { - acc = `${acc}))`; - } - - return acc; - } - - protected _unwrapRegExp(regex: RegExp | string): string { - const flags = typeof regex === "string" ? "" : regex.flags; - const source = typeof regex === "string" ? regex : regex.source; - - if (flags.includes("i")) { - return this._unwrapRegExp(this._makeRegexStringCaseInsensitive(source)); - } - - return source.replace(/(^\^)|(\$$)/g, ""); - } - - protected _makeRegexStringCaseInsensitive(regexString: string): string { - const isAlphabetic = (char: string) => char.match(/[a-z]/i) != null; - - let caseInsensitive = ""; - let inCharacterSet = false; - for (let i = 0; i < regexString.length; i++) { - const char = regexString.charAt(i); - const nextChar = regexString.charAt(i + 1); - - if (char === "\\") { - caseInsensitive += `${char}${nextChar}`; - i++; - continue; - } - - if (char === "[") { - inCharacterSet = true; - } else if (inCharacterSet && char === "]") { - inCharacterSet = false; - } - - if (!isAlphabetic(char)) { - caseInsensitive += char; - continue; - } - - if (!inCharacterSet) { - caseInsensitive += `[${char.toLowerCase()}${char.toUpperCase()}]`; - continue; - } - - const charAfterNext = regexString.charAt(i + 2); - - if (nextChar !== "-" || !isAlphabetic(charAfterNext)) { - caseInsensitive += `${char.toLowerCase()}${char.toUpperCase()}`; - continue; - } - - caseInsensitive += `${char.toLowerCase()}-${charAfterNext.toLowerCase()}${char.toUpperCase()}-${charAfterNext.toUpperCase()}`; - i += 2; - } - - return caseInsensitive; - } - - protected _escapeRegExp(str: unknown): string { - if (typeof str !== "string") { - str = `${str}`; - } - - return (str as string).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - } - - static create = ( - params?: RawCreateParams & { coerce?: true } - ): ZodTemplateLiteral => { - return new ZodTemplateLiteral({ - ...processCreateParams(params), - coerce: params?.coerce ?? false, - parts: [], - regexString: "^$", - typeName: ZodFirstPartyTypeKind.ZodTemplateLiteral, - }); - }; -} - -/////////////////////////////////////////// -/////////////////////////////////////////// -////////// ////////// -////////// ZodReadonly ////////// -////////// ////////// -/////////////////////////////////////////// -/////////////////////////////////////////// -type BuiltIn = - | (((...args: any[]) => any) | (new (...args: any[]) => any)) - | { readonly [Symbol.toStringTag]: string } - | Date - | Error - | Generator - | Promise<unknown> - | RegExp; - -type MakeReadonly<T> = T extends Map<infer K, infer V> - ? ReadonlyMap<K, V> - : T extends Set<infer V> - ? ReadonlySet<V> - : T extends [infer Head, ...infer Tail] - ? readonly [Head, ...Tail] - : T extends Array<infer V> - ? ReadonlyArray<V> - : T extends BuiltIn - ? T - : Readonly<T>; - -export interface ZodReadonlyDef<T extends ZodTypeAny = ZodTypeAny> - extends ZodTypeDef { - innerType: T; - typeName: ZodFirstPartyTypeKind.ZodReadonly; -} - -export class ZodReadonly<T extends ZodTypeAny> extends ZodType< - MakeReadonly<T["_output"]>, - ZodReadonlyDef<T>, - MakeReadonly<T["_input"]> -> { - _parse(input: ParseInput): ParseReturnType<this["_output"]> { - const result = this._def.innerType._parse(input); - if (isValid(result)) { - result.value = Object.freeze(result.value); - } - return result; - } - - static create = <T extends ZodTypeAny>( - type: T, - params?: RawCreateParams - ): ZodReadonly<T> => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params), - }) as any; - }; - - unwrap() { - return this._def.innerType; - } -} - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// z.custom ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -type CustomParams = CustomErrorParams & { fatal?: boolean }; -export const custom = <T>( - check?: (data: unknown) => any, - params: string | CustomParams | ((input: any) => CustomParams) = {}, - /** - * @deprecated - * - * Pass `fatal` into the params object instead: - * - * ```ts - * z.string().custom((val) => val.length > 5, { fatal: false }) - * ``` - * - */ - fatal?: boolean -): ZodType<T> => { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - if (!check(data)) { - const p = - typeof params === "function" - ? params(data) - : typeof params === "string" - ? { message: params } - : params; - const _fatal = p.fatal ?? fatal ?? true; - const p2 = typeof p === "string" ? { message: p } : p; - ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); - } - }); - return ZodAny.create(); -}; - -export { ZodType as Schema, ZodType as ZodSchema }; - -export const late = { - object: ZodObject.lazycreate, -}; - -export enum ZodFirstPartyTypeKind { - ZodString = "ZodString", - ZodNumber = "ZodNumber", - ZodNaN = "ZodNaN", - ZodBigInt = "ZodBigInt", - ZodBoolean = "ZodBoolean", - ZodDate = "ZodDate", - ZodSymbol = "ZodSymbol", - ZodUndefined = "ZodUndefined", - ZodNull = "ZodNull", - ZodAny = "ZodAny", - ZodUnknown = "ZodUnknown", - ZodNever = "ZodNever", - ZodVoid = "ZodVoid", - ZodArray = "ZodArray", - ZodObject = "ZodObject", - ZodUnion = "ZodUnion", - ZodDiscriminatedUnion = "ZodDiscriminatedUnion", - ZodIntersection = "ZodIntersection", - ZodTuple = "ZodTuple", - ZodRecord = "ZodRecord", - ZodMap = "ZodMap", - ZodSet = "ZodSet", - ZodFunction = "ZodFunction", - ZodLazy = "ZodLazy", - ZodLiteral = "ZodLiteral", - ZodEnum = "ZodEnum", - ZodEffects = "ZodEffects", - ZodNativeEnum = "ZodNativeEnum", - ZodOptional = "ZodOptional", - ZodNullable = "ZodNullable", - ZodDefault = "ZodDefault", - ZodCatch = "ZodCatch", - ZodPromise = "ZodPromise", - ZodBranded = "ZodBranded", - ZodPipeline = "ZodPipeline", - ZodTemplateLiteral = "ZodTemplateLiteral", - ZodReadonly = "ZodReadonly", -} -export type ZodFirstPartySchemaTypes = - | ZodString - | ZodNumber - | ZodNaN - | ZodBigInt - | ZodBoolean - | ZodDate - | ZodUndefined - | ZodNull - | ZodAny - | ZodUnknown - | ZodNever - | ZodVoid - | ZodArray<any, any> - | ZodObject<any, any, any> - | ZodUnion<any> - | ZodDiscriminatedUnion<any, any> - | ZodIntersection<any, any> - | ZodTuple<any, any> - | ZodRecord<any, any> - | ZodMap<any> - | ZodSet<any> - | ZodFunction<any, any> - | ZodLazy<any> - | ZodLiteral<any> - | ZodEnum<any> - | ZodEffects<any, any, any> - | ZodNativeEnum<any> - | ZodOptional<any> - | ZodNullable<any> - | ZodDefault<any> - | ZodCatch<any> - | ZodPromise<any> - | ZodBranded<any, any> - | ZodPipeline<any, any> - | ZodReadonly<any> - | ZodSymbol - | ZodTemplateLiteral<any>; - -// requires TS 4.4+ -abstract class Class { - constructor(..._: any[]) {} -} -const instanceOfType = <T extends typeof Class>( - // const instanceOfType = <T extends new (...args: any[]) => any>( - cls: T, - params: CustomParams = { - message: `Input not instance of ${cls.name}`, - } -) => custom<InstanceType<T>>((data) => data instanceof cls, params); - -const stringType = ZodString.create; -const numberType = ZodNumber.create; -const nanType = ZodNaN.create; -const bigIntType = ZodBigInt.create; -const booleanType = ZodBoolean.create; -const dateType = ZodDate.create; -const symbolType = ZodSymbol.create; -const undefinedType = ZodUndefined.create; -const nullType = ZodNull.create; -const anyType = ZodAny.create; -const unknownType = ZodUnknown.create; -const neverType = ZodNever.create; -const voidType = ZodVoid.create; -const arrayType = ZodArray.create; -const objectType = ZodObject.create; -const strictObjectType = ZodObject.strictCreate; -const unionType = ZodUnion.create; -const discriminatedUnionType = ZodDiscriminatedUnion.create; -const intersectionType = ZodIntersection.create; -const tupleType = ZodTuple.create; -const recordType = ZodRecord.create; -const mapType = ZodMap.create; -const setType = ZodSet.create; -const functionType = ZodFunction.create; -const lazyType = ZodLazy.create; -const literalType = ZodLiteral.create; -const enumType = ZodEnum.create; -const nativeEnumType = ZodNativeEnum.create; -const promiseType = ZodPromise.create; -const effectsType = ZodEffects.create; -const optionalType = ZodOptional.create; -const nullableType = ZodNullable.create; -const preprocessType = ZodEffects.createWithPreprocess; -const pipelineType = ZodPipeline.create; -const templateLiteralType = ZodTemplateLiteral.create; -const ostring = () => stringType().optional(); -const onumber = () => numberType().optional(); -const oboolean = () => booleanType().optional(); - -export const coerce = { - string: ((arg) => - ZodString.create({ ...arg, coerce: true })) as (typeof ZodString)["create"], - number: ((arg) => - ZodNumber.create({ ...arg, coerce: true })) as (typeof ZodNumber)["create"], - boolean: ((arg) => - ZodBoolean.create({ - ...arg, - coerce: true, - })) as (typeof ZodBoolean)["create"], - bigint: ((arg) => - ZodBigInt.create({ ...arg, coerce: true })) as (typeof ZodBigInt)["create"], - date: ((arg) => - ZodDate.create({ ...arg, coerce: true })) as (typeof ZodDate)["create"], - templateLiteral: ((arg) => - ZodTemplateLiteral.create({ - ...arg, - coerce: true, - })) as (typeof ZodTemplateLiteral)["create"], -}; - -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, - pipelineType as pipeline, - preprocessType as preprocess, - promiseType as promise, - recordType as record, - setType as set, - strictObjectType as strictObject, - stringType as string, - symbolType as symbol, - templateLiteralType as templateLiteral, - effectsType as transformer, - tupleType as tuple, - undefinedType as undefined, - unionType as union, - unknownType as unknown, - voidType as void, -}; - -export const NEVER = INVALID as never; diff --git a/src/types/any.ts b/src/types/any.ts new file mode 100644 index 000000000..8481927bb --- /dev/null +++ b/src/types/any.ts @@ -0,0 +1,26 @@ +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "./index"; +import { processCreateParams } from "./utils"; +import { OK, ParseInput, ParseReturnType } from "./utils/parseUtil"; + +export interface ZodAnyDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodAny; +} + +export class ZodAny extends ZodType<any, ZodAnyDef> { + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + _any = true as const; + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + return OK(input.data); + } + static create = (params?: RawCreateParams): ZodAny => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/array.ts b/src/types/array.ts new file mode 100644 index 000000000..83542319a --- /dev/null +++ b/src/types/array.ts @@ -0,0 +1,169 @@ +import { ZodIssueCode } from "./error"; +import { + ParseInputLazyPath, + RawCreateParams, + ZodFirstPartyTypeKind, ZodType, + ZodTypeAny, + ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { errorUtil } from "./utils/errorUtil"; +import { + addIssueToContext, + INVALID, + ParseInput, + ParseReturnType, + ParseStatus, +} from "./utils/parseUtil"; + +export interface ZodArrayDef<T extends ZodTypeAny = ZodTypeAny> + extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodArray; + exactLength: { value: number; message?: string } | null; + minLength: { value: number; message?: string } | null; + maxLength: { value: number; message?: string } | null; +} + +export type ArrayCardinality = "many" | "atleastone"; +export type arrayOutputType< + T extends ZodTypeAny, + Cardinality extends ArrayCardinality = "many" +> = Cardinality extends "atleastone" + ? [T["_output"], ...T["_output"][]] + : T["_output"][]; + +export class ZodArray< + T extends ZodTypeAny, + Cardinality extends ArrayCardinality = "many" +> extends ZodType< + arrayOutputType<T, Cardinality>, + ZodArrayDef<T>, + Cardinality extends "atleastone" + ? [T["_input"], ...T["_input"][]] + : T["_input"][] +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { ctx, status } = this._processInputParams(input); + + const def = this._def; + + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined) as number, + maximum: (tooBig ? def.exactLength.value : undefined) as number, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + + if (ctx.common.async) { + return Promise.all( + ([...ctx.data] as any[]).map((item, i) => { + return def.type._parseAsync( + new ParseInputLazyPath(ctx, item, ctx.path, i) + ); + }) + ).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + + const result = ([...ctx.data] as any[]).map((item, i) => { + return def.type._parseSync( + new ParseInputLazyPath(ctx, item, ctx.path, i) + ); + }); + + return ParseStatus.mergeArray(status, result); + } + + get element() { + return this._def.type; + } + + min(minLength: number, message?: errorUtil.ErrMessage): this { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }) as any; + } + + max(maxLength: number, message?: errorUtil.ErrMessage): this { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }) as any; + } + + length(len: number, message?: errorUtil.ErrMessage): this { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }) as any; + } + + nonempty(message?: errorUtil.ErrMessage): ZodArray<T, "atleastone"> { + return this.min(1, message) as any; + } + + static create = <T extends ZodTypeAny>( + schema: T, + params?: RawCreateParams + ): ZodArray<T> => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); + }; +} + +export type ZodNonEmptyArray<T extends ZodTypeAny> = ZodArray<T, "atleastone">; diff --git a/src/types/basetype.ts b/src/types/basetype.ts new file mode 100644 index 000000000..279281bac --- /dev/null +++ b/src/types/basetype.ts @@ -0,0 +1,485 @@ +import { + AsyncParseReturnType, + getParsedType, + isAsync, + IssueData, + isValid, + ParseContext, + ParseInput, + ParseParams, + ParsePath, + ParseReturnType, + ParseStatus, + processCreateParams, + RefinementEffect, + SyncParseReturnType, + util, + ZodArray, + ZodBranded, + ZodCatch, + ZodCustomIssue, + ZodDefault, + ZodEffects, + ZodError, + ZodErrorMap, + ZodFirstPartyTypeKind, + ZodIntersection, + ZodIssueCode, + ZodNullable, + ZodOptional, + ZodPipeline, + ZodPromise, + ZodReadonly, + ZodUnion, +} from "./index"; + +export type RefinementCtx = { + addIssue: (arg: IssueData) => void; + path: (string | number)[]; +}; +export type ZodRawShape = { [k: string]: ZodTypeAny }; +export type ZodTypeAny = ZodType<any, any, any>; +export type TypeOf<T extends ZodType<any, any, any>> = T["_output"]; +export type input<T extends ZodType<any, any, any>> = T["_input"]; +export type output<T extends ZodType<any, any, any>> = T["_output"]; +export type { TypeOf as infer }; + +export type CustomErrorParams = Partial<util.Omit<ZodCustomIssue, "code">>; +export interface ZodTypeDef { + errorMap?: ZodErrorMap; + description?: string; +} +export class ParseInputLazyPath implements ParseInput { + parent: ParseContext; + data: any; + _path: ParsePath; + _key: string | number | (string | number)[]; + _cachedPath: ParsePath = []; + constructor( + parent: ParseContext, + value: any, + path: ParsePath, + key: string | number | (string | number)[] + ) { + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (this._key instanceof Array) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + + return this._cachedPath; + } +} +const handleResult = <Input, Output>( + ctx: ParseContext, + result: SyncParseReturnType<Output> +): + | { success: true; data: Output } + | { success: false; error: ZodError<Input> } => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + + return { + success: false, + get error() { + if ((this as any)._error) return (this as any)._error as Error; + const error = new ZodError(ctx.common.issues); + (this as any)._error = error; + return (this as any)._error; + }, + }; + } +}; + +export type RawCreateParams = + | { + errorMap?: ZodErrorMap; + invalid_type_error?: string; + required_error?: string; + description?: string; + } + | undefined; +export type ProcessedCreateParams = { + errorMap?: ZodErrorMap; + description?: string; +}; +export type SafeParseSuccess<Output> = { + success: true; + data: Output; + error?: never; +}; +export type SafeParseError<Input> = { + success: false; + error: ZodError<Input>; + data?: never; +}; + +export type SafeParseReturnType<Input, Output> = + | SafeParseSuccess<Output> + | SafeParseError<Input>; + +export abstract class ZodType< + Output = any, + Def extends ZodTypeDef = ZodTypeDef, + Input = Output +> { + readonly _type!: Output; + readonly _output!: Output; + readonly _input!: Input; + readonly _def!: Def; + + get description() { + return this._def.description; + } + + abstract _parse(input: ParseInput): ParseReturnType<Output>; + + _getType(input: ParseInput): string { + return getParsedType(input.data); + } + + _getOrReturnCtx( + input: ParseInput, + ctx?: ParseContext | undefined + ): ParseContext { + return ( + ctx || { + common: input.parent.common, + data: input.data, + + parsedType: getParsedType(input.data), + + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + } + ); + } + + _processInputParams(input: ParseInput): { + status: ParseStatus; + ctx: ParseContext; + } { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + + parsedType: getParsedType(input.data), + + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + + _parseSync(input: ParseInput): SyncParseReturnType<Output> { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + + _parseAsync(input: ParseInput): AsyncParseReturnType<Output> { + const result = this._parse(input); + return Promise.resolve(result); + } + + parse(data: unknown, params?: Partial<ParseParams>): Output { + const result = this.safeParse(data, params); + if (result.success) return result.data; + throw result.error; + } + + safeParse( + data: unknown, + params?: Partial<ParseParams> + ): SafeParseReturnType<Input, Output> { + const ctx: ParseContext = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + + return handleResult(ctx, result); + } + + async parseAsync( + data: unknown, + params?: Partial<ParseParams> + ): Promise<Output> { + const result = await this.safeParseAsync(data, params); + if (result.success) return result.data; + throw result.error; + } + + async safeParseAsync( + data: unknown, + params?: Partial<ParseParams> + ): Promise<SafeParseReturnType<Input, Output>> { + const ctx: ParseContext = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data), + }; + + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) + ? maybeAsyncResult + : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + + /** Alias of safeParseAsync */ + spa = this.safeParseAsync; + + refine<RefinedOutput extends Output>( + check: (arg: Output) => arg is RefinedOutput, + message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) + ): ZodEffects<this, RefinedOutput, Input>; + refine( + check: (arg: Output) => unknown | Promise<unknown>, + message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) + ): ZodEffects<this, Output, Input>; + refine( + check: (arg: Output) => unknown, + message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams) + ): ZodEffects<this, Output, Input> { + const getIssueProperties = (val: Output) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => + ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + + refinement<RefinedOutput extends Output>( + check: (arg: Output) => arg is RefinedOutput, + refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) + ): ZodEffects<this, RefinedOutput, Input>; + refinement( + check: (arg: Output) => boolean, + refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) + ): ZodEffects<this, Output, Input>; + refinement( + check: (arg: Output) => unknown, + refinementData: IssueData | ((arg: Output, ctx: RefinementCtx) => IssueData) + ): ZodEffects<this, Output, Input> { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue( + typeof refinementData === "function" + ? refinementData(val, ctx) + : refinementData + ); + return false; + } else { + return true; + } + }); + } + + _refinement( + refinement: RefinementEffect<Output>["refinement"] + ): ZodEffects<this, Output, Input> { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + + superRefine<RefinedOutput extends Output>( + refinement: (arg: Output, ctx: RefinementCtx) => arg is RefinedOutput + ): ZodEffects<this, RefinedOutput, Input>; + superRefine( + refinement: (arg: Output, ctx: RefinementCtx) => void + ): ZodEffects<this, Output, Input>; + superRefine( + refinement: (arg: Output, ctx: RefinementCtx) => Promise<void> + ): ZodEffects<this, Output, Input>; + superRefine( + refinement: (arg: Output, ctx: RefinementCtx) => unknown | Promise<unknown> + ): ZodEffects<this, Output, Input> { + return this._refinement(refinement); + } + + constructor(def: Def) { + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + } + + optional(): ZodOptional<this> { + return ZodOptional.create(this, this._def) as any; + } + nullable(): ZodNullable<this> { + return ZodNullable.create(this, this._def) as any; + } + nullish(): ZodOptional<ZodNullable<this>> { + return this.nullable().optional(); + } + array(): ZodArray<this> { + return ZodArray.create(this, this._def); + } + promise(): ZodPromise<this> { + return ZodPromise.create(this, this._def); + } + + or<T extends ZodTypeAny>(option: T): ZodUnion<[this, T]> { + return ZodUnion.create([this, option], this._def) as any; + } + + and<T extends ZodTypeAny>(incoming: T): ZodIntersection<this, T> { + return ZodIntersection.create(this, incoming, this._def); + } + + transform<NewOut>( + transform: (arg: Output, ctx: RefinementCtx) => NewOut | Promise<NewOut> + ): ZodEffects<this, NewOut> { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }) as any; + } + + default(def: util.noUndefined<Input>): ZodDefault<this>; + default(def: () => util.noUndefined<Input>): ZodDefault<this>; + default(def: any) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }) as any; + } + + brand<B extends string | number | symbol>(brand?: B): ZodBranded<this, B>; + brand<B extends string | number | symbol>(): ZodBranded<this, B> { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + + catch(def: Output): ZodCatch<this>; + catch( + def: (ctx: { error: ZodError; input: Input }) => Output + ): ZodCatch<this>; + catch(def: any) { + const catchValueFunc = typeof def === "function" ? def : () => def; + + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, + }) as any; + } + + describe(description: string): this { + const This = (this as any).constructor; + return new This({ + ...this._def, + description, + }); + } + + pipe<T extends ZodTypeAny>(target: T): ZodPipeline<this, T> { + return ZodPipeline.create(this, target); + } + readonly(): ZodReadonly<this> { + return ZodReadonly.create(this); + } + + isOptional(): boolean { + return this.safeParse(undefined).success; + } + isNullable(): boolean { + return this.safeParse(null).success; + } +} diff --git a/src/types/bigint.ts b/src/types/bigint.ts new file mode 100644 index 000000000..b292bee99 --- /dev/null +++ b/src/types/bigint.ts @@ -0,0 +1,219 @@ +import { + addIssueToContext, + INVALID, + ParseContext, + ParseInput, + ParseReturnType, + ParseStatus, +} from "../external"; +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, util, ZodParsedType } from "./utils"; +import { errorUtil } from "./utils/errorUtil"; + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodBigInt ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// +export type ZodBigIntCheck = + | { kind: "min"; value: bigint; inclusive: boolean; message?: string } + | { kind: "max"; value: bigint; inclusive: boolean; message?: string } + | { kind: "multipleOf"; value: bigint; message?: string }; + +export interface ZodBigIntDef extends ZodTypeDef { + checks: ZodBigIntCheck[]; + typeName: ZodFirstPartyTypeKind.ZodBigInt; + coerce: boolean; +} + +export class ZodBigInt extends ZodType<bigint, ZodBigIntDef> { + _parse(input: ParseInput): ParseReturnType<bigint> { + if (this._def.coerce) { + input.data = BigInt(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + + let ctx: undefined | ParseContext = undefined; + const status = new ParseStatus(); + + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { status: status.value, value: input.data }; + } + + static create = ( + params?: RawCreateParams & { coerce?: boolean } + ): ZodBigInt => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); + }; + + gte(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + min = this.gte; + + gt(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + + lte(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + max = this.lte; + + lt(value: bigint, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + + protected setLimit( + kind: "min" | "max", + value: bigint, + inclusive: boolean, + message?: string + ) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + + _addCheck(check: ZodBigIntCheck) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + positive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + + negative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + + nonpositive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + + nonnegative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + + multipleOf(value: bigint, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + + get minValue() { + let min: bigint | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + return min; + } + + get maxValue() { + let max: bigint | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return max; + } +} diff --git a/src/types/boolean.ts b/src/types/boolean.ts new file mode 100644 index 000000000..80a895803 --- /dev/null +++ b/src/types/boolean.ts @@ -0,0 +1,45 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + OK, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodBooleanDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodBoolean; + coerce: boolean; +} + +export class ZodBoolean extends ZodType<boolean, ZodBooleanDef> { + _parse(input: ParseInput): ParseReturnType<boolean> { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + + static create = ( + params?: RawCreateParams & { coerce?: boolean } + ): ZodBoolean => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/branded.ts b/src/types/branded.ts new file mode 100644 index 000000000..be8d10236 --- /dev/null +++ b/src/types/branded.ts @@ -0,0 +1,33 @@ +import { ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { ParseInput, ParseReturnType } from "./utils/parseUtil"; + +export interface ZodBrandedDef<T extends ZodTypeAny> extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodBranded; +} + +export const BRAND: unique symbol = Symbol("zod_brand"); +export type BRAND<T extends string | number | symbol> = { + [BRAND]: { + [k in T]: true; + }; +}; + +export class ZodBranded< + T extends ZodTypeAny, + B extends string | number | symbol +> extends ZodType<T["_output"] & BRAND<B>, ZodBrandedDef<T>, T["_input"]> { + _parse(input: ParseInput): ParseReturnType<any> { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + + unwrap() { + return this._def.type; + } +} diff --git a/src/types/catch.ts b/src/types/catch.ts new file mode 100644 index 000000000..f25cc65f8 --- /dev/null +++ b/src/types/catch.ts @@ -0,0 +1,100 @@ +import { ZodError } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { processCreateParams } from "./utils"; +import { + isAsync, + ParseContext, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodCatch ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export interface ZodCatchDef<T extends ZodTypeAny = ZodTypeAny> + extends ZodTypeDef { + innerType: T; + catchValue: (ctx: { error: ZodError; input: unknown }) => T["_input"]; + typeName: ZodFirstPartyTypeKind.ZodCatch; +} + +export class ZodCatch<T extends ZodTypeAny> extends ZodType< + T["_output"], + ZodCatchDef<T>, + unknown // any input will pass validation // T["_input"] +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { ctx } = this._processInputParams(input); + + // newCtx is used to not collect issues from inner types in ctx + const newCtx: ParseContext = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: + result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } else { + return { + status: "valid", + value: + result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + + removeCatch() { + return this._def.innerType; + } + + static create = <T extends ZodTypeAny>( + type: T, + params: RawCreateParams & { + catch: T["_output"] | (() => T["_output"]); + } + ): ZodCatch<T> => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: + typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/custom.ts b/src/types/custom.ts new file mode 100644 index 000000000..df11c3e9c --- /dev/null +++ b/src/types/custom.ts @@ -0,0 +1,36 @@ +import { ZodAny } from "./any"; +import { CustomErrorParams, ZodType } from "./index"; + +export type CustomParams = CustomErrorParams & { fatal?: boolean }; + +export const custom = <T>( + check?: (data: unknown) => any, + params: string | CustomParams | ((input: any) => CustomParams) = {}, + /** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ + fatal?: boolean +): ZodType<T> => { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + if (!check(data)) { + const p = + typeof params === "function" + ? params(data) + : typeof params === "string" + ? { message: params } + : params; + const _fatal = p.fatal ?? fatal ?? true; + const p2 = typeof p === "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } + }); + return ZodAny.create(); +}; diff --git a/src/types/date.ts b/src/types/date.ts new file mode 100644 index 000000000..be53e2b5e --- /dev/null +++ b/src/types/date.ts @@ -0,0 +1,144 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, util, ZodParsedType } from "./utils"; +import { errorUtil } from "./utils/errorUtil"; +import { + addIssueToContext, + INVALID, + ParseContext, + ParseInput, + ParseReturnType, + ParseStatus, +} from "./utils/parseUtil"; + +export type ZodDateCheck = + | { kind: "min"; value: number; message?: string } + | { kind: "max"; value: number; message?: string }; +export interface ZodDateDef extends ZodTypeDef { + checks: ZodDateCheck[]; + coerce: boolean; + typeName: ZodFirstPartyTypeKind.ZodDate; +} + +export class ZodDate extends ZodType<Date, ZodDateDef> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + + if (isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + + const status = new ParseStatus(); + let ctx: undefined | ParseContext = undefined; + + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { + status: status.value, + value: new Date((input.data as Date).getTime()), + }; + } + + _addCheck(check: ZodDateCheck) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + min(minDate: Date, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + + max(maxDate: Date, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + + get minDate() { + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + + return min != null ? new Date(min) : null; + } + + get maxDate() { + let max: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + + return max != null ? new Date(max) : null; + } + + static create = ( + params?: RawCreateParams & { coerce?: boolean } + ): ZodDate => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/default.ts b/src/types/default.ts new file mode 100644 index 000000000..503610a1b --- /dev/null +++ b/src/types/default.ts @@ -0,0 +1,58 @@ +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { processCreateParams, util, ZodParsedType } from "./utils"; +import { ParseInput, ParseReturnType } from "./utils/parseUtil"; + +//////////////////////////////////////////// +//////////////////////////////////////////// +////////// ////////// +////////// ZodDefault ////////// +////////// ////////// +//////////////////////////////////////////// +//////////////////////////////////////////// + +export interface ZodDefaultDef<T extends ZodTypeAny = ZodTypeAny> + extends ZodTypeDef { + innerType: T; + defaultValue: () => util.noUndefined<T["_input"]>; + typeName: ZodFirstPartyTypeKind.ZodDefault; +} + +export class ZodDefault<T extends ZodTypeAny> extends ZodType< + util.noUndefined<T["_output"]>, + ZodDefaultDef<T>, + T["_input"] | undefined +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + + removeDefault() { + return this._def.innerType; + } + + static create = <T extends ZodTypeAny>( + type: T, + params: RawCreateParams & { + default: T["_input"] | (() => util.noUndefined<T["_input"]>); + } + ): ZodDefault<T> => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: + typeof params.default === "function" + ? params.default + : () => params.default as any, + ...processCreateParams(params), + }) as any; + }; +} diff --git a/src/types/discriminatedUnion.ts b/src/types/discriminatedUnion.ts new file mode 100644 index 000000000..e84771ff7 --- /dev/null +++ b/src/types/discriminatedUnion.ts @@ -0,0 +1,209 @@ +import { ZodBranded } from "./branded"; +import { ZodCatch } from "./catch"; +import { ZodDefault } from "./default"; +import { ZodEnum } from "./enum"; +import { ZodIssueCode } from "./error"; +import { + input, + output, + RawCreateParams, + ZodFirstPartyTypeKind, ZodRawShape, + ZodType, + ZodTypeAny, + ZodTypeDef } from "./index"; +import { ZodLazy } from "./lazy"; +import { ZodLiteral } from "./literal"; +import { ZodNativeEnum } from "./nativeEnum"; +import { ZodNull } from "./null"; +import { ZodNullable } from "./nullable"; +import { UnknownKeysParam, ZodObject } from "./object"; +import { ZodOptional } from "./optional"; +import { ZodReadonly } from "./readonly"; +import { ZodEffects } from "./transformer"; +import { ZodUndefined } from "./undefined"; +import { processCreateParams, util, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; +import { Primitive } from "./utils/typeAliases"; + +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +const getDiscriminator = <T extends ZodTypeAny>(type: T): Primitive[] => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return util.objectValues(type.enum as any); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [undefined]; + } else if (type instanceof ZodNull) { + return [null]; + } else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } +}; + +export type ZodDiscriminatedUnionOption<Discriminator extends string> = + ZodObject< + { + [key in Discriminator]: ZodTypeAny; + } & ZodRawShape, + UnknownKeysParam, + ZodTypeAny + >; + +export interface ZodDiscriminatedUnionDef< + Discriminator extends string, + Options extends ZodDiscriminatedUnionOption<string>[] = ZodDiscriminatedUnionOption<string>[] +> extends ZodTypeDef { + discriminator: Discriminator; + options: Options; + optionsMap: Map<Primitive, ZodDiscriminatedUnionOption<any>>; + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion; +} + +export class ZodDiscriminatedUnion< + Discriminator extends string, + Options extends ZodDiscriminatedUnionOption<Discriminator>[] +> extends ZodType< + output<Options[number]>, + ZodDiscriminatedUnionDef<Discriminator, Options>, + input<Options[number]> +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { ctx } = this._processInputParams(input); + + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + + const discriminator = this.discriminator; + + const discriminatorValue: string = ctx.data[discriminator]; + + const option = this.optionsMap.get(discriminatorValue); + + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }) as any; + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }) as any; + } + } + + get discriminator() { + return this._def.discriminator; + } + + get options() { + return this._def.options; + } + + get optionsMap() { + return this._def.optionsMap; + } + + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create< + Discriminator extends string, + Types extends [ + ZodDiscriminatedUnionOption<Discriminator>, + ...ZodDiscriminatedUnionOption<Discriminator>[] + ] + >( + discriminator: Discriminator, + options: Types, + params?: RawCreateParams + ): ZodDiscriminatedUnion<Discriminator, Types> { + // Get all the valid discriminator values + const optionsMap: Map<Primitive, Types[number]> = new Map(); + + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error( + `A discriminator value for key \`${discriminator}\` could not be extracted from all schema options` + ); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error( + `Discriminator property ${String( + discriminator + )} has duplicate value ${String(value)}` + ); + } + + optionsMap.set(value, type); + } + } + + return new ZodDiscriminatedUnion< + Discriminator, + // DiscriminatorValue, + Types + >({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } +} diff --git a/src/types/enum.ts b/src/types/enum.ts new file mode 100644 index 000000000..29537711b --- /dev/null +++ b/src/types/enum.ts @@ -0,0 +1,155 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, util } from "./utils"; +import { + addIssueToContext, + INVALID, + OK, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodEnum ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// + +export type ArrayKeys = keyof any[]; +export type Indices<T> = Exclude<keyof T, ArrayKeys>; + +export type EnumValues = [string, ...string[]]; + +export type Values<T extends EnumValues> = { + [k in T[number]]: k; +}; + +export interface ZodEnumDef<T extends EnumValues = EnumValues> + extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodEnum; +} + +export type Writeable<T> = { + -readonly [P in keyof T]: T[P]; +}; + +export type FilterEnum<Values, ToExclude> = Values extends [] + ? [] + : Values extends [infer Head, ...infer Rest] + ? Head extends ToExclude + ? FilterEnum<Rest, ToExclude> + : [Head, ...FilterEnum<Rest, ToExclude>] + : never; + +export type typecast<A, T> = A extends T ? A : never; + +export function createZodEnum< + U extends string, + T extends Readonly<[U, ...U[]]> +>(values: T, params?: RawCreateParams): ZodEnum<Writeable<T>>; +export function createZodEnum<U extends string, T extends [U, ...U[]]>( + values: T, + params?: RawCreateParams +): ZodEnum<T>; +export function createZodEnum( + values: [string, ...string[]], + params?: RawCreateParams +) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} + +export class ZodEnum<T extends [string, ...string[]]> extends ZodType< + T[number], + ZodEnumDef<T> +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues) as "string", + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + + if (this._def.values.indexOf(input.data) === -1) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + + get options() { + return this._def.values; + } + + get enum(): Values<T> { + const enumValues: any = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues as any; + } + + get Values(): Values<T> { + const enumValues: any = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues as any; + } + + get Enum(): Values<T> { + const enumValues: any = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues as any; + } + + extract<ToExtract extends readonly [T[number], ...T[number][]]>( + values: ToExtract, + newDef: RawCreateParams = this._def + ): ZodEnum<Writeable<ToExtract>> { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }) as any; + } + + exclude<ToExclude extends readonly [T[number], ...T[number][]]>( + values: ToExclude, + newDef: RawCreateParams = this._def + ): ZodEnum< + typecast<Writeable<FilterEnum<T, ToExclude[number]>>, [string, ...string[]]> + > { + return ZodEnum.create( + this.options.filter((opt) => !values.includes(opt)) as FilterEnum< + T, + ToExclude[number] + >, + { + ...this._def, + ...newDef, + } + ) as any; + } + + static create = createZodEnum; +} diff --git a/src/ZodError.ts b/src/types/error/index.ts similarity index 96% rename from src/ZodError.ts rename to src/types/error/index.ts index 6a4dc9de6..faa3c61e3 100644 --- a/src/ZodError.ts +++ b/src/types/error/index.ts @@ -1,6 +1,12 @@ -import type { TypeOf, ZodFirstPartyTypeKind, ZodType } from "."; -import { Primitive } from "./helpers/typeAliases"; -import { util, ZodParsedType } from "./helpers/util"; +import { + defaultErrorMap, + Primitive, + TypeOf, + util, + ZodFirstPartyTypeKind, + ZodParsedType, + ZodType, +} from "../index"; type allKeys<T> = T extends any ? keyof T : never; @@ -364,3 +370,13 @@ export class ZodTemplateLiteralUnsupportedCheckError extends Error { this.name = "ZodTemplateLiteralUnsupportedCheckError"; } } +let overrideErrorMap = defaultErrorMap; +export { defaultErrorMap }; + +export function setErrorMap(map: ZodErrorMap) { + overrideErrorMap = map; +} + +export function getErrorMap() { + return overrideErrorMap; +} diff --git a/src/locales/en.ts b/src/types/error/locales/en.ts similarity index 97% rename from src/locales/en.ts rename to src/types/error/locales/en.ts index 11325a95b..c7964c58b 100644 --- a/src/locales/en.ts +++ b/src/types/error/locales/en.ts @@ -1,5 +1,9 @@ -import { util, ZodParsedType } from "../helpers/util"; -import { ZodErrorMap, ZodIssueCode } from "../ZodError"; +import { + type ZodErrorMap, + util, + ZodIssueCode, + ZodParsedType, +} from "../../index"; const errorMap: ZodErrorMap = (issue, _ctx) => { let message: string; diff --git a/src/types/function.ts b/src/types/function.ts new file mode 100644 index 000000000..f64efafef --- /dev/null +++ b/src/types/function.ts @@ -0,0 +1,216 @@ +import { + defaultErrorMap, + getErrorMap, + ZodError, + ZodErrorMap, + ZodIssue, + ZodIssueCode, +} from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { ZodPromise } from "./promise"; +import { AnyZodTuple, ZodTuple } from "./tuple"; +import { ZodUnknown } from "./unknown"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + makeIssue, + OK, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodFunctionDef< + Args extends ZodTuple<any, any> = ZodTuple<any, any>, + Returns extends ZodTypeAny = ZodTypeAny +> extends ZodTypeDef { + args: Args; + returns: Returns; + typeName: ZodFirstPartyTypeKind.ZodFunction; +} + +export type OuterTypeOfFunction< + Args extends ZodTuple<any, any>, + Returns extends ZodTypeAny +> = Args["_input"] extends Array<any> + ? (...args: Args["_input"]) => Returns["_output"] + : never; + +export type InnerTypeOfFunction< + Args extends ZodTuple<any, any>, + Returns extends ZodTypeAny +> = Args["_output"] extends Array<any> + ? (...args: Args["_output"]) => Returns["_input"] + : never; + +export class ZodFunction< + Args extends ZodTuple<any, any>, + Returns extends ZodTypeAny +> extends ZodType< + OuterTypeOfFunction<Args, Returns>, + ZodFunctionDef<Args, Returns>, + InnerTypeOfFunction<Args, Returns> +> { + _parse(input: ParseInput): ParseReturnType<any> { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + + function makeArgsIssue(args: any, error: ZodError): ZodIssue { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + defaultErrorMap, + ].filter((x) => !!x) as ZodErrorMap[], + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + + function makeReturnsIssue(returns: any, error: ZodError): ZodIssue { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + getErrorMap(), + defaultErrorMap, + ].filter((x) => !!x) as ZodErrorMap[], + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (this: any, ...args: any[]) { + const error = new ZodError([]); + const parsedArgs = await me._def.args + .parseAsync(args, params) + .catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs as any); + const parsedReturns = await ( + me._def.returns as unknown as ZodPromise<ZodTypeAny> + )._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (this: any, ...args: any[]) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }) as any; + } + } + + parameters() { + return this._def.args; + } + + returnType() { + return this._def.returns; + } + + args<Items extends Parameters<(typeof ZodTuple)["create"]>[0]>( + ...items: Items + ): ZodFunction<ZodTuple<Items, ZodUnknown>, Returns> { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) as any, + }); + } + + returns<NewReturnType extends ZodType<any, any>>( + returnType: NewReturnType + ): ZodFunction<Args, NewReturnType> { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + + implement<F extends InnerTypeOfFunction<Args, Returns>>( + func: F + ): ReturnType<F> extends Returns["_output"] + ? (...args: Args["_input"]) => ReturnType<F> + : OuterTypeOfFunction<Args, Returns> { + const validatedFunc = this.parse(func); + return validatedFunc as any; + } + + strictImplement( + func: InnerTypeOfFunction<Args, Returns> + ): InnerTypeOfFunction<Args, Returns> { + const validatedFunc = this.parse(func); + return validatedFunc as any; + } + + validate = this.implement; + + static create(): ZodFunction<ZodTuple<[], ZodUnknown>, ZodUnknown>; + static create<T extends AnyZodTuple = ZodTuple<[], ZodUnknown>>( + args: T + ): ZodFunction<T, ZodUnknown>; + static create<T extends AnyZodTuple, U extends ZodTypeAny>( + args: T, + returns: U + ): ZodFunction<T, U>; + static create< + T extends AnyZodTuple = ZodTuple<[], ZodUnknown>, + U extends ZodTypeAny = ZodUnknown + >(args: T, returns: U, params?: RawCreateParams): ZodFunction<T, U>; + static create( + args?: AnyZodTuple, + returns?: ZodTypeAny, + params?: RawCreateParams + ) { + return new ZodFunction({ + args: (args + ? args + : ZodTuple.create([]).rest(ZodUnknown.create())) as any, + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }) as any; + } +} diff --git a/src/types/helpers/partialUtil.ts b/src/types/helpers/partialUtil.ts new file mode 100644 index 000000000..3789664a4 --- /dev/null +++ b/src/types/helpers/partialUtil.ts @@ -0,0 +1,33 @@ +import { ZodArray } from "../array"; +import { ZodRawShape, ZodTypeAny } from "../index"; +import { ZodNullable } from "../nullable"; +import { ZodObject } from "../object"; +import { ZodOptional } from "../optional"; +import { ZodTuple, ZodTupleItems } from "../tuple"; + +export namespace partialUtil { + export type DeepPartial<T extends ZodTypeAny> = + T extends ZodObject<ZodRawShape> + ? ZodObject< + { [k in keyof T["shape"]]: ZodOptional<DeepPartial<T["shape"][k]>> }, + T["_def"]["unknownKeys"], + T["_def"]["catchall"] + > + : T extends ZodArray<infer Type, infer Card> + ? ZodArray<DeepPartial<Type>, Card> + : T extends ZodOptional<infer Type> + ? ZodOptional<DeepPartial<Type>> + : T extends ZodNullable<infer Type> + ? ZodNullable<DeepPartial<Type>> + : T extends ZodTuple<infer Items> + ? { + [k in keyof Items]: Items[k] extends ZodTypeAny + ? DeepPartial<Items[k]> + : never; + } extends infer PI + ? PI extends ZodTupleItems + ? ZodTuple<PI> + : never + : never + : T; +} diff --git a/src/types/index.ts b/src/types/index.ts new file mode 100644 index 000000000..e2a3bbf46 --- /dev/null +++ b/src/types/index.ts @@ -0,0 +1,56 @@ +/* eslint-disable simple-import-sort/exports */ +/** + * Internal pattern to get rid of circular dependencies + * @see https://medium.com/p/a04c987cf0de + */ +import defaultErrorMap from "./error/locales/en"; +export * from "./utils"; +export * from "./utils/enumUtil"; +export * from "./utils/errorUtil"; +export * from "./utils/parseUtil"; +export * from "./utils/partialUtil"; +export * from "./utils/typeAliases"; +export * from "./basetype"; +export * from "../defs"; +export * from "./any"; +export * from "./array"; +export * from "./bigint"; +export * from "./boolean"; +export * from "./branded"; +export * from "./catch"; +export * from "./custom"; +export * from "./date"; +export * from "./default"; +export * from "./discriminatedUnion"; +export * from "./enum"; +export * from "./error"; +export * from "./error"; +export { defaultErrorMap }; +export * from "./function"; +export * from "./index"; +export * from "./intersection"; +export * from "./lazy"; +export * from "./literal"; +export * from "./map"; +export * from "./nan"; +export * from "./nativeEnum"; +export * from "./never"; +export * from "./null"; +export * from "./nullable"; +export * from "./number"; +export * from "./object"; +export * from "./optional"; +export * from "./pipeline"; +export * from "./promise"; +export * from "./readonly"; +export * from "./record"; +export * from "./set"; +export * from "./string"; +export * from "./symbol"; +export * from "./templateLiteral"; +export * from "./transformer"; +export * from "./tuple"; +export * from "./undefined"; +export * from "./union"; +export * from "./unknown"; +export * from "./void"; diff --git a/src/types/intersection.ts b/src/types/intersection.ts new file mode 100644 index 000000000..696e7005d --- /dev/null +++ b/src/types/intersection.ts @@ -0,0 +1,158 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { + getParsedType, + processCreateParams, + util, + ZodParsedType, +} from "./utils"; +import { + addIssueToContext, + INVALID, + isAborted, + isDirty, + ParseInput, + ParseReturnType, + SyncParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodIntersectionDef< + T extends ZodTypeAny = ZodTypeAny, + U extends ZodTypeAny = ZodTypeAny +> extends ZodTypeDef { + left: T; + right: U; + typeName: ZodFirstPartyTypeKind.ZodIntersection; +} + +function mergeValues( + a: any, + b: any +): { valid: true; data: any } | { valid: false } { + const aType = getParsedType(a); + const bType = getParsedType(b); + + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util + .objectKeys(a) + .filter((key) => bKeys.indexOf(key) !== -1); + + const newObj: any = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + + const newArray: unknown[] = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + + if (!sharedValue.valid) { + return { valid: false }; + } + + newArray.push(sharedValue.data); + } + + return { valid: true, data: newArray }; + } else if ( + aType === ZodParsedType.date && + bType === ZodParsedType.date && + +a === +b + ) { + return { valid: true, data: a }; + } else { + return { valid: false }; + } +} + +export class ZodIntersection< + T extends ZodTypeAny, + U extends ZodTypeAny +> extends ZodType< + T["_output"] & U["_output"], + ZodIntersectionDef<T, U>, + T["_input"] & U["_input"] +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { status, ctx } = this._processInputParams(input); + const handleParsed = ( + parsedLeft: SyncParseReturnType, + parsedRight: SyncParseReturnType + ): SyncParseReturnType<T & U> => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + + const merged = mergeValues(parsedLeft.value, parsedRight.value); + + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + + return { status: status.value, value: merged.data as any }; + }; + + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]: any) => handleParsed(left, right)); + } else { + return handleParsed( + this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }) + ); + } + } + + static create = <T extends ZodTypeAny, U extends ZodTypeAny>( + left: T, + right: U, + params?: RawCreateParams + ): ZodIntersection<T, U> => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/lazy.ts b/src/types/lazy.ts new file mode 100644 index 000000000..abe7d7371 --- /dev/null +++ b/src/types/lazy.ts @@ -0,0 +1,50 @@ +import { + input, + output, + RawCreateParams, + ZodFirstPartyTypeKind, ZodType, + ZodTypeAny, + ZodTypeDef } from "./index"; +import { processCreateParams } from "./utils"; +import { ParseInput, ParseReturnType } from "./utils/parseUtil"; + +/////////////////////////////////////// +/////////////////////////////////////// +////////// ////////// +////////// ZodLazy ////////// +////////// ////////// +/////////////////////////////////////// +/////////////////////////////////////// + +export interface ZodLazyDef<T extends ZodTypeAny = ZodTypeAny> + extends ZodTypeDef { + getter: () => T; + typeName: ZodFirstPartyTypeKind.ZodLazy; +} + +export class ZodLazy<T extends ZodTypeAny> extends ZodType< + output<T>, + ZodLazyDef<T>, + input<T> +> { + get schema(): T { + return this._def.getter(); + } + + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + + static create = <T extends ZodTypeAny>( + getter: () => T, + params?: RawCreateParams + ): ZodLazy<T> => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/literal.ts b/src/types/literal.ts new file mode 100644 index 000000000..79328d1df --- /dev/null +++ b/src/types/literal.ts @@ -0,0 +1,45 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams } from "./utils"; +import { + addIssueToContext, + INVALID, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; +import { Primitive } from "./utils/typeAliases"; + +export interface ZodLiteralDef<T = any> extends ZodTypeDef { + value: T; + typeName: ZodFirstPartyTypeKind.ZodLiteral; +} + +export class ZodLiteral<T> extends ZodType<T, ZodLiteralDef<T>> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + + get value() { + return this._def.value; + } + + static create = <T extends Primitive>( + value: T, + params?: RawCreateParams + ): ZodLiteral<T> => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/map.ts b/src/types/map.ts new file mode 100644 index 000000000..ea11690ca --- /dev/null +++ b/src/types/map.ts @@ -0,0 +1,116 @@ +import { ZodIssueCode } from "./error"; +import { + ParseInputLazyPath, + RawCreateParams, + ZodFirstPartyTypeKind, ZodType, + ZodTypeAny, + ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + ParseInput, + ParseReturnType, + SyncParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodMapDef< + Key extends ZodTypeAny = ZodTypeAny, + Value extends ZodTypeAny = ZodTypeAny +> extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodMap; +} + +export class ZodMap< + Key extends ZodTypeAny = ZodTypeAny, + Value extends ZodTypeAny = ZodTypeAny +> extends ZodType< + Map<Key["_output"], Value["_output"]>, + ZodMapDef<Key, Value>, + Map<Key["_input"], Value["_input"]> +> { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + + const keyType = this._def.keyType; + const valueType = this._def.valueType; + + const pairs = [...(ctx.data as Map<unknown, unknown>).entries()].map( + ([key, value], index) => { + return { + key: keyType._parse( + new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"]) + ), + value: valueType._parse( + new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]) + ), + }; + } + ); + + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key as SyncParseReturnType; + const value = pair.value as SyncParseReturnType; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + static create = < + Key extends ZodTypeAny = ZodTypeAny, + Value extends ZodTypeAny = ZodTypeAny + >( + keyType: Key, + valueType: Value, + params?: RawCreateParams + ): ZodMap<Key, Value> => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/nan.ts b/src/types/nan.ts new file mode 100644 index 000000000..911896d48 --- /dev/null +++ b/src/types/nan.ts @@ -0,0 +1,45 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +///////////////////////////////////////// +///////////////////////////////////////// +////////// ////////// +////////// ZodNaN ////////// +////////// ////////// +///////////////////////////////////////// +///////////////////////////////////////// + +export interface ZodNaNDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNaN; +} + +export class ZodNaN extends ZodType<number, ZodNaNDef> { + _parse(input: ParseInput): ParseReturnType<any> { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; + } + + return { status: "valid", value: input.data }; + } + + static create = (params?: RawCreateParams): ZodNaN => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/nativeEnum.ts b/src/types/nativeEnum.ts new file mode 100644 index 000000000..a2bf8eacd --- /dev/null +++ b/src/types/nativeEnum.ts @@ -0,0 +1,73 @@ +import { ZodIssueCode } from "./error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "./index"; +import { processCreateParams, util, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + OK, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodNativeEnumDef<T extends EnumLike = EnumLike> + extends ZodTypeDef { + values: T; + typeName: ZodFirstPartyTypeKind.ZodNativeEnum; +} + +export type EnumLike = { [k: string]: string | number; [nu: number]: string }; + +export class ZodNativeEnum<T extends EnumLike> extends ZodType< + T[keyof T], + ZodNativeEnumDef<T> +> { + _parse(input: ParseInput): ParseReturnType<T[keyof T]> { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + + const ctx = this._getOrReturnCtx(input); + if ( + ctx.parsedType !== ZodParsedType.string && + ctx.parsedType !== ZodParsedType.number + ) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues) as "string", + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + + if (nativeEnumValues.indexOf(input.data) === -1) { + const expectedValues = util.objectValues(nativeEnumValues); + + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data as any); + } + + get enum() { + return this._def.values; + } + + static create = <T extends EnumLike>( + values: T, + params?: RawCreateParams + ): ZodNativeEnum<T> => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/never.ts b/src/types/never.ts new file mode 100644 index 000000000..ebc582e5d --- /dev/null +++ b/src/types/never.ts @@ -0,0 +1,31 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodNeverDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNever; +} + +export class ZodNever extends ZodType<never, ZodNeverDef> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } + static create = (params?: RawCreateParams): ZodNever => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/null.ts b/src/types/null.ts new file mode 100644 index 000000000..2617b721d --- /dev/null +++ b/src/types/null.ts @@ -0,0 +1,36 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + OK, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodNullDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodNull; +} + +export class ZodNull extends ZodType<null, ZodNullDef> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + static create = (params?: RawCreateParams): ZodNull => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/nullable.ts b/src/types/nullable.ts new file mode 100644 index 000000000..0264b2617 --- /dev/null +++ b/src/types/nullable.ts @@ -0,0 +1,48 @@ +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { OK, ParseInput, ParseReturnType } from "./utils/parseUtil"; + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodNullable ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// + +export interface ZodNullableDef<T extends ZodTypeAny = ZodTypeAny> + extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodNullable; +} + +export type ZodNullableType<T extends ZodTypeAny> = ZodNullable<T>; + +export class ZodNullable<T extends ZodTypeAny> extends ZodType< + T["_output"] | null, + ZodNullableDef<T>, + T["_input"] | null +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + + unwrap() { + return this._def.innerType; + } + + static create = <T extends ZodTypeAny>( + type: T, + params?: RawCreateParams + ): ZodNullable<T> => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }) as any; + }; +} diff --git a/src/types/number.ts b/src/types/number.ts new file mode 100644 index 000000000..4a75eb169 --- /dev/null +++ b/src/types/number.ts @@ -0,0 +1,301 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, util, ZodParsedType } from "./utils"; +import { errorUtil } from "./utils/errorUtil"; +import { + addIssueToContext, + INVALID, + ParseContext, + ParseInput, + ParseReturnType, + ParseStatus, +} from "./utils/parseUtil"; + +export type ZodNumberCheck = + | { kind: "min"; value: number; inclusive: boolean; message?: string } + | { kind: "max"; value: number; inclusive: boolean; message?: string } + | { kind: "int"; message?: string } + | { kind: "multipleOf"; value: number; message?: string } + | { kind: "finite"; message?: string }; +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function floatSafeRemainder(val: number, step: number) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / Math.pow(10, decCount); +} + +export interface ZodNumberDef extends ZodTypeDef { + checks: ZodNumberCheck[]; + typeName: ZodFirstPartyTypeKind.ZodNumber; + coerce: boolean; +} + +export class ZodNumber extends ZodType<number, ZodNumberDef> { + _parse(input: ParseInput): ParseReturnType<number> { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + + let ctx: undefined | ParseContext = undefined; + const status = new ParseStatus(); + + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { status: status.value, value: input.data }; + } + + static create = ( + params?: RawCreateParams & { coerce?: boolean } + ): ZodNumber => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); + }; + + gte(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + min = this.gte; + + gt(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + + lte(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + max = this.lte; + + lt(value: number, message?: errorUtil.ErrMessage) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + + protected setLimit( + kind: "min" | "max", + value: number, + inclusive: boolean, + message?: string + ) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + + _addCheck(check: ZodNumberCheck) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + int(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + + positive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + + negative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + + nonpositive(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + + nonnegative(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + + multipleOf(value: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + step = this.multipleOf; + + finite(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + + safe(message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + + get minValue() { + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + return min; + } + + get maxValue() { + let max: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return max; + } + + get isInt() { + return !!this._def.checks.find( + (ch) => + ch.kind === "int" || + (ch.kind === "multipleOf" && util.isInteger(ch.value)) + ); + } + + get isFinite() { + let max: number | null = null, + min: number | null = null; + for (const ch of this._def.checks) { + if ( + ch.kind === "finite" || + ch.kind === "int" || + ch.kind === "multipleOf" + ) { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +} diff --git a/src/types/object.ts b/src/types/object.ts new file mode 100644 index 000000000..62c327ad4 --- /dev/null +++ b/src/types/object.ts @@ -0,0 +1,645 @@ +import { + addIssueToContext, + INVALID, + objectUtil, + ParseInput, + ParseReturnType, + ParseStatus, + util, + ZodIssueCode, + ZodParsedType, +} from "../external"; +import { ZodArray } from "./array"; +import { createZodEnum, ZodEnum } from "./enum"; +import { + ParseInputLazyPath, + RawCreateParams, + ZodFirstPartyTypeKind, ZodRawShape, + ZodType, + ZodTypeAny, + ZodTypeDef } from "./index"; +import { ZodNever } from "./never"; +import { ZodNullable } from "./nullable"; +import { ZodOptional } from "./optional"; +import { ZodTuple } from "./tuple"; +import { processCreateParams } from "./utils"; +import { enumUtil } from "./utils/enumUtil"; +import { errorUtil } from "./utils/errorUtil"; +import { partialUtil } from "./utils/partialUtil"; + +export type UnknownKeysParam = "passthrough" | "strict" | "strip"; + +export interface ZodObjectDef< + T extends ZodRawShape = ZodRawShape, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam, + Catchall extends ZodTypeAny = ZodTypeAny +> extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodObject; + shape: () => T; + catchall: Catchall; + unknownKeys: UnknownKeys; +} + +export type mergeTypes<A, B> = { + [k in keyof A | keyof B]: k extends keyof B + ? B[k] + : k extends keyof A + ? A[k] + : never; +}; + +export type objectOutputType< + Shape extends ZodRawShape, + Catchall extends ZodTypeAny, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam +> = objectUtil.flatten< + objectUtil.addQuestionMarks<baseObjectOutputType<Shape>> +> & + CatchallOutput<Catchall> & + PassthroughType<UnknownKeys>; + +export type baseObjectOutputType<Shape extends ZodRawShape> = { + [k in keyof Shape]: Shape[k]["_output"]; +}; + +export type objectInputType< + Shape extends ZodRawShape, + Catchall extends ZodTypeAny, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam +> = objectUtil.flatten<baseObjectInputType<Shape>> & + CatchallInput<Catchall> & + PassthroughType<UnknownKeys>; +export type baseObjectInputType<Shape extends ZodRawShape> = + objectUtil.addQuestionMarks<{ + [k in keyof Shape]: Shape[k]["_input"]; + }>; + +export type CatchallOutput<T extends ZodType> = ZodType extends T + ? unknown + : { [k: string]: T["_output"] }; + +export type CatchallInput<T extends ZodType> = ZodType extends T + ? unknown + : { [k: string]: T["_input"] }; + +export type PassthroughType<T extends UnknownKeysParam> = + T extends "passthrough" ? { [k: string]: unknown } : unknown; + +export type deoptional<T extends ZodTypeAny> = T extends ZodOptional<infer U> + ? deoptional<U> + : T extends ZodNullable<infer U> + ? ZodNullable<deoptional<U>> + : T; + +export type SomeZodObject = ZodObject< + ZodRawShape, + UnknownKeysParam, + ZodTypeAny +>; + +export type noUnrecognized<Obj extends object, Shape extends object> = { + [k in keyof Obj]: k extends keyof Shape ? Obj[k] : never; +}; +function deepPartialify(schema: ZodTypeAny): any { + if (schema instanceof ZodObject) { + const newShape: any = {}; + + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }) as any; + } else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple) { + return ZodTuple.create( + schema.items.map((item: any) => deepPartialify(item)) + ); + } else { + return schema; + } +} + +export class ZodObject< + T extends ZodRawShape, + UnknownKeys extends UnknownKeysParam = UnknownKeysParam, + Catchall extends ZodTypeAny = ZodTypeAny, + Output = objectOutputType<T, Catchall, UnknownKeys>, + Input = objectInputType<T, Catchall, UnknownKeys> +> extends ZodType<Output, ZodObjectDef<T, UnknownKeys, Catchall>, Input> { + private _cached: { shape: T; keys: string[] } | null = null; + + _getCached(): { shape: T; keys: string[] } { + if (this._cached !== null) return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + return (this._cached = { shape, keys }); + } + + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + + const { status, ctx } = this._processInputParams(input); + + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys: string[] = []; + + if ( + !( + this._def.catchall instanceof ZodNever && + this._def.unknownKeys === "strip" + ) + ) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + + const pairs: { + key: ParseReturnType<any>; + value: ParseReturnType<any>; + alwaysSet?: boolean; + }[] = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + ), + alwaysSet: key in ctx.data, + }); + } + + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + // run catchall validation + const catchall = this._def.catchall; + + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs: any[] = []; + for (const pair of pairs) { + const key = await pair.key; + syncPairs.push({ + key, + value: await pair.value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs as any); + } + } + + get shape() { + return this._def.shape(); + } + + strict(message?: errorUtil.ErrMessage): ZodObject<T, "strict", Catchall> { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + const defaultError = + this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }) as any; + } + + strip(): ZodObject<T, "strip", Catchall> { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }) as any; + } + + passthrough(): ZodObject<T, "passthrough", Catchall> { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }) as any; + } + + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + nonstrict = this.passthrough; + + // const AugmentFactory = + // <Def extends ZodObjectDef>(def: Def) => + // <Augmentation extends ZodRawShape>( + // augmentation: Augmentation + // ): ZodObject< + // extendShape<ReturnType<Def["shape"]>, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend<Augmentation extends ZodRawShape>( + augmentation: Augmentation + ): ZodObject<objectUtil.extendShape<T, Augmentation>, UnknownKeys, Catchall> { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }) as any; + } + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape<T, Augmentation>, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + augment = this.extend; + + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge<Incoming extends AnyZodObject, Augmentation extends Incoming["shape"]>( + merging: Incoming + ): ZodObject< + objectUtil.extendShape<T, Augmentation>, + Incoming["_def"]["unknownKeys"], + Incoming["_def"]["catchall"] + > { + const merged: any = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }) as any; + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey<Key extends string, Schema extends ZodTypeAny>( + key: Key, + schema: Schema + ): ZodObject< + T & { + [k in Key]: Schema; + }, + UnknownKeys, + Catchall + > { + return this.augment({ [key]: schema }) as any; + } + // merge<Incoming extends AnyZodObject>( + // merging: Incoming + // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => { + // ZodObject< + // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall<Index extends ZodTypeAny>( + index: Index + ): ZodObject<T, UnknownKeys, Index> { + return new ZodObject({ + ...this._def, + catchall: index, + }) as any; + } + + pick< + Mask extends { + [k in keyof T]?: true; + } + >( + mask: Mask + ): ZodObject<Pick<T, Extract<keyof T, keyof Mask>>, UnknownKeys, Catchall> { + const shape: any = {}; + + util.objectKeys(mask).forEach((key) => { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + }); + + return new ZodObject({ + ...this._def, + shape: () => shape, + }) as any; + } + + omit< + Mask extends { + [k in keyof T]?: true; + } + >(mask: Mask): ZodObject<Omit<T, keyof Mask>, UnknownKeys, Catchall> { + const shape: any = {}; + + util.objectKeys(this.shape).forEach((key) => { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + }); + + return new ZodObject({ + ...this._def, + shape: () => shape, + }) as any; + } + + /** + * @deprecated + */ + deepPartial(): partialUtil.DeepPartial<this> { + return deepPartialify(this) as any; + } + + partial(): ZodObject< + { + [k in keyof T]: ZodOptional<T[k]>; + }, + UnknownKeys, + Catchall + >; + partial< + Mask extends { + [k in keyof T]?: true; + } + >( + mask: Mask + ): ZodObject< + objectUtil.noNever<{ + [k in keyof T]: k extends keyof Mask ? ZodOptional<T[k]> : T[k]; + }>, + UnknownKeys, + Catchall + >; + partial(mask?: any) { + const newShape: any = {}; + + util.objectKeys(this.shape).forEach((key) => { + const fieldSchema = this.shape[key]; + + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + }); + + return new ZodObject({ + ...this._def, + shape: () => newShape, + }) as any; + } + + required(): ZodObject< + { + [k in keyof T]: deoptional<T[k]>; + }, + UnknownKeys, + Catchall + >; + required< + Mask extends { + [k in keyof T]?: true; + } + >( + mask: Mask + ): ZodObject< + objectUtil.noNever<{ + [k in keyof T]: k extends keyof Mask ? deoptional<T[k]> : T[k]; + }>, + UnknownKeys, + Catchall + >; + required(mask?: any) { + const newShape: any = {}; + + util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + + while (newField instanceof ZodOptional) { + newField = (newField as ZodOptional<any>)._def.innerType; + } + + newShape[key] = newField; + } + }); + + return new ZodObject({ + ...this._def, + shape: () => newShape, + }) as any; + } + + keyof(): ZodEnum<enumUtil.UnionToTupleString<keyof T>> { + return createZodEnum( + util.objectKeys(this.shape) as [string, ...string[]] + ) as any; + } + + static create = <T extends ZodRawShape>( + shape: T, + params?: RawCreateParams + ): ZodObject<T, "strip"> => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }) as any; + }; + + static strictCreate = <T extends ZodRawShape>( + shape: T, + params?: RawCreateParams + ): ZodObject<T, "strict"> => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }) as any; + }; + + static lazycreate = <T extends ZodRawShape>( + shape: () => T, + params?: RawCreateParams + ): ZodObject<T, "strip"> => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }) as any; + }; +} + +export type AnyZodObject = ZodObject<any, any, any>; diff --git a/src/types/optional.ts b/src/types/optional.ts new file mode 100644 index 000000000..32215e9b4 --- /dev/null +++ b/src/types/optional.ts @@ -0,0 +1,48 @@ +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { OK, ParseInput, ParseReturnType } from "./utils/parseUtil"; + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodOptional ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// + +export interface ZodOptionalDef<T extends ZodTypeAny = ZodTypeAny> + extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodOptional; +} + +export type ZodOptionalType<T extends ZodTypeAny> = ZodOptional<T>; + +export class ZodOptional<T extends ZodTypeAny> extends ZodType< + T["_output"] | undefined, + ZodOptionalDef<T>, + T["_input"] | undefined +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + + unwrap() { + return this._def.innerType; + } + + static create = <T extends ZodTypeAny>( + type: T, + params?: RawCreateParams + ): ZodOptional<T> => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }) as any; + }; +} diff --git a/src/types/pipeline.ts b/src/types/pipeline.ts new file mode 100644 index 000000000..e49a348dc --- /dev/null +++ b/src/types/pipeline.ts @@ -0,0 +1,70 @@ +import { ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { DIRTY, INVALID, ParseInput, ParseReturnType } from "./utils/parseUtil"; + +export interface ZodPipelineDef<A extends ZodTypeAny, B extends ZodTypeAny> + extends ZodTypeDef { + in: A; + out: B; + typeName: ZodFirstPartyTypeKind.ZodPipeline; +} + +export class ZodPipeline< + A extends ZodTypeAny, + B extends ZodTypeAny +> extends ZodType<B["_output"], ZodPipelineDef<A, B>, A["_input"]> { + _parse(input: ParseInput): ParseReturnType<any> { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + + static create<A extends ZodTypeAny, B extends ZodTypeAny>( + a: A, + b: B + ): ZodPipeline<A, B> { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } +} diff --git a/src/types/promise.ts b/src/types/promise.ts new file mode 100644 index 000000000..56bedef6b --- /dev/null +++ b/src/types/promise.ts @@ -0,0 +1,74 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + OK, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +////////////////////////////////////////// +////////////////////////////////////////// +////////// ////////// +////////// ZodPromise ////////// +////////// ////////// +////////////////////////////////////////// +////////////////////////////////////////// + +export interface ZodPromiseDef<T extends ZodTypeAny = ZodTypeAny> + extends ZodTypeDef { + type: T; + typeName: ZodFirstPartyTypeKind.ZodPromise; +} + +export class ZodPromise<T extends ZodTypeAny> extends ZodType< + Promise<T["_output"]>, + ZodPromiseDef<T>, + Promise<T["_input"]> +> { + unwrap() { + return this._def.type; + } + + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { ctx } = this._processInputParams(input); + if ( + ctx.parsedType !== ZodParsedType.promise && + ctx.common.async === false + ) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, + }); + return INVALID; + } + + const promisified = + ctx.parsedType === ZodParsedType.promise + ? ctx.data + : Promise.resolve(ctx.data); + + return OK( + promisified.then((data: any) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + }) + ); + } + + static create = <T extends ZodTypeAny>( + schema: T, + params?: RawCreateParams + ): ZodPromise<T> => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/readonly.ts b/src/types/readonly.ts new file mode 100644 index 000000000..023c9aa9b --- /dev/null +++ b/src/types/readonly.ts @@ -0,0 +1,65 @@ +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { processCreateParams } from "./utils"; +import { isValid, ParseInput, ParseReturnType } from "./utils/parseUtil"; + +/////////////////////////////////////////// +/////////////////////////////////////////// +////////// ////////// +////////// ZodReadonly ////////// +////////// ////////// +/////////////////////////////////////////// +/////////////////////////////////////////// +type BuiltIn = + | (((...args: any[]) => any) | (new (...args: any[]) => any)) + | { readonly [Symbol.toStringTag]: string } + | Date + | Error + | Generator + | Promise<unknown> + | RegExp; +type MakeReadonly<T> = T extends Map<infer K, infer V> + ? ReadonlyMap<K, V> + : T extends Set<infer V> + ? ReadonlySet<V> + : T extends [infer Head, ...infer Tail] + ? readonly [Head, ...Tail] + : T extends Array<infer V> + ? ReadonlyArray<V> + : T extends BuiltIn + ? T + : Readonly<T>; + +export interface ZodReadonlyDef<T extends ZodTypeAny = ZodTypeAny> + extends ZodTypeDef { + innerType: T; + typeName: ZodFirstPartyTypeKind.ZodReadonly; +} + +export class ZodReadonly<T extends ZodTypeAny> extends ZodType< + MakeReadonly<T["_output"]>, + ZodReadonlyDef<T>, + MakeReadonly<T["_input"]> +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const result = this._def.innerType._parse(input); + if (isValid(result)) { + result.value = Object.freeze(result.value); + } + return result; + } + + static create = <T extends ZodTypeAny>( + type: T, + params?: RawCreateParams + ): ZodReadonly<T> => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }) as any; + }; + + unwrap() { + return this._def.innerType; + } +} diff --git a/src/types/record.ts b/src/types/record.ts new file mode 100644 index 000000000..5bb937841 --- /dev/null +++ b/src/types/record.ts @@ -0,0 +1,121 @@ +import { BRAND } from "./branded"; +import { ZodIssueCode } from "./error"; +import { + ParseInputLazyPath, + RawCreateParams, + ZodFirstPartyTypeKind, ZodType, + ZodTypeAny, + ZodTypeDef } from "./index"; +import { ZodString } from "./string"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + ParseInput, + ParseReturnType, + ParseStatus, +} from "./utils/parseUtil"; + +export interface ZodRecordDef< + Key extends KeySchema = ZodString, + Value extends ZodTypeAny = ZodTypeAny +> extends ZodTypeDef { + valueType: Value; + keyType: Key; + typeName: ZodFirstPartyTypeKind.ZodRecord; +} + +export type KeySchema = ZodType<string | number | symbol, any, any>; + +export type RecordType<K extends string | number | symbol, V> = [ + string +] extends [K] + ? Record<K, V> + : [number] extends [K] + ? Record<K, V> + : [symbol] extends [K] + ? Record<K, V> + : [BRAND<string | number | symbol>] extends [K] + ? Record<K, V> + : Partial<Record<K, V>>; + +export class ZodRecord< + Key extends KeySchema = ZodString, + Value extends ZodTypeAny = ZodTypeAny +> extends ZodType< + RecordType<Key["_output"], Value["_output"]>, + ZodRecordDef<Key, Value>, + RecordType<Key["_input"], Value["_input"]> +> { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + + const pairs: { + key: ParseReturnType<any>; + value: ParseReturnType<any>; + }[] = []; + + const keyType = this._def.keyType; + const valueType = this._def.valueType; + + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse( + new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key) + ), + }); + } + + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs as any); + } + } + + get element() { + return this._def.valueType; + } + + static create<Value extends ZodTypeAny>( + valueType: Value, + params?: RawCreateParams + ): ZodRecord<ZodString, Value>; + static create<Keys extends KeySchema, Value extends ZodTypeAny>( + keySchema: Keys, + valueType: Value, + params?: RawCreateParams + ): ZodRecord<Keys, Value>; + static create(first: any, second?: any, third?: any): ZodRecord<any, any> { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } +} diff --git a/src/types/set.ts b/src/types/set.ts new file mode 100644 index 000000000..23b0bf90f --- /dev/null +++ b/src/types/set.ts @@ -0,0 +1,129 @@ +import { ZodIssueCode } from "./error"; +import { + ParseInputLazyPath, + RawCreateParams, + ZodFirstPartyTypeKind, ZodType, + ZodTypeAny, + ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { errorUtil } from "./utils/errorUtil"; +import { + addIssueToContext, + INVALID, + ParseInput, + ParseReturnType, + SyncParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodSetDef<Value extends ZodTypeAny = ZodTypeAny> + extends ZodTypeDef { + valueType: Value; + typeName: ZodFirstPartyTypeKind.ZodSet; + minSize: { value: number; message?: string } | null; + maxSize: { value: number; message?: string } | null; +} + +export class ZodSet<Value extends ZodTypeAny = ZodTypeAny> extends ZodType< + Set<Value["_output"]>, + ZodSetDef<Value>, + Set<Value["_input"]> +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + + const def = this._def; + + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + + const valueType = this._def.valueType; + + function finalizeSet(elements: SyncParseReturnType<any>[]) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") return INVALID; + if (element.status === "dirty") status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + + const elements = [...(ctx.data as Set<unknown>).values()].map((item, i) => + valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)) + ); + + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } else { + return finalizeSet(elements as SyncParseReturnType[]); + } + } + + min(minSize: number, message?: errorUtil.ErrMessage): this { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }) as any; + } + + max(maxSize: number, message?: errorUtil.ErrMessage): this { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }) as any; + } + + size(size: number, message?: errorUtil.ErrMessage): this { + return this.min(size, message).max(size, message) as any; + } + + nonempty(message?: errorUtil.ErrMessage): ZodSet<Value> { + return this.min(1, message) as any; + } + + static create = <Value extends ZodTypeAny = ZodTypeAny>( + valueType: Value, + params?: RawCreateParams + ): ZodSet<Value> => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/string.ts b/src/types/string.ts new file mode 100644 index 000000000..3ecccfc04 --- /dev/null +++ b/src/types/string.ts @@ -0,0 +1,553 @@ +import { StringValidation, ZodIssueCode } from "../external"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, util, ZodParsedType } from "./utils"; +import { errorUtil } from "./utils/errorUtil"; +import { + addIssueToContext, + INVALID, + ParseContext, + ParseInput, + ParseReturnType, + ParseStatus, +} from "./utils/parseUtil"; + +export type IpVersion = "v4" | "v6"; +export type ZodStringCheck = + | { kind: "min"; value: number; message?: string } + | { kind: "max"; value: number; message?: string } + | { kind: "length"; value: number; message?: string } + | { kind: "email"; message?: string } + | { kind: "url"; message?: string } + | { kind: "emoji"; message?: string } + | { kind: "uuid"; message?: string } + | { kind: "cuid"; message?: string } + | { kind: "includes"; value: string; position?: number; message?: string } + | { kind: "cuid2"; message?: string } + | { kind: "ulid"; message?: string } + | { kind: "startsWith"; value: string; message?: string } + | { kind: "endsWith"; value: string; message?: string } + | { kind: "regex"; regex: RegExp; message?: string } + | { kind: "trim"; message?: string } + | { kind: "toLowerCase"; message?: string } + | { kind: "toUpperCase"; message?: string } + | { + kind: "datetime"; + offset: boolean; + precision: number | null; + message?: string; + } + | { kind: "ip"; version?: IpVersion; message?: string }; + +export interface ZodStringDef extends ZodTypeDef { + checks: ZodStringCheck[]; + typeName: ZodFirstPartyTypeKind.ZodString; + coerce: boolean; +} +export const cuidRegex = /^c[^\s-]{8,}$/i; +export const cuid2Regex = /^[a-z][a-z0-9]*$/; +export const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; +export const uuidRegex = + /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode + +export const emailRegex = + /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex: RegExp; +export const ipv4Regex = + /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; +export const ipv6Regex = + /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +// Adapted from https://stackoverflow.com/a/3143231 +export const datetimeRegex = (args: { + precision: number | null; + offset: boolean; +}) => { + if (args.precision) { + if (args.offset) { + return new RegExp( + `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$` + ); + } else { + return new RegExp( + `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$` + ); + } + } else if (args.precision === 0) { + if (args.offset) { + return new RegExp( + `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$` + ); + } else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); + } + } else { + if (args.offset) { + return new RegExp( + `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$` + ); + } else { + return new RegExp( + `^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$` + ); + } + } +}; +function isValidIP(ip: string, version?: IpVersion) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + + return false; +} + +export class ZodString extends ZodType<string, ZodStringDef> { + _parse(input: ParseInput): ParseReturnType<string> { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext( + ctx, + { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + } + // + ); + return INVALID; + } + + const status = new ParseStatus(); + let ctx: undefined | ParseContext = undefined; + + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input.data = input.data.trim(); + } else if (check.kind === "includes") { + if (!(input.data as string).includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!(input.data as string).startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!(input.data as string).endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + + return { status: status.value, value: input.data }; + } + + protected _regex( + regex: RegExp, + validation: StringValidation, + message?: errorUtil.ErrMessage + ) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + } + + _addCheck(check: ZodStringCheck) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + + email(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + cuid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message?: errorUtil.ErrMessage) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + + ip(options?: string | { version?: "v4" | "v6"; message?: string }) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + + datetime( + options?: + | string + | { + message?: string | undefined; + precision?: number | null; + offset?: boolean; + } + ) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: + typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + ...errorUtil.errToObj(options?.message), + }); + } + + regex(regex: RegExp, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + + includes(value: string, options?: { message?: string; position?: number }) { + return this._addCheck({ + kind: "includes", + value: value, + position: options?.position, + ...errorUtil.errToObj(options?.message), + }); + } + + startsWith(value: string, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + + endsWith(value: string, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + + min(minLength: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + + max(maxLength: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + + length(len: number, message?: errorUtil.ErrMessage) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + + /** + * @deprecated Use z.string().min(1) instead. + * @see {@link ZodString.min} + */ + nonempty(message?: errorUtil.ErrMessage) { + return this.min(1, errorUtil.errToObj(message)); + } + + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + + get minLength() { + let min: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) min = ch.value; + } + } + return min; + } + get maxLength() { + let max: number | null = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) max = ch.value; + } + } + return max; + } + + static create = (params?: RawCreateParams & { coerce?: true }): ZodString => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/symbol.ts b/src/types/symbol.ts new file mode 100644 index 000000000..d26ec6f9d --- /dev/null +++ b/src/types/symbol.ts @@ -0,0 +1,38 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + OK, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodSymbolDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodSymbol; +} + +export class ZodSymbol extends ZodType<symbol, ZodSymbolDef, symbol> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + + return OK(input.data); + } + + static create = (params?: RawCreateParams): ZodSymbol => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/templateLiteral.ts b/src/types/templateLiteral.ts new file mode 100644 index 000000000..7591ce1fc --- /dev/null +++ b/src/types/templateLiteral.ts @@ -0,0 +1,478 @@ +import { ZodAny } from "./any"; +import { ZodBigInt } from "./bigint"; +import { ZodBoolean } from "./boolean"; +import { ZodBranded } from "./branded"; +import { ZodEnum } from "./enum"; +import { + ZodIssueCode, + ZodTemplateLiteralUnsupportedCheckError, + ZodTemplateLiteralUnsupportedTypeError, +} from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { ZodLazy } from "./lazy"; +import { ZodLiteral } from "./literal"; +import { ZodNaN } from "./nan"; +import { ZodNativeEnum } from "./nativeEnum"; +import { ZodNever } from "./never"; +import { ZodNull } from "./null"; +import { ZodNullable } from "./nullable"; +import { ZodNumber } from "./number"; +import { ZodOptional } from "./optional"; +import { ZodPipeline } from "./pipeline"; +import { + cuid2Regex, + cuidRegex, + datetimeRegex, + emailRegex, + ipv4Regex, + ipv6Regex, + ulidRegex, + uuidRegex, + ZodString, + ZodStringCheck, +} from "./string"; +import { ZodUndefined } from "./undefined"; +import { ZodUnion } from "./union"; +import { processCreateParams, util, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +type TemplateLiteralPrimitive = string | number | boolean | null | undefined; +type TemplateLiteralInterpolatedPosition = ZodType< + TemplateLiteralPrimitive | bigint +>; +type appendToTemplateLiteral< + Template extends string, + Suffix extends TemplateLiteralPrimitive | ZodType +> = Suffix extends TemplateLiteralPrimitive + ? `${Template}${Suffix}` + : Suffix extends ZodOptional<infer UnderlyingType> + ? Template | appendToTemplateLiteral<Template, UnderlyingType> + : Suffix extends ZodBranded<infer UnderlyingType, any> + ? appendToTemplateLiteral<Template, UnderlyingType> + : Suffix extends ZodType<infer Output, any, any> + ? Output extends TemplateLiteralPrimitive | bigint + ? `${Template}${Output}` + : never + : never; + +export interface ZodTemplateLiteralDef extends ZodTypeDef { + coerce: boolean; + parts: readonly ( + | TemplateLiteralPrimitive + | TemplateLiteralInterpolatedPosition + )[]; + regexString: string; + typeName: ZodFirstPartyTypeKind.ZodTemplateLiteral; +} + +export class ZodTemplateLiteral<Template extends string = ""> extends ZodType< + Template, + ZodTemplateLiteralDef +> { + interpolated<I extends TemplateLiteralInterpolatedPosition>( + type: Exclude<I, ZodNever | ZodNaN | ZodPipeline<any, any> | ZodLazy<any>> + ): ZodTemplateLiteral<appendToTemplateLiteral<Template, I>> { + return this._addPart(type) as any; + } + + literal<L extends TemplateLiteralPrimitive>( + literal: L + ): ZodTemplateLiteral<appendToTemplateLiteral<Template, L>> { + return this._addPart(literal) as any; + } + + _parse(input: ParseInput): ParseReturnType<Template> { + if (this._def.coerce) { + input.data = String(input.data); + } + + const parsedType = this._getType(input); + + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + }); + return INVALID; + } + + if (!new RegExp(this._def.regexString).test(input.data)) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + message: `does not match template literal with pattern /${this._def.regexString}/`, + path: ctx.path, + validation: "regex", + }); + return INVALID; + } + + return { status: "valid", value: input.data }; + } + + protected _addPart( + part: TemplateLiteralPrimitive | TemplateLiteralInterpolatedPosition + ): ZodTemplateLiteral { + const parts = [...this._def.parts, part]; + + return new ZodTemplateLiteral({ + ...this._def, + parts, + regexString: this._appendToRegexString(this._def.regexString, part), + }); + } + + protected _appendToRegexString( + regexString: string, + part: TemplateLiteralPrimitive | TemplateLiteralInterpolatedPosition + ): string { + return `^${this._unwrapRegExp( + regexString + )}${this._transformPartToRegexString(part)}$`; + } + + protected _transformPartToRegexString( + part: TemplateLiteralPrimitive | TemplateLiteralInterpolatedPosition + ): string { + if (!(part instanceof ZodType)) { + return this._escapeRegExp(part); + } + + if (part instanceof ZodLiteral) { + return this._escapeRegExp(part._def.value); + } + + if (part instanceof ZodString) { + return this._transformZodStringPartToRegexString(part); + } + + if (part instanceof ZodEnum || part instanceof ZodNativeEnum) { + const values = + part instanceof ZodEnum + ? part._def.values + : util.getValidEnumValues(part._def.values); + + return `(${values.map(this._escapeRegExp).join("|")})`; + } + + if (part instanceof ZodUnion) { + return `(${(part._def.options as any[]) + .map((option) => this._transformPartToRegexString(option)) + .join("|")})`; + } + + if (part instanceof ZodNumber) { + return this._transformZodNumberPartToRegexString(part); + } + + if (part instanceof ZodOptional) { + return `(${this._transformPartToRegexString(part.unwrap())})?`; + } + + if (part instanceof ZodTemplateLiteral) { + return this._unwrapRegExp(part._def.regexString); + } + + if (part instanceof ZodBigInt) { + // FIXME: include/exclude '-' based on min/max values after https://github.com/colinhacks/zod/pull/1711 is merged. + return "\\-?\\d+"; + } + + if (part instanceof ZodBoolean) { + return "(true|false)"; + } + + if (part instanceof ZodNullable) { + do { + part = part.unwrap(); + } while (part instanceof ZodNullable); + + return `(${this._transformPartToRegexString(part)}|null)${ + part instanceof ZodOptional ? "?" : "" + }`; + } + + if (part instanceof ZodBranded) { + return this._transformPartToRegexString(part.unwrap()); + } + + if (part instanceof ZodAny) { + return ".*"; + } + + if (part instanceof ZodNull) { + return "null"; + } + + if (part instanceof ZodUndefined) { + return "undefined"; + } + + throw new ZodTemplateLiteralUnsupportedTypeError(); + } + + // FIXME: we don't support transformations, so `.trim()` is not supported. + protected _transformZodStringPartToRegexString(part: ZodString): string { + let maxLength = Infinity, + minLength = 0, + endsWith = "", + startsWith = ""; + + for (const ch of part._def.checks) { + const regex = this._resolveRegexForStringCheck(ch); + + if (regex) { + return this._unwrapRegExp(regex); + } + + if (ch.kind === "endsWith") { + endsWith = ch.value; + } else if (ch.kind === "length") { + minLength = maxLength = ch.value; + } else if (ch.kind === "max") { + maxLength = Math.max(0, Math.min(maxLength, ch.value)); + } else if (ch.kind === "min") { + minLength = Math.max(minLength, ch.value); + } else if (ch.kind === "startsWith") { + startsWith = ch.value; + } else { + throw new ZodTemplateLiteralUnsupportedCheckError( + ZodFirstPartyTypeKind.ZodString, + ch.kind + ); + } + } + + const constrainedMinLength = Math.max( + 0, + minLength - startsWith.length - endsWith.length + ); + const constrainedMaxLength = Number.isFinite(maxLength) + ? Math.max(0, maxLength - startsWith.length - endsWith.length) + : Infinity; + + if ( + constrainedMaxLength === 0 || + constrainedMinLength > constrainedMaxLength + ) { + return `${startsWith}${endsWith}`; + } + + return `${startsWith}.${this._resolveRegexWildcardLength( + constrainedMinLength, + constrainedMaxLength + )}${endsWith}`; + } + + protected _resolveRegexForStringCheck(check: ZodStringCheck): RegExp | null { + return { + [check.kind]: null, + cuid: cuidRegex, + cuid2: cuid2Regex, + datetime: check.kind === "datetime" ? datetimeRegex(check) : null, + email: emailRegex, + ip: + check.kind === "ip" + ? { + any: new RegExp( + `^(${this._unwrapRegExp( + ipv4Regex.source + )})|(${this._unwrapRegExp(ipv6Regex.source)})$` + ), + v4: ipv4Regex, + v6: ipv6Regex, + }[check.version || "any"] + : null, + regex: check.kind === "regex" ? check.regex : null, + ulid: ulidRegex, + uuid: uuidRegex, + }[check.kind]; + } + + protected _resolveRegexWildcardLength( + minLength: number, + maxLength: number + ): string { + if (minLength === maxLength) { + return minLength === 1 ? "" : `{${minLength}}`; + } + + if (maxLength !== Infinity) { + return `{${minLength},${maxLength}}`; + } + + if (minLength === 0) { + return "*"; + } + + if (minLength === 1) { + return "+"; + } + + return `{${minLength},}`; + } + + // FIXME: we do not support exponent notation (e.g. 2e5) since it conflicts with `.int()`. + protected _transformZodNumberPartToRegexString(part: ZodNumber): string { + let canBeNegative = true, + canBePositive = true, + min = -Infinity, + max = Infinity, + canBeZero = true, + isFinite = false, + isInt = false, + acc = ""; + + for (const ch of part._def.checks) { + if (ch.kind === "finite") { + isFinite = true; + } else if (ch.kind === "int") { + isInt = true; + } else if (ch.kind === "max") { + max = Math.min(max, ch.value); + + if (ch.value <= 0) { + canBePositive = false; + + if (ch.value === 0 && !ch.inclusive) { + canBeZero = false; + } + } + } else if (ch.kind === "min") { + min = Math.max(min, ch.value); + + if (ch.value >= 0) { + canBeNegative = false; + + if (ch.value === 0 && !ch.inclusive) { + canBeZero = false; + } + } + } else { + throw new ZodTemplateLiteralUnsupportedCheckError( + ZodFirstPartyTypeKind.ZodNumber, + ch.kind + ); + } + } + + if (Number.isFinite(min) && Number.isFinite(max)) { + isFinite = true; + } + + if (canBeNegative) { + acc = `${acc}\\-`; + + if (canBePositive) { + acc = `${acc}?`; + } + } else if (!canBePositive) { + return "0+"; + } + + if (!isFinite) { + acc = `${acc}(Infinity|(`; + } + + if (!canBeZero) { + if (!isInt) { + acc = `${acc}((\\d*[1-9]\\d*(\\.\\d+)?)|(\\d+\\.\\d*[1-9]\\d*))`; + } else { + acc = `${acc}\\d*[1-9]\\d*`; + } + } else if (isInt) { + acc = `${acc}\\d+`; + } else { + acc = `${acc}\\d+(\\.\\d+)?`; + } + + if (!isFinite) { + acc = `${acc}))`; + } + + return acc; + } + + protected _unwrapRegExp(regex: RegExp | string): string { + const flags = typeof regex === "string" ? "" : regex.flags; + const source = typeof regex === "string" ? regex : regex.source; + + if (flags.includes("i")) { + return this._unwrapRegExp(this._makeRegexStringCaseInsensitive(source)); + } + + return source.replace(/(^\^)|(\$$)/g, ""); + } + + protected _makeRegexStringCaseInsensitive(regexString: string): string { + const isAlphabetic = (char: string) => char.match(/[a-z]/i) != null; + + let caseInsensitive = ""; + let inCharacterSet = false; + for (let i = 0; i < regexString.length; i++) { + const char = regexString.charAt(i); + const nextChar = regexString.charAt(i + 1); + + if (char === "\\") { + caseInsensitive += `${char}${nextChar}`; + i++; + continue; + } + + if (char === "[") { + inCharacterSet = true; + } else if (inCharacterSet && char === "]") { + inCharacterSet = false; + } + + if (!isAlphabetic(char)) { + caseInsensitive += char; + continue; + } + + if (!inCharacterSet) { + caseInsensitive += `[${char.toLowerCase()}${char.toUpperCase()}]`; + continue; + } + + const charAfterNext = regexString.charAt(i + 2); + + if (nextChar !== "-" || !isAlphabetic(charAfterNext)) { + caseInsensitive += `${char.toLowerCase()}${char.toUpperCase()}`; + continue; + } + + caseInsensitive += `${char.toLowerCase()}-${charAfterNext.toLowerCase()}${char.toUpperCase()}-${charAfterNext.toUpperCase()}`; + i += 2; + } + + return caseInsensitive; + } + + protected _escapeRegExp(str: unknown): string { + if (typeof str !== "string") { + str = `${str}`; + } + + return (str as string).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + + static create = ( + params?: RawCreateParams & { coerce?: true } + ): ZodTemplateLiteral => { + return new ZodTemplateLiteral({ + ...processCreateParams(params), + coerce: params?.coerce ?? false, + parts: [], + regexString: "^$", + typeName: ZodFirstPartyTypeKind.ZodTemplateLiteral, + }); + }; +} diff --git a/src/types/transformer.ts b/src/types/transformer.ts new file mode 100644 index 000000000..790379600 --- /dev/null +++ b/src/types/transformer.ts @@ -0,0 +1,216 @@ +import { IssueData } from "./error"; +import { + input, + output, + RawCreateParams, + RefinementCtx, + ZodFirstPartyTypeKind, ZodType, + ZodTypeAny, + ZodTypeDef } from "./index"; +import { processCreateParams, util } from "./utils"; +import { + addIssueToContext, + DIRTY, + INVALID, + isValid, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +export type Refinement<T> = (arg: T, ctx: RefinementCtx) => any; +export type SuperRefinement<T> = ( + arg: T, + ctx: RefinementCtx +) => void | Promise<void>; + +export type RefinementEffect<T> = { + type: "refinement"; + refinement: (arg: T, ctx: RefinementCtx) => any; +}; +export type TransformEffect<T> = { + type: "transform"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export type PreprocessEffect<T> = { + type: "preprocess"; + transform: (arg: T, ctx: RefinementCtx) => any; +}; +export type Effect<T> = + | RefinementEffect<T> + | TransformEffect<T> + | PreprocessEffect<T>; + +export interface ZodEffectsDef<T extends ZodTypeAny = ZodTypeAny> + extends ZodTypeDef { + schema: T; + typeName: ZodFirstPartyTypeKind.ZodEffects; + effect: Effect<any>; +} + +export class ZodEffects< + T extends ZodTypeAny, + Output = output<T>, + Input = input<T> +> extends ZodType<Output, ZodEffectsDef<T>, Input> { + innerType() { + return this._def.schema; + } + + sourceType(): T { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? (this._def.schema as unknown as ZodEffects<T>).sourceType() + : (this._def.schema as T); + } + + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { status, ctx } = this._processInputParams(input); + + const effect = this._def.effect || null; + + const checkCtx: RefinementCtx = { + addIssue: (arg: IssueData) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") return INVALID; + + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") return INVALID; + if (result.status === "dirty") return DIRTY(result.value); + if (status.value === "dirty") return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") return INVALID; + if (result.status === "dirty") return DIRTY(result.value); + if (status.value === "dirty") return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc: unknown): any => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error( + "Async refinement encountered during synchronous parse operation. Use .parseAsync instead." + ); + } + return acc; + }; + + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") return INVALID; + if (inner.status === "dirty") status.dirty(); + + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((inner) => { + if (inner.status === "aborted") return INVALID; + if (inner.status === "dirty") status.dirty(); + + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + + if (!isValid(base)) return base; + + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error( + `Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.` + ); + } + + return { status: status.value, value: result }; + } else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((base) => { + if (!isValid(base)) return base; + + return Promise.resolve(effect.transform(base.value, checkCtx)).then( + (result) => ({ status: status.value, value: result }) + ); + }); + } + } + + util.assertNever(effect); + } + + static create = <I extends ZodType>( + schema: I, + effect: Effect<I["_output"]>, + params?: RawCreateParams + ): ZodEffects<I, I["_output"]> => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); + }; + + static createWithPreprocess = <I extends ZodTypeAny>( + preprocess: (arg: unknown, ctx: RefinementCtx) => unknown, + schema: I, + params?: RawCreateParams + ): ZodEffects<I, I["_output"], unknown> => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); + }; +} +export { ZodEffects as ZodTransformer }; diff --git a/src/types/tuple.ts b/src/types/tuple.ts new file mode 100644 index 000000000..86fff942f --- /dev/null +++ b/src/types/tuple.ts @@ -0,0 +1,141 @@ +import { ZodIssueCode } from "./error"; +import { + ParseInputLazyPath, + RawCreateParams, + ZodFirstPartyTypeKind, ZodType, + ZodTypeAny, + ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + ParseInput, + ParseReturnType, + ParseStatus, + SyncParseReturnType, +} from "./utils/parseUtil"; + +export type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +export type AssertArray<T> = T extends any[] ? T : never; +export type OutputTypeOfTuple<T extends ZodTupleItems | []> = AssertArray<{ + [k in keyof T]: T[k] extends ZodType<any, any> ? T[k]["_output"] : never; +}>; +export type OutputTypeOfTupleWithRest< + T extends ZodTupleItems | [], + Rest extends ZodTypeAny | null = null +> = Rest extends ZodTypeAny + ? [...OutputTypeOfTuple<T>, ...Rest["_output"][]] + : OutputTypeOfTuple<T>; + +export type InputTypeOfTuple<T extends ZodTupleItems | []> = AssertArray<{ + [k in keyof T]: T[k] extends ZodType<any, any> ? T[k]["_input"] : never; +}>; +export type InputTypeOfTupleWithRest< + T extends ZodTupleItems | [], + Rest extends ZodTypeAny | null = null +> = Rest extends ZodTypeAny + ? [...InputTypeOfTuple<T>, ...Rest["_input"][]] + : InputTypeOfTuple<T>; + +export interface ZodTupleDef< + T extends ZodTupleItems | [] = ZodTupleItems, + Rest extends ZodTypeAny | null = null +> extends ZodTypeDef { + items: T; + rest: Rest; + typeName: ZodFirstPartyTypeKind.ZodTuple; +} + +export type AnyZodTuple = ZodTuple< + [ZodTypeAny, ...ZodTypeAny[]] | [], + ZodTypeAny | null +>; +export class ZodTuple< + T extends [ZodTypeAny, ...ZodTypeAny[]] | [] = [ZodTypeAny, ...ZodTypeAny[]], + Rest extends ZodTypeAny | null = null +> extends ZodType< + OutputTypeOfTupleWithRest<T, Rest>, + ZodTupleDef<T, Rest>, + InputTypeOfTupleWithRest<T, Rest> +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + + return INVALID; + } + + const rest = this._def.rest; + + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + + const items = ([...ctx.data] as any[]) + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) return null as any as SyncParseReturnType<any>; + return schema._parse( + new ParseInputLazyPath(ctx, item, ctx.path, itemIndex) + ); + }) + .filter((x) => !!x); // filter nulls + + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items as SyncParseReturnType[]); + } + } + + get items() { + return this._def.items; + } + + rest<Rest extends ZodTypeAny>(rest: Rest): ZodTuple<T, Rest> { + return new ZodTuple({ + ...this._def, + rest, + }); + } + + static create = <T extends [ZodTypeAny, ...ZodTypeAny[]] | []>( + schemas: T, + params?: RawCreateParams + ): ZodTuple<T, null> => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/undefined.ts b/src/types/undefined.ts new file mode 100644 index 000000000..a52a1f52e --- /dev/null +++ b/src/types/undefined.ts @@ -0,0 +1,38 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + OK, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodUndefinedDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUndefined; +} + +export class ZodUndefined extends ZodType<undefined, ZodUndefinedDef> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + params?: RawCreateParams; + + static create = (params?: RawCreateParams): ZodUndefined => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/union.ts b/src/types/union.ts new file mode 100644 index 000000000..a14bfeef2 --- /dev/null +++ b/src/types/union.ts @@ -0,0 +1,153 @@ +import { ZodError, ZodIssue, ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { processCreateParams } from "./utils"; +import { + addIssueToContext, + DIRTY, + INVALID, + ParseContext, + ParseInput, + ParseReturnType, + SyncParseReturnType, +} from "./utils/parseUtil"; + +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// ZodUnion ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// + +export type ZodUnionOptions = Readonly<[ZodTypeAny, ...ZodTypeAny[]]>; +export interface ZodUnionDef< + T extends ZodUnionOptions = Readonly< + [ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]] + > +> extends ZodTypeDef { + options: T; + typeName: ZodFirstPartyTypeKind.ZodUnion; +} + +export class ZodUnion<T extends ZodUnionOptions> extends ZodType< + T[number]["_output"], + ZodUnionDef<T>, + T[number]["_input"] +> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + + function handleResults( + results: { ctx: ParseContext; result: SyncParseReturnType<any> }[] + ) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + + // return invalid + const unionErrors = results.map( + (result) => new ZodError(result.ctx.common.issues) + ); + + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + + if (ctx.common.async) { + return Promise.all( + options.map(async (option) => { + const childCtx: ParseContext = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + }) + ).then(handleResults); + } else { + let dirty: undefined | { result: DIRTY<any>; ctx: ParseContext } = + undefined; + const issues: ZodIssue[][] = []; + for (const option of options) { + const childCtx: ParseContext = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + + return INVALID; + } + } + + get options() { + return this._def.options; + } + + static create = < + T extends Readonly<[ZodTypeAny, ZodTypeAny, ...ZodTypeAny[]]> + >( + types: T, + params?: RawCreateParams + ): ZodUnion<T> => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); + }; +} diff --git a/src/types/unknown.ts b/src/types/unknown.ts new file mode 100644 index 000000000..78c709736 --- /dev/null +++ b/src/types/unknown.ts @@ -0,0 +1,22 @@ +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams } from "./utils"; +import { OK, ParseInput, ParseReturnType } from "./utils/parseUtil"; + +export interface ZodUnknownDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodUnknown; +} + +export class ZodUnknown extends ZodType<unknown, ZodUnknownDef> { + // required + _unknown = true as const; + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + return OK(input.data); + } + + static create = (params?: RawCreateParams): ZodUnknown => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); + }; +} diff --git a/src/helpers/enumUtil.ts b/src/types/utils/enumUtil.ts similarity index 100% rename from src/helpers/enumUtil.ts rename to src/types/utils/enumUtil.ts diff --git a/src/helpers/errorUtil.ts b/src/types/utils/errorUtil.ts similarity index 100% rename from src/helpers/errorUtil.ts rename to src/types/utils/errorUtil.ts diff --git a/src/helpers/util.ts b/src/types/utils/index.ts similarity index 85% rename from src/helpers/util.ts rename to src/types/utils/index.ts index 39e1e8025..fede00ca7 100644 --- a/src/helpers/util.ts +++ b/src/types/utils/index.ts @@ -1,3 +1,6 @@ +import type { ZodErrorMap } from "../error"; +import type { ProcessedCreateParams, RawCreateParams } from "../index"; + export namespace util { type AssertEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends < V @@ -108,10 +111,6 @@ export namespace objectUtil { [k in keyof T]: undefined extends T[k] ? never : k; }[keyof T]; - // export type addQuestionMarks< - // T extends object, - // R extends keyof T = requiredKeys<T> - // > = Pick<Required<T>, R> & Partial<T>; export type addQuestionMarks< T extends object, R extends keyof T = requiredKeys<T>, @@ -219,3 +218,23 @@ export const getParsedType = (data: any): ZodParsedType => { return ZodParsedType.unknown; } }; +export function processCreateParams( + params: RawCreateParams +): ProcessedCreateParams { + if (!params) return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error( + `Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.` + ); + } + if (errorMap) return { errorMap: errorMap, description }; + const customMap: ZodErrorMap = (iss, ctx) => { + if (iss.code !== "invalid_type") return { message: ctx.defaultError }; + if (typeof ctx.data === "undefined") { + return { message: required_error ?? ctx.defaultError }; + } + return { message: invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} diff --git a/src/helpers/parseUtil.ts b/src/types/utils/parseUtil.ts similarity index 96% rename from src/helpers/parseUtil.ts rename to src/types/utils/parseUtil.ts index 4824fcf7f..258b84efa 100644 --- a/src/helpers/parseUtil.ts +++ b/src/types/utils/parseUtil.ts @@ -1,7 +1,6 @@ -import { getErrorMap } from "../errors"; -import defaultErrorMap from "../locales/en"; -import type { IssueData, ZodErrorMap, ZodIssue } from "../ZodError"; -import type { ZodParsedType } from "./util"; +import { defaultErrorMap, getErrorMap } from "../../external"; +import { IssueData, ZodErrorMap, ZodIssue } from "../error"; +import type { ZodParsedType } from "."; export const makeIssue = (params: { data: any; diff --git a/src/helpers/partialUtil.ts b/src/types/utils/partialUtil.ts similarity index 90% rename from src/helpers/partialUtil.ts rename to src/types/utils/partialUtil.ts index ebfa5ec31..74c86e08c 100644 --- a/src/helpers/partialUtil.ts +++ b/src/types/utils/partialUtil.ts @@ -1,13 +1,9 @@ -import type { - ZodArray, - ZodNullable, - ZodObject, - ZodOptional, - ZodRawShape, - ZodTuple, - ZodTupleItems, - ZodTypeAny, -} from "../index"; +import { ZodArray } from "../array"; +import { ZodRawShape, ZodTypeAny } from "../index"; +import { ZodNullable } from "../nullable"; +import { ZodObject } from "../object"; +import { ZodOptional } from "../optional"; +import { ZodTuple, ZodTupleItems } from "../tuple"; export namespace partialUtil { // export type DeepPartial<T extends AnyZodObject> = T extends AnyZodObject diff --git a/src/helpers/typeAliases.ts b/src/types/utils/typeAliases.ts similarity index 100% rename from src/helpers/typeAliases.ts rename to src/types/utils/typeAliases.ts diff --git a/src/types/void.ts b/src/types/void.ts new file mode 100644 index 000000000..3139da61f --- /dev/null +++ b/src/types/void.ts @@ -0,0 +1,37 @@ +import { ZodIssueCode } from "./error"; +import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; +import { processCreateParams, ZodParsedType } from "./utils"; +import { + addIssueToContext, + INVALID, + OK, + ParseInput, + ParseReturnType, +} from "./utils/parseUtil"; + +export interface ZodVoidDef extends ZodTypeDef { + typeName: ZodFirstPartyTypeKind.ZodVoid; +} + +export class ZodVoid extends ZodType<void, ZodVoidDef> { + _parse(input: ParseInput): ParseReturnType<this["_output"]> { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } + + static create = (params?: RawCreateParams): ZodVoid => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); + }; +} diff --git a/src/z.ts b/src/z.ts new file mode 100644 index 000000000..c01dd09f6 --- /dev/null +++ b/src/z.ts @@ -0,0 +1,205 @@ +import { + custom, + CustomParams, + INVALID, + ZodAny, + ZodArray, + ZodBigInt, + ZodBoolean, + ZodBranded, + ZodCatch, + ZodDate, + ZodDefault, + ZodDiscriminatedUnion, + ZodEffects, + ZodEnum, + ZodFunction, + ZodIntersection, + ZodLazy, + ZodLiteral, + ZodMap, + ZodNaN, + ZodNativeEnum, + ZodNever, + ZodNull, + ZodNullable, + ZodNumber, + ZodObject, + ZodOptional, + ZodPipeline, + ZodPromise, + ZodReadonly, + ZodRecord, + ZodSet, + ZodString, + ZodSymbol, + ZodTemplateLiteral, + ZodTuple, + ZodType, + ZodUndefined, + ZodUnion, + ZodUnknown, + ZodVoid, +} from "./types"; + +export { ZodType as Schema, ZodType as ZodSchema }; + +export const late = { + object: ZodObject.lazycreate, +}; + +export type ZodFirstPartySchemaTypes = + | ZodString + | ZodNumber + | ZodNaN + | ZodBigInt + | ZodBoolean + | ZodDate + | ZodUndefined + | ZodNull + | ZodAny + | ZodUnknown + | ZodNever + | ZodVoid + | ZodArray<any, any> + | ZodObject<any, any, any> + | ZodUnion<any> + | ZodDiscriminatedUnion<any, any> + | ZodIntersection<any, any> + | ZodTuple<any, any> + | ZodRecord<any, any> + | ZodMap<any> + | ZodSet<any> + | ZodFunction<any, any> + | ZodLazy<any> + | ZodLiteral<any> + | ZodEnum<any> + | ZodEffects<any, any, any> + | ZodNativeEnum<any> + | ZodOptional<any> + | ZodNullable<any> + | ZodDefault<any> + | ZodCatch<any> + | ZodPromise<any> + | ZodBranded<any, any> + | ZodPipeline<any, any> + | ZodReadonly<any> + | ZodSymbol + | ZodTemplateLiteral<any>; + +// requires TS 4.4+ +abstract class Class { + constructor(..._: any[]) {} +} +const instanceOfType = <T extends typeof Class>( + // const instanceOfType = <T extends new (...args: any[]) => any>( + cls: T, + params: CustomParams = { + message: `Input not instance of ${cls.name}`, + } +) => custom<InstanceType<T>>((data) => data instanceof cls, params); + +const stringType = ZodString.create; +const numberType = ZodNumber.create; +const nanType = ZodNaN.create; +const bigIntType = ZodBigInt.create; +const booleanType = ZodBoolean.create; +const dateType = ZodDate.create; +const symbolType = ZodSymbol.create; +const undefinedType = ZodUndefined.create; +const nullType = ZodNull.create; +const anyType = ZodAny.create; +const unknownType = ZodUnknown.create; +const neverType = ZodNever.create; +const voidType = ZodVoid.create; +const arrayType = ZodArray.create; +const objectType = ZodObject.create; +const strictObjectType = ZodObject.strictCreate; +const unionType = ZodUnion.create; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +const intersectionType = ZodIntersection.create; +const tupleType = ZodTuple.create; +const recordType = ZodRecord.create; +const mapType = ZodMap.create; +const setType = ZodSet.create; +const functionType = ZodFunction.create; +const lazyType = ZodLazy.create; +const literalType = ZodLiteral.create; +const enumType = ZodEnum.create; +const nativeEnumType = ZodNativeEnum.create; +const promiseType = ZodPromise.create; +const effectsType = ZodEffects.create; +const optionalType = ZodOptional.create; +const nullableType = ZodNullable.create; +const preprocessType = ZodEffects.createWithPreprocess; +const pipelineType = ZodPipeline.create; +const templateLiteralType = ZodTemplateLiteral.create; +const ostring = () => stringType().optional(); +const onumber = () => numberType().optional(); +const oboolean = () => booleanType().optional(); + +export const coerce = { + string: ((arg) => + ZodString.create({ ...arg, coerce: true })) as (typeof ZodString)["create"], + number: ((arg) => + ZodNumber.create({ ...arg, coerce: true })) as (typeof ZodNumber)["create"], + boolean: ((arg) => + ZodBoolean.create({ + ...arg, + coerce: true, + })) as (typeof ZodBoolean)["create"], + bigint: ((arg) => + ZodBigInt.create({ ...arg, coerce: true })) as (typeof ZodBigInt)["create"], + date: ((arg) => + ZodDate.create({ ...arg, coerce: true })) as (typeof ZodDate)["create"], + templateLiteral: ((arg) => + ZodTemplateLiteral.create({ + ...arg, + coerce: true, + })) as (typeof ZodTemplateLiteral)["create"], +}; + +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, + pipelineType as pipeline, + preprocessType as preprocess, + promiseType as promise, + recordType as record, + setType as set, + strictObjectType as strictObject, + stringType as string, + symbolType as symbol, + templateLiteralType as templateLiteral, + effectsType as transformer, + tupleType as tuple, + undefinedType as undefined, + unionType as union, + unknownType as unknown, + voidType as void, +}; + +export const NEVER = INVALID as never; From fb58a5e4e8834cb76eb6f01b4dc4e5f9c286287b Mon Sep 17 00:00:00 2001 From: Charles Catta <charles.catta@botpress.com> Date: Thu, 4 Apr 2024 12:05:53 -0400 Subject: [PATCH 3/3] Move files in folders --- playground.ts | 8 +++ src/__tests__/base.test.ts | 2 +- src/__tests__/firstpartyschematypes.test.ts | 24 --------- src/__tests__/generics.test.ts | 2 +- src/__tests__/instanceof.test.ts | 2 +- src/__tests__/parseUtil.test.ts | 2 +- src/__tests__/partials.test.ts | 2 +- src/__tests__/pickomit.test.ts | 2 +- src/__tests__/preprocess.test.ts | 2 +- src/__tests__/primitive.test.ts | 2 +- src/__tests__/recursive.test.ts | 2 +- src/__tests__/refine.test.ts | 2 +- src/__tests__/set.test.ts | 2 +- src/external.ts | 6 --- src/index.ts | 5 +- .../any}/anyunknown.test.ts | 4 +- src/types/{any.ts => any/index.ts} | 6 +-- src/{__tests__ => types/array}/array.test.ts | 4 +- src/types/{array.ts => array/index.ts} | 14 ++--- src/types/{basetype.ts => basetype/index.ts} | 2 +- .../bigint}/bigint.test.ts | 2 +- src/types/{bigint.ts => bigint/index.ts} | 24 ++++----- src/types/{boolean.ts => boolean/index.ts} | 13 +++-- .../branded}/branded.test.ts | 4 +- src/types/{branded.ts => branded/index.ts} | 9 +++- src/{__tests__ => types/catch}/catch.test.ts | 4 +- src/types/{catch.ts => catch/index.ts} | 14 +++-- .../custom}/custom.test.ts | 2 +- src/types/{custom.ts => custom/index.ts} | 4 +- src/{__tests__ => types/date}/date.test.ts | 2 +- src/types/{date.ts => date/index.ts} | 15 ++++-- .../default}/default.test.ts | 4 +- src/types/{default.ts => default/index.ts} | 12 +++-- .../firstparty.test.ts => types/defs.test.ts} | 22 +++++++- src/{ => types}/defs.ts | 54 +++++++++---------- .../discriminatedUnion.test.ts} | 2 +- .../index.ts} | 42 ++++++++------- src/{__tests__ => types/enum}/enum.test.ts | 4 +- src/types/{enum.ts => enum/index.ts} | 13 +++-- .../error}/all-errors.test.ts | 4 +- src/{__tests__ => types/error}/error.test.ts | 7 ++- .../function}/function.test.ts | 4 +- src/types/{function.ts => function/index.ts} | 20 ++++--- src/types/helpers/partialUtil.ts | 33 ------------ src/types/index.ts | 2 +- .../index.ts} | 14 +++-- .../intersection}/intersection.test.ts | 2 +- src/types/{lazy.ts => lazy/index.ts} | 10 ++-- src/types/{literal.ts => literal/index.ts} | 15 ++++-- .../literal}/literal.test.ts | 2 +- src/types/{map.ts => map/index.ts} | 12 +++-- src/{__tests__ => types/map}/map.test.ts | 6 +-- src/types/{nan.ts => nan/index.ts} | 21 ++++---- src/{__tests__ => types/nan}/nan.test.ts | 2 +- .../{nativeEnum.ts => nativeEnum/index.ts} | 8 +-- .../nativeEnum}/nativeEnum.test.ts | 4 +- src/types/{never.ts => never/index.ts} | 13 +++-- src/types/{null.ts => null/index.ts} | 13 +++-- src/types/{nullable.ts => nullable/index.ts} | 20 ++++--- .../nullable}/nullable.test.ts | 2 +- src/types/{number.ts => number/index.ts} | 15 ++++-- .../number}/number.test.ts | 2 +- src/types/{object.ts => object/index.ts} | 28 +++++----- .../object}/object-in-es5-env.test.ts | 2 +- .../object}/object.test.ts | 4 +- src/types/{optional.ts => optional/index.ts} | 12 +++-- .../optional}/optional.test.ts | 2 +- src/types/{pipeline.ts => pipeline/index.ts} | 14 ++++- .../pipeline}/pipeline.test.ts | 2 +- src/types/{promise.ts => promise/index.ts} | 22 ++++---- .../promise}/promise.test.ts | 4 +- src/types/{readonly.ts => readonly/index.ts} | 20 +++---- .../readonly}/readonly.test.ts | 4 +- src/types/{record.ts => record/index.ts} | 16 +++--- .../record}/record.test.ts | 4 +- src/types/{set.ts => set/index.ts} | 14 ++--- src/types/{string.ts => string/index.ts} | 15 ++++-- .../string}/string.test.ts | 2 +- src/types/{symbol.ts => symbol/index.ts} | 13 +++-- .../index.ts} | 49 +++++++++-------- .../templateLiteral/templateLiteral.test.ts} | 4 +- .../{transformer.ts => transformer/index.ts} | 12 +++-- .../transformer}/transformer.test.ts | 4 +- src/types/{tuple.ts => tuple/index.ts} | 12 +++-- src/{__tests__ => types/tuple}/tuple.test.ts | 6 +-- .../{undefined.ts => undefined/index.ts} | 13 +++-- src/types/{union.ts => union/index.ts} | 22 ++++---- .../union/union.test.ts} | 2 +- src/types/{unknown.ts => unknown/index.ts} | 11 ++-- src/types/utils/parseUtil.ts | 2 +- src/types/utils/partialUtil.ts | 41 -------------- src/types/{void.ts => void/index.ts} | 13 +++-- src/{__tests__ => types/void}/void.test.ts | 4 +- src/z.ts | 7 +++ 94 files changed, 500 insertions(+), 452 deletions(-) delete mode 100644 src/__tests__/firstpartyschematypes.test.ts delete mode 100644 src/external.ts rename src/{__tests__ => types/any}/anyunknown.test.ts (89%) rename src/types/{any.ts => any/index.ts} (82%) rename src/{__tests__ => types/array}/array.test.ts (96%) rename src/types/{array.ts => array/index.ts} (94%) rename src/types/{basetype.ts => basetype/index.ts} (99%) rename src/{__tests__ => types/bigint}/bigint.test.ts (98%) rename src/types/{bigint.ts => bigint/index.ts} (90%) rename src/types/{boolean.ts => boolean/index.ts} (81%) rename src/{__tests__ => types/branded}/branded.test.ts (96%) rename src/types/{branded.ts => branded/index.ts} (82%) rename src/{__tests__ => types/catch}/catch.test.ts (99%) rename src/types/{catch.ts => catch/index.ts} (91%) rename src/{__tests__ => types/custom}/custom.test.ts (94%) rename src/types/{custom.ts => custom/index.ts} (91%) rename src/{__tests__ => types/date}/date.test.ts (96%) rename src/types/{date.ts => date/index.ts} (92%) rename src/{__tests__ => types/default}/default.test.ts (98%) rename src/types/{default.ts => default/index.ts} (86%) rename src/{__tests__/firstparty.test.ts => types/defs.test.ts} (76%) rename src/{ => types}/defs.ts (52%) rename src/{__tests__/discriminated-unions.test.ts => types/discriminatedUnion/discriminatedUnion.test.ts} (99%) rename src/types/{discriminatedUnion.ts => discriminatedUnion/index.ts} (86%) rename src/{__tests__ => types/enum}/enum.test.ts (97%) rename src/types/{enum.ts => enum/index.ts} (94%) rename src/{__tests__ => types/error}/all-errors.test.ts (98%) rename src/{__tests__ => types/error}/error.test.ts (99%) rename src/{__tests__ => types/function}/function.test.ts (98%) rename src/types/{function.ts => function/index.ts} (94%) delete mode 100644 src/types/helpers/partialUtil.ts rename src/types/{intersection.ts => intersection/index.ts} (94%) rename src/{__tests__ => types/intersection}/intersection.test.ts (98%) rename src/types/{lazy.ts => lazy/index.ts} (86%) rename src/types/{literal.ts => literal/index.ts} (78%) rename src/{__tests__ => types/literal}/literal.test.ts (96%) rename src/types/{map.ts => map/index.ts} (93%) rename src/{__tests__ => types/map}/map.test.ts (96%) rename src/types/{nan.ts => nan/index.ts} (61%) rename src/{__tests__ => types/nan}/nan.test.ts (94%) rename src/types/{nativeEnum.ts => nativeEnum/index.ts} (91%) rename src/{__tests__ => types/nativeEnum}/nativeEnum.test.ts (96%) rename src/types/{never.ts => never/index.ts} (75%) rename src/types/{null.ts => null/index.ts} (78%) rename src/types/{nullable.ts => nullable/index.ts} (62%) rename src/{__tests__ => types/nullable}/nullable.test.ts (97%) rename src/types/{number.ts => number/index.ts} (96%) rename src/{__tests__ => types/number}/number.test.ts (99%) rename src/types/{object.ts => object/index.ts} (96%) rename src/{__tests__ => types/object}/object-in-es5-env.test.ts (95%) rename src/{__tests__ => types/object}/object.test.ts (99%) rename src/types/{optional.ts => optional/index.ts} (83%) rename src/{__tests__ => types/optional}/optional.test.ts (97%) rename src/types/{pipeline.ts => pipeline/index.ts} (90%) rename src/{__tests__ => types/pipeline}/pipeline.test.ts (95%) rename src/types/{promise.ts => promise/index.ts} (72%) rename src/{__tests__ => types/promise}/promise.test.ts (97%) rename src/types/{readonly.ts => readonly/index.ts} (71%) rename src/{__tests__ => types/readonly}/readonly.test.ts (98%) rename src/types/{record.ts => record/index.ts} (91%) rename src/{__tests__ => types/record}/record.test.ts (98%) rename src/types/{set.ts => set/index.ts} (93%) rename src/types/{string.ts => string/index.ts} (98%) rename src/{__tests__ => types/string}/string.test.ts (99%) rename src/types/{symbol.ts => symbol/index.ts} (78%) rename src/types/{templateLiteral.ts => templateLiteral/index.ts} (93%) rename src/{__tests__/template-literal.test.ts => types/templateLiteral/templateLiteral.test.ts} (99%) rename src/types/{transformer.ts => transformer/index.ts} (96%) rename src/{__tests__ => types/transformer}/transformer.test.ts (98%) rename src/types/{tuple.ts => tuple/index.ts} (94%) rename src/{__tests__ => types/tuple}/tuple.test.ts (95%) rename src/types/{undefined.ts => undefined/index.ts} (79%) rename src/types/{union.ts => union/index.ts} (87%) rename src/{__tests__/unions.test.ts => types/union/union.test.ts} (97%) rename src/types/{unknown.ts => unknown/index.ts} (69%) rename src/types/{void.ts => void/index.ts} (78%) rename src/{__tests__ => types/void}/void.test.ts (80%) diff --git a/playground.ts b/playground.ts index 1bacf6580..8f53fa52f 100644 --- a/playground.ts +++ b/playground.ts @@ -10,3 +10,11 @@ z.array( ); z.coerce.bigint(); + +z.union([z.string(), z.number()]); +z.union([z.string(), z.number()]); +const lit = z + .templateLiteral() + .literal("https://") + .interpolated(z.string()) + .literal(".com"); diff --git a/src/__tests__/base.test.ts b/src/__tests__/base.test.ts index 9c5eeac6b..ea75d84ba 100644 --- a/src/__tests__/base.test.ts +++ b/src/__tests__/base.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; import * as z from "../index"; +import { util } from "../types/utils"; test("type guard", () => { const stringToNumber = z.string().transform((arg) => arg.length); diff --git a/src/__tests__/firstpartyschematypes.test.ts b/src/__tests__/firstpartyschematypes.test.ts deleted file mode 100644 index 56d3f53f6..000000000 --- a/src/__tests__/firstpartyschematypes.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -// @ts-ignore TS6133 -import { test } from "@jest/globals"; - -import { ZodFirstPartySchemaTypes, ZodFirstPartyTypeKind } from ".."; -import { util } from "../helpers/util"; - -test("Identify missing [ZodFirstPartySchemaTypes]", () => { - type ZodFirstPartySchemaForType<T extends ZodFirstPartyTypeKind> = - ZodFirstPartySchemaTypes extends infer Schema - ? Schema extends { _def: { typeName: T } } - ? Schema - : never - : never; - type ZodMappedTypes = { - [key in ZodFirstPartyTypeKind]: ZodFirstPartySchemaForType<key>; - }; - type ZodFirstPartySchemaTypesMissingFromUnion = keyof { - [key in keyof ZodMappedTypes as ZodMappedTypes[key] extends { _def: never } - ? key - : never]: unknown; - }; - - util.assertEqual<ZodFirstPartySchemaTypesMissingFromUnion, never>(true); -}); diff --git a/src/__tests__/generics.test.ts b/src/__tests__/generics.test.ts index a28cc9631..e3196bc69 100644 --- a/src/__tests__/generics.test.ts +++ b/src/__tests__/generics.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; import * as z from "../index"; +import { util } from "../types/utils"; test("generics", () => { async function stripOuter<TData extends z.ZodTypeAny>( diff --git a/src/__tests__/instanceof.test.ts b/src/__tests__/instanceof.test.ts index 4175f487f..05bd5db97 100644 --- a/src/__tests__/instanceof.test.ts +++ b/src/__tests__/instanceof.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; +import { util } from "../types/utils"; import * as z from "../index"; test("instanceof", async () => { diff --git a/src/__tests__/parseUtil.test.ts b/src/__tests__/parseUtil.test.ts index f8a2f0987..c166a75ae 100644 --- a/src/__tests__/parseUtil.test.ts +++ b/src/__tests__/parseUtil.test.ts @@ -6,7 +6,7 @@ import { isDirty, isValid, SyncParseReturnType, -} from "../helpers/parseUtil"; +} from "../types/utils/parseUtil"; test("parseUtil isInvalid should use structural typing", () => { // Test for issue #556: https://github.com/colinhacks/zod/issues/556 diff --git a/src/__tests__/partials.test.ts b/src/__tests__/partials.test.ts index 3186c9f97..e77fe2cf4 100644 --- a/src/__tests__/partials.test.ts +++ b/src/__tests__/partials.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; +import { util } from "../types/utils"; import * as z from "../index"; import { ZodNullable, ZodOptional } from "../index"; diff --git a/src/__tests__/pickomit.test.ts b/src/__tests__/pickomit.test.ts index d1432c85d..0db8c8366 100644 --- a/src/__tests__/pickomit.test.ts +++ b/src/__tests__/pickomit.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; +import { util } from "../types/utils"; import * as z from "../index"; const fish = z.object({ diff --git a/src/__tests__/preprocess.test.ts b/src/__tests__/preprocess.test.ts index 271d293ae..0fa10ca0e 100644 --- a/src/__tests__/preprocess.test.ts +++ b/src/__tests__/preprocess.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; +import { util } from "../types/utils"; import * as z from "../index"; test("preprocess", () => { diff --git a/src/__tests__/primitive.test.ts b/src/__tests__/primitive.test.ts index cd1c4f5fc..925682524 100644 --- a/src/__tests__/primitive.test.ts +++ b/src/__tests__/primitive.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; import * as z from "../index"; +import { util } from "../types/utils"; import { Mocker } from "./Mocker"; const literalStringSchema = z.literal("asdf"); diff --git a/src/__tests__/recursive.test.ts b/src/__tests__/recursive.test.ts index 1c30074d3..59bdfd444 100644 --- a/src/__tests__/recursive.test.ts +++ b/src/__tests__/recursive.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { test } from "@jest/globals"; -import { z } from ".."; +import { z } from "../index"; interface Category { name: string; diff --git a/src/__tests__/refine.test.ts b/src/__tests__/refine.test.ts index 2decb2324..058eae60f 100644 --- a/src/__tests__/refine.test.ts +++ b/src/__tests__/refine.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; +import { util } from "../types/utils"; import * as z from "../index"; import { ZodIssueCode } from "../types/error"; diff --git a/src/__tests__/set.test.ts b/src/__tests__/set.test.ts index 5526a4f3a..a7582a850 100644 --- a/src/__tests__/set.test.ts +++ b/src/__tests__/set.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; +import { util } from "../types/utils"; import * as z from "../index"; import { ZodIssueCode } from "../index"; diff --git a/src/external.ts b/src/external.ts deleted file mode 100644 index c66be1c32..000000000 --- a/src/external.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from "./types"; -export * from "./types/error"; -export * from "./types/utils"; -export * from "./types/utils/parseUtil"; -export * from "./types/utils/typeAliases"; -export * from "./z"; diff --git a/src/index.ts b/src/index.ts index e6a2db629..55841e4c5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,5 @@ -import * as z from "./external"; -export * from "./external"; +import * as z from "./z"; +export * from "./z"; export { z }; + export default z; diff --git a/src/__tests__/anyunknown.test.ts b/src/types/any/anyunknown.test.ts similarity index 89% rename from src/__tests__/anyunknown.test.ts rename to src/types/any/anyunknown.test.ts index 59880f328..e3aa3ba29 100644 --- a/src/__tests__/anyunknown.test.ts +++ b/src/types/any/anyunknown.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import * as z from "../../index"; +import { util } from "../utils"; test("check any inference", () => { const t1 = z.any(); diff --git a/src/types/any.ts b/src/types/any/index.ts similarity index 82% rename from src/types/any.ts rename to src/types/any/index.ts index 8481927bb..1be481a58 100644 --- a/src/types/any.ts +++ b/src/types/any/index.ts @@ -3,9 +3,9 @@ import { ZodFirstPartyTypeKind, ZodType, ZodTypeDef, -} from "./index"; -import { processCreateParams } from "./utils"; -import { OK, ParseInput, ParseReturnType } from "./utils/parseUtil"; +} from "../index"; +import { processCreateParams } from "../utils"; +import { OK, ParseInput, ParseReturnType } from "../utils/parseUtil"; export interface ZodAnyDef extends ZodTypeDef { typeName: ZodFirstPartyTypeKind.ZodAny; diff --git a/src/__tests__/array.test.ts b/src/types/array/array.test.ts similarity index 96% rename from src/__tests__/array.test.ts rename to src/types/array/array.test.ts index 21ae44bee..2864e6cd6 100644 --- a/src/__tests__/array.test.ts +++ b/src/types/array/array.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import * as z from "../../index"; +import { util } from "../utils"; const minTwo = z.string().array().min(2); const maxTwo = z.string().array().max(2); diff --git a/src/types/array.ts b/src/types/array/index.ts similarity index 94% rename from src/types/array.ts rename to src/types/array/index.ts index 83542319a..e98633ec2 100644 --- a/src/types/array.ts +++ b/src/types/array/index.ts @@ -1,19 +1,21 @@ -import { ZodIssueCode } from "./error"; +import { ZodIssueCode } from "../error"; import { ParseInputLazyPath, RawCreateParams, - ZodFirstPartyTypeKind, ZodType, + ZodFirstPartyTypeKind, + ZodType, ZodTypeAny, - ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; -import { errorUtil } from "./utils/errorUtil"; + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; +import { errorUtil } from "../utils/errorUtil"; import { addIssueToContext, INVALID, ParseInput, ParseReturnType, ParseStatus, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodArrayDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { diff --git a/src/types/basetype.ts b/src/types/basetype/index.ts similarity index 99% rename from src/types/basetype.ts rename to src/types/basetype/index.ts index 279281bac..8f759161c 100644 --- a/src/types/basetype.ts +++ b/src/types/basetype/index.ts @@ -31,7 +31,7 @@ import { ZodPromise, ZodReadonly, ZodUnion, -} from "./index"; +} from "../index"; export type RefinementCtx = { addIssue: (arg: IssueData) => void; diff --git a/src/__tests__/bigint.test.ts b/src/types/bigint/bigint.test.ts similarity index 98% rename from src/__tests__/bigint.test.ts rename to src/types/bigint/bigint.test.ts index 1aea6fcdb..1b7e87b60 100644 --- a/src/__tests__/bigint.test.ts +++ b/src/types/bigint/bigint.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; const gtFive = z.bigint().gt(BigInt(5)); const gteFive = z.bigint().gte(BigInt(5)); diff --git a/src/types/bigint.ts b/src/types/bigint/index.ts similarity index 90% rename from src/types/bigint.ts rename to src/types/bigint/index.ts index b292bee99..d7c391bcc 100644 --- a/src/types/bigint.ts +++ b/src/types/bigint/index.ts @@ -5,19 +5,17 @@ import { ParseInput, ParseReturnType, ParseStatus, -} from "../external"; -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, util, ZodParsedType } from "./utils"; -import { errorUtil } from "./utils/errorUtil"; - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodBigInt ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// +} from "../"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, util, ZodParsedType } from "../utils"; +import { errorUtil } from "../utils/errorUtil"; + export type ZodBigIntCheck = | { kind: "min"; value: bigint; inclusive: boolean; message?: string } | { kind: "max"; value: bigint; inclusive: boolean; message?: string } diff --git a/src/types/boolean.ts b/src/types/boolean/index.ts similarity index 81% rename from src/types/boolean.ts rename to src/types/boolean/index.ts index 80a895803..7277a7265 100644 --- a/src/types/boolean.ts +++ b/src/types/boolean/index.ts @@ -1,13 +1,18 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, OK, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodBooleanDef extends ZodTypeDef { typeName: ZodFirstPartyTypeKind.ZodBoolean; diff --git a/src/__tests__/branded.test.ts b/src/types/branded/branded.test.ts similarity index 96% rename from src/__tests__/branded.test.ts rename to src/types/branded/branded.test.ts index d30dfeb83..119ee850c 100644 --- a/src/__tests__/branded.test.ts +++ b/src/types/branded/branded.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import * as z from "../../index"; +import { util } from "../utils"; test("branded types", () => { const mySchema = z diff --git a/src/types/branded.ts b/src/types/branded/index.ts similarity index 82% rename from src/types/branded.ts rename to src/types/branded/index.ts index be8d10236..9f268e83e 100644 --- a/src/types/branded.ts +++ b/src/types/branded/index.ts @@ -1,5 +1,10 @@ -import { ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; -import { ParseInput, ParseReturnType } from "./utils/parseUtil"; +import { + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; +import { ParseInput, ParseReturnType } from "../utils/parseUtil"; export interface ZodBrandedDef<T extends ZodTypeAny> extends ZodTypeDef { type: T; diff --git a/src/__tests__/catch.test.ts b/src/types/catch/catch.test.ts similarity index 99% rename from src/__tests__/catch.test.ts rename to src/types/catch/catch.test.ts index ae0ebe0a4..158288fa5 100644 --- a/src/__tests__/catch.test.ts +++ b/src/types/catch/catch.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { z } from ".."; -import { util } from "../helpers/util"; +import { z } from "../.."; +import { util } from "../utils"; test("basic catch", () => { expect(z.string().catch("default").parse(undefined)).toBe("default"); diff --git a/src/types/catch.ts b/src/types/catch/index.ts similarity index 91% rename from src/types/catch.ts rename to src/types/catch/index.ts index f25cc65f8..fc858077b 100644 --- a/src/types/catch.ts +++ b/src/types/catch/index.ts @@ -1,12 +1,18 @@ -import { ZodError } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; -import { processCreateParams } from "./utils"; +import { ZodError } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; +import { processCreateParams } from "../utils"; import { isAsync, ParseContext, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; ////////////////////////////////////////// ////////////////////////////////////////// diff --git a/src/__tests__/custom.test.ts b/src/types/custom/custom.test.ts similarity index 94% rename from src/__tests__/custom.test.ts rename to src/types/custom/custom.test.ts index 0fb9ca46c..35eed344d 100644 --- a/src/__tests__/custom.test.ts +++ b/src/types/custom/custom.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; test("passing validations", () => { const example1 = z.custom<number>((x) => typeof x === "number"); diff --git a/src/types/custom.ts b/src/types/custom/index.ts similarity index 91% rename from src/types/custom.ts rename to src/types/custom/index.ts index df11c3e9c..34755767f 100644 --- a/src/types/custom.ts +++ b/src/types/custom/index.ts @@ -1,5 +1,5 @@ -import { ZodAny } from "./any"; -import { CustomErrorParams, ZodType } from "./index"; +import { ZodAny } from "../any"; +import { CustomErrorParams, ZodType } from "../index"; export type CustomParams = CustomErrorParams & { fatal?: boolean }; diff --git a/src/__tests__/date.test.ts b/src/types/date/date.test.ts similarity index 96% rename from src/__tests__/date.test.ts rename to src/types/date/date.test.ts index 634d54223..1033b439e 100644 --- a/src/__tests__/date.test.ts +++ b/src/types/date/date.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; const beforeBenchmarkDate = new Date(2022, 10, 4); const benchmarkDate = new Date(2022, 10, 5); diff --git a/src/types/date.ts b/src/types/date/index.ts similarity index 92% rename from src/types/date.ts rename to src/types/date/index.ts index be53e2b5e..2b827e745 100644 --- a/src/types/date.ts +++ b/src/types/date/index.ts @@ -1,7 +1,12 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, util, ZodParsedType } from "./utils"; -import { errorUtil } from "./utils/errorUtil"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, util, ZodParsedType } from "../utils"; +import { errorUtil } from "../utils/errorUtil"; import { addIssueToContext, INVALID, @@ -9,7 +14,7 @@ import { ParseInput, ParseReturnType, ParseStatus, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export type ZodDateCheck = | { kind: "min"; value: number; message?: string } diff --git a/src/__tests__/default.test.ts b/src/types/default/default.test.ts similarity index 98% rename from src/__tests__/default.test.ts rename to src/types/default/default.test.ts index bd03cbd85..c20706e94 100644 --- a/src/__tests__/default.test.ts +++ b/src/types/default/default.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { z } from ".."; -import { util } from "../helpers/util"; +import { z } from "../.."; +import { util } from "../utils"; test("basic defaults", () => { expect(z.string().default("default").parse(undefined)).toBe("default"); diff --git a/src/types/default.ts b/src/types/default/index.ts similarity index 86% rename from src/types/default.ts rename to src/types/default/index.ts index 503610a1b..ca5f35fef 100644 --- a/src/types/default.ts +++ b/src/types/default/index.ts @@ -1,6 +1,12 @@ -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; -import { processCreateParams, util, ZodParsedType } from "./utils"; -import { ParseInput, ParseReturnType } from "./utils/parseUtil"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; +import { processCreateParams, util, ZodParsedType } from "../utils"; +import { ParseInput, ParseReturnType } from "../utils/parseUtil"; //////////////////////////////////////////// //////////////////////////////////////////// diff --git a/src/__tests__/firstparty.test.ts b/src/types/defs.test.ts similarity index 76% rename from src/__tests__/firstparty.test.ts rename to src/types/defs.test.ts index e47601cb0..36359fe29 100644 --- a/src/__tests__/firstparty.test.ts +++ b/src/types/defs.test.ts @@ -1,8 +1,9 @@ // @ts-ignore TS6133 import { test } from "@jest/globals"; -import { util } from "../helpers/util"; +import { ZodFirstPartySchemaTypes, ZodFirstPartyTypeKind } from ".."; import * as z from "../index"; +import { util } from "./utils"; test("first party switch", () => { const myType = z.string() as z.ZodFirstPartySchemaTypes; @@ -87,3 +88,22 @@ test("first party switch", () => { util.assertNever(def); } }); + +test("Identify missing [ZodFirstPartySchemaTypes]", () => { + type ZodFirstPartySchemaForType<T extends ZodFirstPartyTypeKind> = + ZodFirstPartySchemaTypes extends infer Schema + ? Schema extends { _def: { typeName: T } } + ? Schema + : never + : never; + type ZodMappedTypes = { + [key in ZodFirstPartyTypeKind]: ZodFirstPartySchemaForType<key>; + }; + type ZodFirstPartySchemaTypesMissingFromUnion = keyof { + [key in keyof ZodMappedTypes as ZodMappedTypes[key] extends { _def: never } + ? key + : never]: unknown; + }; + + util.assertEqual<ZodFirstPartySchemaTypesMissingFromUnion, never>(true); +}); diff --git a/src/defs.ts b/src/types/defs.ts similarity index 52% rename from src/defs.ts rename to src/types/defs.ts index d10b8f09f..b46222011 100644 --- a/src/defs.ts +++ b/src/types/defs.ts @@ -1,30 +1,30 @@ -import type { ZodAnyDef } from "./types/any"; -import type { ZodArrayDef } from "./types/array"; -import type { ZodBigIntDef } from "./types/bigint"; -import type { ZodBooleanDef } from "./types/boolean"; -import type { ZodDateDef } from "./types/date"; -import type { ZodEnumDef } from "./types/enum"; -import type { ZodFunctionDef } from "./types/function"; -import type { ZodIntersectionDef } from "./types/intersection"; -import type { ZodLazyDef } from "./types/lazy"; -import type { ZodLiteralDef } from "./types/literal"; -import type { ZodMapDef } from "./types/map"; -import type { ZodNativeEnumDef } from "./types/nativeEnum"; -import type { ZodNeverDef } from "./types/never"; -import type { ZodNullDef } from "./types/null"; -import type { ZodNullableDef } from "./types/nullable"; -import type { ZodNumberDef } from "./types/number"; -import type { ZodObjectDef } from "./types/object"; -import type { ZodOptionalDef } from "./types/optional"; -import type { ZodPromiseDef } from "./types/promise"; -import type { ZodRecordDef } from "./types/record"; -import type { ZodStringDef } from "./types/string"; -import type { ZodEffectsDef as ZodTransformerDef } from "./types/transformer"; -import type { ZodTupleDef } from "./types/tuple"; -import type { ZodUndefinedDef } from "./types/undefined"; -import type { ZodUnionDef } from "./types/union"; -import type { ZodUnknownDef } from "./types/unknown"; -import type { ZodVoidDef } from "./types/void"; +import type { ZodAnyDef } from "./any"; +import type { ZodArrayDef } from "./array"; +import type { ZodBigIntDef } from "./bigint"; +import type { ZodBooleanDef } from "./boolean"; +import type { ZodDateDef } from "./date"; +import type { ZodEnumDef } from "./enum"; +import type { ZodFunctionDef } from "./function"; +import type { ZodIntersectionDef } from "./intersection"; +import type { ZodLazyDef } from "./lazy"; +import type { ZodLiteralDef } from "./literal"; +import type { ZodMapDef } from "./map"; +import type { ZodNativeEnumDef } from "./nativeEnum"; +import type { ZodNeverDef } from "./never"; +import type { ZodNullDef } from "./null"; +import type { ZodNullableDef } from "./nullable"; +import type { ZodNumberDef } from "./number"; +import type { ZodObjectDef } from "./object"; +import type { ZodOptionalDef } from "./optional"; +import type { ZodPromiseDef } from "./promise"; +import type { ZodRecordDef } from "./record"; +import type { ZodStringDef } from "./string"; +import type { ZodEffectsDef as ZodTransformerDef } from "./transformer"; +import type { ZodTupleDef } from "./tuple"; +import type { ZodUndefinedDef } from "./undefined"; +import type { ZodUnionDef } from "./union"; +import type { ZodUnknownDef } from "./unknown"; +import type { ZodVoidDef } from "./void"; export type ZodDef = | ZodStringDef diff --git a/src/__tests__/discriminated-unions.test.ts b/src/types/discriminatedUnion/discriminatedUnion.test.ts similarity index 99% rename from src/__tests__/discriminated-unions.test.ts rename to src/types/discriminatedUnion/discriminatedUnion.test.ts index 9d8e7b6ce..ea880b981 100644 --- a/src/__tests__/discriminated-unions.test.ts +++ b/src/types/discriminatedUnion/discriminatedUnion.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; test("valid", () => { expect( diff --git a/src/types/discriminatedUnion.ts b/src/types/discriminatedUnion/index.ts similarity index 86% rename from src/types/discriminatedUnion.ts rename to src/types/discriminatedUnion/index.ts index e84771ff7..a4886fae3 100644 --- a/src/types/discriminatedUnion.ts +++ b/src/types/discriminatedUnion/index.ts @@ -1,34 +1,36 @@ -import { ZodBranded } from "./branded"; -import { ZodCatch } from "./catch"; -import { ZodDefault } from "./default"; -import { ZodEnum } from "./enum"; -import { ZodIssueCode } from "./error"; +import { ZodBranded } from "../branded"; +import { ZodCatch } from "../catch"; +import { ZodDefault } from "../default"; +import { ZodEnum } from "../enum"; +import { ZodIssueCode } from "../error"; import { input, output, RawCreateParams, - ZodFirstPartyTypeKind, ZodRawShape, + ZodFirstPartyTypeKind, + ZodRawShape, ZodType, ZodTypeAny, - ZodTypeDef } from "./index"; -import { ZodLazy } from "./lazy"; -import { ZodLiteral } from "./literal"; -import { ZodNativeEnum } from "./nativeEnum"; -import { ZodNull } from "./null"; -import { ZodNullable } from "./nullable"; -import { UnknownKeysParam, ZodObject } from "./object"; -import { ZodOptional } from "./optional"; -import { ZodReadonly } from "./readonly"; -import { ZodEffects } from "./transformer"; -import { ZodUndefined } from "./undefined"; -import { processCreateParams, util, ZodParsedType } from "./utils"; + ZodTypeDef, +} from "../index"; +import { ZodLazy } from "../lazy"; +import { ZodLiteral } from "../literal"; +import { ZodNativeEnum } from "../nativeEnum"; +import { ZodNull } from "../null"; +import { ZodNullable } from "../nullable"; +import { UnknownKeysParam, ZodObject } from "../object"; +import { ZodOptional } from "../optional"; +import { ZodReadonly } from "../readonly"; +import { ZodEffects } from "../transformer"; +import { ZodUndefined } from "../undefined"; +import { processCreateParams, util, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; -import { Primitive } from "./utils/typeAliases"; +} from "../utils/parseUtil"; +import { Primitive } from "../utils/typeAliases"; ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// diff --git a/src/__tests__/enum.test.ts b/src/types/enum/enum.test.ts similarity index 97% rename from src/__tests__/enum.test.ts rename to src/types/enum/enum.test.ts index e529e9ce4..3cea67920 100644 --- a/src/__tests__/enum.test.ts +++ b/src/types/enum/enum.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import { util } from "../utils"; +import * as z from "../../index"; test("create enum", () => { const MyEnum = z.enum(["Red", "Green", "Blue"]); diff --git a/src/types/enum.ts b/src/types/enum/index.ts similarity index 94% rename from src/types/enum.ts rename to src/types/enum/index.ts index 29537711b..6fa2178f9 100644 --- a/src/types/enum.ts +++ b/src/types/enum/index.ts @@ -1,13 +1,18 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, util } from "./utils"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, util } from "../utils"; import { addIssueToContext, INVALID, OK, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; /////////////////////////////////////// /////////////////////////////////////// diff --git a/src/__tests__/all-errors.test.ts b/src/types/error/all-errors.test.ts similarity index 98% rename from src/__tests__/all-errors.test.ts rename to src/types/error/all-errors.test.ts index 7b5999b42..0e9032ce1 100644 --- a/src/__tests__/all-errors.test.ts +++ b/src/types/error/all-errors.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import * as z from "../../index"; +import { util } from "../utils"; const Test = z.object({ f1: z.number(), diff --git a/src/__tests__/error.test.ts b/src/types/error/error.test.ts similarity index 99% rename from src/__tests__/error.test.ts rename to src/types/error/error.test.ts index 29cf4cf84..a20b1fbff 100644 --- a/src/__tests__/error.test.ts +++ b/src/types/error/error.test.ts @@ -1,9 +1,8 @@ -// @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { ZodParsedType } from "../helpers/util"; -import * as z from "../index"; -import { ZodError, ZodIssueCode } from "../types/error"; +import * as z from "../../index"; +import { ZodParsedType } from "../../index"; +import { ZodError, ZodIssueCode } from "."; test("error creation", () => { const err1 = ZodError.create([]); diff --git a/src/__tests__/function.test.ts b/src/types/function/function.test.ts similarity index 98% rename from src/__tests__/function.test.ts rename to src/types/function/function.test.ts index 1c23cb9c5..141365bfa 100644 --- a/src/__tests__/function.test.ts +++ b/src/types/function/function.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import * as z from "../../index"; +import { util } from "../utils"; const args1 = z.tuple([z.string()]); const returns1 = z.number(); diff --git a/src/types/function.ts b/src/types/function/index.ts similarity index 94% rename from src/types/function.ts rename to src/types/function/index.ts index f64efafef..998699257 100644 --- a/src/types/function.ts +++ b/src/types/function/index.ts @@ -5,12 +5,18 @@ import { ZodErrorMap, ZodIssue, ZodIssueCode, -} from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; -import { ZodPromise } from "./promise"; -import { AnyZodTuple, ZodTuple } from "./tuple"; -import { ZodUnknown } from "./unknown"; -import { processCreateParams, ZodParsedType } from "./utils"; +} from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; +import { ZodPromise } from "../promise"; +import { AnyZodTuple, ZodTuple } from "../tuple"; +import { ZodUnknown } from "../unknown"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, @@ -18,7 +24,7 @@ import { OK, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodFunctionDef< Args extends ZodTuple<any, any> = ZodTuple<any, any>, diff --git a/src/types/helpers/partialUtil.ts b/src/types/helpers/partialUtil.ts deleted file mode 100644 index 3789664a4..000000000 --- a/src/types/helpers/partialUtil.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { ZodArray } from "../array"; -import { ZodRawShape, ZodTypeAny } from "../index"; -import { ZodNullable } from "../nullable"; -import { ZodObject } from "../object"; -import { ZodOptional } from "../optional"; -import { ZodTuple, ZodTupleItems } from "../tuple"; - -export namespace partialUtil { - export type DeepPartial<T extends ZodTypeAny> = - T extends ZodObject<ZodRawShape> - ? ZodObject< - { [k in keyof T["shape"]]: ZodOptional<DeepPartial<T["shape"][k]>> }, - T["_def"]["unknownKeys"], - T["_def"]["catchall"] - > - : T extends ZodArray<infer Type, infer Card> - ? ZodArray<DeepPartial<Type>, Card> - : T extends ZodOptional<infer Type> - ? ZodOptional<DeepPartial<Type>> - : T extends ZodNullable<infer Type> - ? ZodNullable<DeepPartial<Type>> - : T extends ZodTuple<infer Items> - ? { - [k in keyof Items]: Items[k] extends ZodTypeAny - ? DeepPartial<Items[k]> - : never; - } extends infer PI - ? PI extends ZodTupleItems - ? ZodTuple<PI> - : never - : never - : T; -} diff --git a/src/types/index.ts b/src/types/index.ts index e2a3bbf46..ebefbc0d4 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -11,7 +11,7 @@ export * from "./utils/parseUtil"; export * from "./utils/partialUtil"; export * from "./utils/typeAliases"; export * from "./basetype"; -export * from "../defs"; +export * from "./defs"; export * from "./any"; export * from "./array"; export * from "./bigint"; diff --git a/src/types/intersection.ts b/src/types/intersection/index.ts similarity index 94% rename from src/types/intersection.ts rename to src/types/intersection/index.ts index 696e7005d..a58ebf98f 100644 --- a/src/types/intersection.ts +++ b/src/types/intersection/index.ts @@ -1,11 +1,17 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; import { getParsedType, processCreateParams, util, ZodParsedType, -} from "./utils"; +} from "../utils"; import { addIssueToContext, INVALID, @@ -14,7 +20,7 @@ import { ParseInput, ParseReturnType, SyncParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodIntersectionDef< T extends ZodTypeAny = ZodTypeAny, diff --git a/src/__tests__/intersection.test.ts b/src/types/intersection/intersection.test.ts similarity index 98% rename from src/__tests__/intersection.test.ts rename to src/types/intersection/intersection.test.ts index de9255d80..edc286245 100644 --- a/src/__tests__/intersection.test.ts +++ b/src/types/intersection/intersection.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; test("object intersection", () => { const BaseTeacher = z.object({ diff --git a/src/types/lazy.ts b/src/types/lazy/index.ts similarity index 86% rename from src/types/lazy.ts rename to src/types/lazy/index.ts index abe7d7371..4e2c80b2d 100644 --- a/src/types/lazy.ts +++ b/src/types/lazy/index.ts @@ -2,11 +2,13 @@ import { input, output, RawCreateParams, - ZodFirstPartyTypeKind, ZodType, + ZodFirstPartyTypeKind, + ZodType, ZodTypeAny, - ZodTypeDef } from "./index"; -import { processCreateParams } from "./utils"; -import { ParseInput, ParseReturnType } from "./utils/parseUtil"; + ZodTypeDef, +} from "../index"; +import { processCreateParams } from "../utils"; +import { ParseInput, ParseReturnType } from "../utils/parseUtil"; /////////////////////////////////////// /////////////////////////////////////// diff --git a/src/types/literal.ts b/src/types/literal/index.ts similarity index 78% rename from src/types/literal.ts rename to src/types/literal/index.ts index 79328d1df..7ef69d12b 100644 --- a/src/types/literal.ts +++ b/src/types/literal/index.ts @@ -1,13 +1,18 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams } from "./utils"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams } from "../utils"; import { addIssueToContext, INVALID, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; -import { Primitive } from "./utils/typeAliases"; +} from "../utils/parseUtil"; +import { Primitive } from "../utils/typeAliases"; export interface ZodLiteralDef<T = any> extends ZodTypeDef { value: T; diff --git a/src/__tests__/literal.test.ts b/src/types/literal/literal.test.ts similarity index 96% rename from src/__tests__/literal.test.ts rename to src/types/literal/literal.test.ts index 140f728e6..ba3f477ec 100644 --- a/src/__tests__/literal.test.ts +++ b/src/types/literal/literal.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; const literalTuna = z.literal("tuna"); const literalFortyTwo = z.literal(42); diff --git a/src/types/map.ts b/src/types/map/index.ts similarity index 93% rename from src/types/map.ts rename to src/types/map/index.ts index ea11690ca..9be4e534d 100644 --- a/src/types/map.ts +++ b/src/types/map/index.ts @@ -1,18 +1,20 @@ -import { ZodIssueCode } from "./error"; +import { ZodIssueCode } from "../error"; import { ParseInputLazyPath, RawCreateParams, - ZodFirstPartyTypeKind, ZodType, + ZodFirstPartyTypeKind, + ZodType, ZodTypeAny, - ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, ParseInput, ParseReturnType, SyncParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodMapDef< Key extends ZodTypeAny = ZodTypeAny, diff --git a/src/__tests__/map.test.ts b/src/types/map/map.test.ts similarity index 96% rename from src/__tests__/map.test.ts rename to src/types/map/map.test.ts index 08405db3d..6ec92a01d 100644 --- a/src/__tests__/map.test.ts +++ b/src/types/map/map.test.ts @@ -1,9 +1,9 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; -import { ZodIssueCode } from "../index"; +import { util } from "../utils"; +import * as z from "../../index"; +import { ZodIssueCode } from "../../index"; const stringMap = z.map(z.string(), z.string()); type stringMap = z.infer<typeof stringMap>; diff --git a/src/types/nan.ts b/src/types/nan/index.ts similarity index 61% rename from src/types/nan.ts rename to src/types/nan/index.ts index 911896d48..221388f29 100644 --- a/src/types/nan.ts +++ b/src/types/nan/index.ts @@ -1,20 +1,17 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; - -///////////////////////////////////////// -///////////////////////////////////////// -////////// ////////// -////////// ZodNaN ////////// -////////// ////////// -///////////////////////////////////////// -///////////////////////////////////////// +} from "../utils/parseUtil"; export interface ZodNaNDef extends ZodTypeDef { typeName: ZodFirstPartyTypeKind.ZodNaN; diff --git a/src/__tests__/nan.test.ts b/src/types/nan/nan.test.ts similarity index 94% rename from src/__tests__/nan.test.ts rename to src/types/nan/nan.test.ts index b98d5a628..a23c56ac3 100644 --- a/src/__tests__/nan.test.ts +++ b/src/types/nan/nan.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; const schema = z.nan(); diff --git a/src/types/nativeEnum.ts b/src/types/nativeEnum/index.ts similarity index 91% rename from src/types/nativeEnum.ts rename to src/types/nativeEnum/index.ts index a2bf8eacd..073f841ab 100644 --- a/src/types/nativeEnum.ts +++ b/src/types/nativeEnum/index.ts @@ -1,18 +1,18 @@ -import { ZodIssueCode } from "./error"; +import { ZodIssueCode } from "../error"; import { RawCreateParams, ZodFirstPartyTypeKind, ZodType, ZodTypeDef, -} from "./index"; -import { processCreateParams, util, ZodParsedType } from "./utils"; +} from "../index"; +import { processCreateParams, util, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, OK, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodNativeEnumDef<T extends EnumLike = EnumLike> extends ZodTypeDef { diff --git a/src/__tests__/nativeEnum.test.ts b/src/types/nativeEnum/nativeEnum.test.ts similarity index 96% rename from src/__tests__/nativeEnum.test.ts rename to src/types/nativeEnum/nativeEnum.test.ts index 11b7aff0d..ef3930633 100644 --- a/src/__tests__/nativeEnum.test.ts +++ b/src/types/nativeEnum/nativeEnum.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import { util } from "../utils"; +import * as z from "../../index"; test("nativeEnum test with consts", () => { const Fruits: { Apple: "apple"; Banana: "banana" } = { diff --git a/src/types/never.ts b/src/types/never/index.ts similarity index 75% rename from src/types/never.ts rename to src/types/never/index.ts index ebc582e5d..6503ef465 100644 --- a/src/types/never.ts +++ b/src/types/never/index.ts @@ -1,12 +1,17 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodNeverDef extends ZodTypeDef { typeName: ZodFirstPartyTypeKind.ZodNever; diff --git a/src/types/null.ts b/src/types/null/index.ts similarity index 78% rename from src/types/null.ts rename to src/types/null/index.ts index 2617b721d..3d65ee97f 100644 --- a/src/types/null.ts +++ b/src/types/null/index.ts @@ -1,13 +1,18 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, OK, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodNullDef extends ZodTypeDef { typeName: ZodFirstPartyTypeKind.ZodNull; diff --git a/src/types/nullable.ts b/src/types/nullable/index.ts similarity index 62% rename from src/types/nullable.ts rename to src/types/nullable/index.ts index 0264b2617..79087992a 100644 --- a/src/types/nullable.ts +++ b/src/types/nullable/index.ts @@ -1,14 +1,12 @@ -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; -import { OK, ParseInput, ParseReturnType } from "./utils/parseUtil"; - -/////////////////////////////////////////// -/////////////////////////////////////////// -////////// ////////// -////////// ZodNullable ////////// -////////// ////////// -/////////////////////////////////////////// -/////////////////////////////////////////// +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; +import { OK, ParseInput, ParseReturnType } from "../utils/parseUtil"; export interface ZodNullableDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { diff --git a/src/__tests__/nullable.test.ts b/src/types/nullable/nullable.test.ts similarity index 97% rename from src/__tests__/nullable.test.ts rename to src/types/nullable/nullable.test.ts index e57f6079b..cd6779fcd 100644 --- a/src/__tests__/nullable.test.ts +++ b/src/types/nullable/nullable.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; function checkErrors(a: z.ZodTypeAny, bad: any) { let expected; diff --git a/src/types/number.ts b/src/types/number/index.ts similarity index 96% rename from src/types/number.ts rename to src/types/number/index.ts index 4a75eb169..526f78dae 100644 --- a/src/types/number.ts +++ b/src/types/number/index.ts @@ -1,7 +1,12 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, util, ZodParsedType } from "./utils"; -import { errorUtil } from "./utils/errorUtil"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, util, ZodParsedType } from "../utils"; +import { errorUtil } from "../utils/errorUtil"; import { addIssueToContext, INVALID, @@ -9,7 +14,7 @@ import { ParseInput, ParseReturnType, ParseStatus, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export type ZodNumberCheck = | { kind: "min"; value: number; inclusive: boolean; message?: string } diff --git a/src/__tests__/number.test.ts b/src/types/number/number.test.ts similarity index 99% rename from src/__tests__/number.test.ts rename to src/types/number/number.test.ts index 4b95f5c93..5a0e84f75 100644 --- a/src/__tests__/number.test.ts +++ b/src/types/number/number.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; const gtFive = z.number().gt(5); const gteFive = z.number().gte(5); diff --git a/src/types/object.ts b/src/types/object/index.ts similarity index 96% rename from src/types/object.ts rename to src/types/object/index.ts index 62c327ad4..206e6fa95 100644 --- a/src/types/object.ts +++ b/src/types/object/index.ts @@ -8,24 +8,26 @@ import { util, ZodIssueCode, ZodParsedType, -} from "../external"; -import { ZodArray } from "./array"; -import { createZodEnum, ZodEnum } from "./enum"; +} from "../"; +import { ZodArray } from "../array"; +import { createZodEnum, ZodEnum } from "../enum"; import { ParseInputLazyPath, RawCreateParams, - ZodFirstPartyTypeKind, ZodRawShape, + ZodFirstPartyTypeKind, + ZodRawShape, ZodType, ZodTypeAny, - ZodTypeDef } from "./index"; -import { ZodNever } from "./never"; -import { ZodNullable } from "./nullable"; -import { ZodOptional } from "./optional"; -import { ZodTuple } from "./tuple"; -import { processCreateParams } from "./utils"; -import { enumUtil } from "./utils/enumUtil"; -import { errorUtil } from "./utils/errorUtil"; -import { partialUtil } from "./utils/partialUtil"; + ZodTypeDef, +} from "../index"; +import { ZodNever } from "../never"; +import { ZodNullable } from "../nullable"; +import { ZodOptional } from "../optional"; +import { ZodTuple } from "../tuple"; +import { processCreateParams } from "../utils"; +import { enumUtil } from "../utils/enumUtil"; +import { errorUtil } from "../utils/errorUtil"; +import { partialUtil } from "../utils/partialUtil"; export type UnknownKeysParam = "passthrough" | "strict" | "strip"; diff --git a/src/__tests__/object-in-es5-env.test.ts b/src/types/object/object-in-es5-env.test.ts similarity index 95% rename from src/__tests__/object-in-es5-env.test.ts rename to src/types/object/object-in-es5-env.test.ts index 6d17a0964..fa10d1847 100644 --- a/src/__tests__/object-in-es5-env.test.ts +++ b/src/types/object/object-in-es5-env.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; const RealSet = Set; const RealMap = Map; diff --git a/src/__tests__/object.test.ts b/src/types/object/object.test.ts similarity index 99% rename from src/__tests__/object.test.ts rename to src/types/object/object.test.ts index 879351f83..65ec92ca2 100644 --- a/src/__tests__/object.test.ts +++ b/src/types/object/object.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import { util } from "../utils"; +import * as z from "../../index"; const Test = z.object({ f1: z.number(), diff --git a/src/types/optional.ts b/src/types/optional/index.ts similarity index 83% rename from src/types/optional.ts rename to src/types/optional/index.ts index 32215e9b4..c548c4a14 100644 --- a/src/types/optional.ts +++ b/src/types/optional/index.ts @@ -1,6 +1,12 @@ -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; -import { OK, ParseInput, ParseReturnType } from "./utils/parseUtil"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; +import { OK, ParseInput, ParseReturnType } from "../utils/parseUtil"; /////////////////////////////////////////// /////////////////////////////////////////// diff --git a/src/__tests__/optional.test.ts b/src/types/optional/optional.test.ts similarity index 97% rename from src/__tests__/optional.test.ts rename to src/types/optional/optional.test.ts index 4ed86d3aa..ae8805ddd 100644 --- a/src/__tests__/optional.test.ts +++ b/src/types/optional/optional.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; function checkErrors(a: z.ZodTypeAny, bad: any) { let expected; diff --git a/src/types/pipeline.ts b/src/types/pipeline/index.ts similarity index 90% rename from src/types/pipeline.ts rename to src/types/pipeline/index.ts index e49a348dc..39a81f831 100644 --- a/src/types/pipeline.ts +++ b/src/types/pipeline/index.ts @@ -1,5 +1,15 @@ -import { ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; -import { DIRTY, INVALID, ParseInput, ParseReturnType } from "./utils/parseUtil"; +import { + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; +import { + DIRTY, + INVALID, + ParseInput, + ParseReturnType, +} from "../utils/parseUtil"; export interface ZodPipelineDef<A extends ZodTypeAny, B extends ZodTypeAny> extends ZodTypeDef { diff --git a/src/__tests__/pipeline.test.ts b/src/types/pipeline/pipeline.test.ts similarity index 95% rename from src/__tests__/pipeline.test.ts rename to src/types/pipeline/pipeline.test.ts index a977f1ef6..79932de10 100644 --- a/src/__tests__/pipeline.test.ts +++ b/src/types/pipeline/pipeline.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; test("string to number pipeline", () => { const schema = z.string().transform(Number).pipe(z.number()); diff --git a/src/types/promise.ts b/src/types/promise/index.ts similarity index 72% rename from src/types/promise.ts rename to src/types/promise/index.ts index 56bedef6b..588edfda0 100644 --- a/src/types/promise.ts +++ b/src/types/promise/index.ts @@ -1,21 +1,19 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, OK, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; - -////////////////////////////////////////// -////////////////////////////////////////// -////////// ////////// -////////// ZodPromise ////////// -////////// ////////// -////////////////////////////////////////// -////////////////////////////////////////// +} from "../utils/parseUtil"; export interface ZodPromiseDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { diff --git a/src/__tests__/promise.test.ts b/src/types/promise/promise.test.ts similarity index 97% rename from src/__tests__/promise.test.ts rename to src/types/promise/promise.test.ts index e0c9d3cc0..59673fa06 100644 --- a/src/__tests__/promise.test.ts +++ b/src/types/promise/promise.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import { util } from "../utils"; +import * as z from "../../index"; const promSchema = z.promise( z.object({ diff --git a/src/types/readonly.ts b/src/types/readonly/index.ts similarity index 71% rename from src/types/readonly.ts rename to src/types/readonly/index.ts index 023c9aa9b..4cedf9fd0 100644 --- a/src/types/readonly.ts +++ b/src/types/readonly/index.ts @@ -1,14 +1,13 @@ -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; -import { processCreateParams } from "./utils"; -import { isValid, ParseInput, ParseReturnType } from "./utils/parseUtil"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; +import { processCreateParams } from "../utils"; +import { isValid, ParseInput, ParseReturnType } from "../utils/parseUtil"; -/////////////////////////////////////////// -/////////////////////////////////////////// -////////// ////////// -////////// ZodReadonly ////////// -////////// ////////// -/////////////////////////////////////////// -/////////////////////////////////////////// type BuiltIn = | (((...args: any[]) => any) | (new (...args: any[]) => any)) | { readonly [Symbol.toStringTag]: string } @@ -17,6 +16,7 @@ type BuiltIn = | Generator | Promise<unknown> | RegExp; + type MakeReadonly<T> = T extends Map<infer K, infer V> ? ReadonlyMap<K, V> : T extends Set<infer V> diff --git a/src/__tests__/readonly.test.ts b/src/types/readonly/readonly.test.ts similarity index 98% rename from src/__tests__/readonly.test.ts rename to src/types/readonly/readonly.test.ts index 267ff190c..c2afe1c36 100644 --- a/src/__tests__/readonly.test.ts +++ b/src/types/readonly/readonly.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import { util } from "../utils"; +import * as z from "../../index"; enum testEnum { A, diff --git a/src/types/record.ts b/src/types/record/index.ts similarity index 91% rename from src/types/record.ts rename to src/types/record/index.ts index 5bb937841..3c5de28d8 100644 --- a/src/types/record.ts +++ b/src/types/record/index.ts @@ -1,20 +1,22 @@ -import { BRAND } from "./branded"; -import { ZodIssueCode } from "./error"; +import { BRAND } from "../branded"; +import { ZodIssueCode } from "../error"; import { ParseInputLazyPath, RawCreateParams, - ZodFirstPartyTypeKind, ZodType, + ZodFirstPartyTypeKind, + ZodType, ZodTypeAny, - ZodTypeDef } from "./index"; -import { ZodString } from "./string"; -import { processCreateParams, ZodParsedType } from "./utils"; + ZodTypeDef, +} from "../index"; +import { ZodString } from "../string"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, ParseInput, ParseReturnType, ParseStatus, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodRecordDef< Key extends KeySchema = ZodString, diff --git a/src/__tests__/record.test.ts b/src/types/record/record.test.ts similarity index 98% rename from src/__tests__/record.test.ts rename to src/types/record/record.test.ts index 7a773c748..c1cb089b7 100644 --- a/src/__tests__/record.test.ts +++ b/src/types/record/record.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import { util } from "../utils"; +import * as z from "../../index"; const booleanRecord = z.record(z.boolean()); type booleanRecord = z.infer<typeof booleanRecord>; diff --git a/src/types/set.ts b/src/types/set/index.ts similarity index 93% rename from src/types/set.ts rename to src/types/set/index.ts index 23b0bf90f..7741f9e64 100644 --- a/src/types/set.ts +++ b/src/types/set/index.ts @@ -1,19 +1,21 @@ -import { ZodIssueCode } from "./error"; +import { ZodIssueCode } from "../error"; import { ParseInputLazyPath, RawCreateParams, - ZodFirstPartyTypeKind, ZodType, + ZodFirstPartyTypeKind, + ZodType, ZodTypeAny, - ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; -import { errorUtil } from "./utils/errorUtil"; + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; +import { errorUtil } from "../utils/errorUtil"; import { addIssueToContext, INVALID, ParseInput, ParseReturnType, SyncParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodSetDef<Value extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef { diff --git a/src/types/string.ts b/src/types/string/index.ts similarity index 98% rename from src/types/string.ts rename to src/types/string/index.ts index 3ecccfc04..becac6add 100644 --- a/src/types/string.ts +++ b/src/types/string/index.ts @@ -1,7 +1,12 @@ -import { StringValidation, ZodIssueCode } from "../external"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, util, ZodParsedType } from "./utils"; -import { errorUtil } from "./utils/errorUtil"; +import { StringValidation, ZodIssueCode } from "../"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, util, ZodParsedType } from "../utils"; +import { errorUtil } from "../utils/errorUtil"; import { addIssueToContext, INVALID, @@ -9,7 +14,7 @@ import { ParseInput, ParseReturnType, ParseStatus, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export type IpVersion = "v4" | "v6"; export type ZodStringCheck = diff --git a/src/__tests__/string.test.ts b/src/types/string/string.test.ts similarity index 99% rename from src/__tests__/string.test.ts rename to src/types/string/string.test.ts index 43e348b7b..2f4a027fa 100644 --- a/src/__tests__/string.test.ts +++ b/src/types/string/string.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; const minFive = z.string().min(5, "min5"); const maxFive = z.string().max(5, "max5"); diff --git a/src/types/symbol.ts b/src/types/symbol/index.ts similarity index 78% rename from src/types/symbol.ts rename to src/types/symbol/index.ts index d26ec6f9d..9c249d19f 100644 --- a/src/types/symbol.ts +++ b/src/types/symbol/index.ts @@ -1,13 +1,18 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, OK, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodSymbolDef extends ZodTypeDef { typeName: ZodFirstPartyTypeKind.ZodSymbol; diff --git a/src/types/templateLiteral.ts b/src/types/templateLiteral/index.ts similarity index 93% rename from src/types/templateLiteral.ts rename to src/types/templateLiteral/index.ts index 7591ce1fc..1c9f63948 100644 --- a/src/types/templateLiteral.ts +++ b/src/types/templateLiteral/index.ts @@ -1,24 +1,29 @@ -import { ZodAny } from "./any"; -import { ZodBigInt } from "./bigint"; -import { ZodBoolean } from "./boolean"; -import { ZodBranded } from "./branded"; -import { ZodEnum } from "./enum"; +import { ZodAny } from "../any"; +import { ZodBigInt } from "../bigint"; +import { ZodBoolean } from "../boolean"; +import { ZodBranded } from "../branded"; +import { ZodEnum } from "../enum"; import { ZodIssueCode, ZodTemplateLiteralUnsupportedCheckError, ZodTemplateLiteralUnsupportedTypeError, -} from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { ZodLazy } from "./lazy"; -import { ZodLiteral } from "./literal"; -import { ZodNaN } from "./nan"; -import { ZodNativeEnum } from "./nativeEnum"; -import { ZodNever } from "./never"; -import { ZodNull } from "./null"; -import { ZodNullable } from "./nullable"; -import { ZodNumber } from "./number"; -import { ZodOptional } from "./optional"; -import { ZodPipeline } from "./pipeline"; +} from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { ZodLazy } from "../lazy"; +import { ZodLiteral } from "../literal"; +import { ZodNaN } from "../nan"; +import { ZodNativeEnum } from "../nativeEnum"; +import { ZodNever } from "../never"; +import { ZodNull } from "../null"; +import { ZodNullable } from "../nullable"; +import { ZodNumber } from "../number"; +import { ZodOptional } from "../optional"; +import { ZodPipeline } from "../pipeline"; import { cuid2Regex, cuidRegex, @@ -30,16 +35,16 @@ import { uuidRegex, ZodString, ZodStringCheck, -} from "./string"; -import { ZodUndefined } from "./undefined"; -import { ZodUnion } from "./union"; -import { processCreateParams, util, ZodParsedType } from "./utils"; +} from "../string"; +import { ZodUndefined } from "../undefined"; +import { ZodUnion } from "../union"; +import { processCreateParams, util, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; type TemplateLiteralPrimitive = string | number | boolean | null | undefined; type TemplateLiteralInterpolatedPosition = ZodType< diff --git a/src/__tests__/template-literal.test.ts b/src/types/templateLiteral/templateLiteral.test.ts similarity index 99% rename from src/__tests__/template-literal.test.ts rename to src/types/templateLiteral/templateLiteral.test.ts index b45eb1f5f..4ff051653 100644 --- a/src/__tests__/template-literal.test.ts +++ b/src/types/templateLiteral/templateLiteral.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import * as z from "../../index"; +import { util } from "../utils"; const empty = z.templateLiteral(); const hello = z.templateLiteral().literal("hello"); diff --git a/src/types/transformer.ts b/src/types/transformer/index.ts similarity index 96% rename from src/types/transformer.ts rename to src/types/transformer/index.ts index 790379600..f11217c4d 100644 --- a/src/types/transformer.ts +++ b/src/types/transformer/index.ts @@ -1,13 +1,15 @@ -import { IssueData } from "./error"; +import { IssueData } from "../error"; import { input, output, RawCreateParams, RefinementCtx, - ZodFirstPartyTypeKind, ZodType, + ZodFirstPartyTypeKind, + ZodType, ZodTypeAny, - ZodTypeDef } from "./index"; -import { processCreateParams, util } from "./utils"; + ZodTypeDef, +} from "../index"; +import { processCreateParams, util } from "../utils"; import { addIssueToContext, DIRTY, @@ -15,7 +17,7 @@ import { isValid, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export type Refinement<T> = (arg: T, ctx: RefinementCtx) => any; export type SuperRefinement<T> = ( diff --git a/src/__tests__/transformer.test.ts b/src/types/transformer/transformer.test.ts similarity index 98% rename from src/__tests__/transformer.test.ts rename to src/types/transformer/transformer.test.ts index 0f80aa030..62ceb4cfb 100644 --- a/src/__tests__/transformer.test.ts +++ b/src/types/transformer/transformer.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import { util } from "../utils"; +import * as z from "../../index"; const stringToNumber = z.string().transform((arg) => parseFloat(arg)); // const numberToString = z diff --git a/src/types/tuple.ts b/src/types/tuple/index.ts similarity index 94% rename from src/types/tuple.ts rename to src/types/tuple/index.ts index 86fff942f..91a882656 100644 --- a/src/types/tuple.ts +++ b/src/types/tuple/index.ts @@ -1,11 +1,13 @@ -import { ZodIssueCode } from "./error"; +import { ZodIssueCode } from "../error"; import { ParseInputLazyPath, RawCreateParams, - ZodFirstPartyTypeKind, ZodType, + ZodFirstPartyTypeKind, + ZodType, ZodTypeAny, - ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, @@ -13,7 +15,7 @@ import { ParseReturnType, ParseStatus, SyncParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; export type AssertArray<T> = T extends any[] ? T : never; diff --git a/src/__tests__/tuple.test.ts b/src/types/tuple/tuple.test.ts similarity index 95% rename from src/__tests__/tuple.test.ts rename to src/types/tuple/tuple.test.ts index 9363c0928..1aa99d8dc 100644 --- a/src/__tests__/tuple.test.ts +++ b/src/types/tuple/tuple.test.ts @@ -1,9 +1,9 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; -import { ZodError } from "../types/error"; +import { util } from "../utils"; +import * as z from "../../index"; +import { ZodError } from "../error"; const testTuple = z.tuple([ z.string(), diff --git a/src/types/undefined.ts b/src/types/undefined/index.ts similarity index 79% rename from src/types/undefined.ts rename to src/types/undefined/index.ts index a52a1f52e..34f27f7a8 100644 --- a/src/types/undefined.ts +++ b/src/types/undefined/index.ts @@ -1,13 +1,18 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, OK, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodUndefinedDef extends ZodTypeDef { typeName: ZodFirstPartyTypeKind.ZodUndefined; diff --git a/src/types/union.ts b/src/types/union/index.ts similarity index 87% rename from src/types/union.ts rename to src/types/union/index.ts index a14bfeef2..0424e251e 100644 --- a/src/types/union.ts +++ b/src/types/union/index.ts @@ -1,6 +1,12 @@ -import { ZodError, ZodIssue, ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeAny, ZodTypeDef } from "./index"; -import { processCreateParams } from "./utils"; +import { ZodError, ZodIssue, ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeAny, + ZodTypeDef, +} from "../index"; +import { processCreateParams } from "../utils"; import { addIssueToContext, DIRTY, @@ -9,15 +15,7 @@ import { ParseInput, ParseReturnType, SyncParseReturnType, -} from "./utils/parseUtil"; - -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// ZodUnion ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// +} from "../utils/parseUtil"; export type ZodUnionOptions = Readonly<[ZodTypeAny, ...ZodTypeAny[]]>; export interface ZodUnionDef< diff --git a/src/__tests__/unions.test.ts b/src/types/union/union.test.ts similarity index 97% rename from src/__tests__/unions.test.ts rename to src/types/union/union.test.ts index e7b30bcef..174f86791 100644 --- a/src/__tests__/unions.test.ts +++ b/src/types/union/union.test.ts @@ -1,7 +1,7 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import * as z from "../index"; +import * as z from "../../index"; test("function parsing", () => { const schema = z.union([ diff --git a/src/types/unknown.ts b/src/types/unknown/index.ts similarity index 69% rename from src/types/unknown.ts rename to src/types/unknown/index.ts index 78c709736..2cd54ceca 100644 --- a/src/types/unknown.ts +++ b/src/types/unknown/index.ts @@ -1,6 +1,11 @@ -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams } from "./utils"; -import { OK, ParseInput, ParseReturnType } from "./utils/parseUtil"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams } from "../utils"; +import { OK, ParseInput, ParseReturnType } from "../utils/parseUtil"; export interface ZodUnknownDef extends ZodTypeDef { typeName: ZodFirstPartyTypeKind.ZodUnknown; diff --git a/src/types/utils/parseUtil.ts b/src/types/utils/parseUtil.ts index 258b84efa..e733feb22 100644 --- a/src/types/utils/parseUtil.ts +++ b/src/types/utils/parseUtil.ts @@ -1,4 +1,4 @@ -import { defaultErrorMap, getErrorMap } from "../../external"; +import { defaultErrorMap, getErrorMap } from "../"; import { IssueData, ZodErrorMap, ZodIssue } from "../error"; import type { ZodParsedType } from "."; diff --git a/src/types/utils/partialUtil.ts b/src/types/utils/partialUtil.ts index 74c86e08c..3789664a4 100644 --- a/src/types/utils/partialUtil.ts +++ b/src/types/utils/partialUtil.ts @@ -6,31 +6,6 @@ import { ZodOptional } from "../optional"; import { ZodTuple, ZodTupleItems } from "../tuple"; export namespace partialUtil { - // export type DeepPartial<T extends AnyZodObject> = T extends AnyZodObject - // ? ZodObject< - // { [k in keyof T["_shape"]]: InternalDeepPartial<T["_shape"][k]> }, - // T["_unknownKeys"], - // T["_catchall"] - // > - // : T extends ZodArray<infer Type, infer Card> - // ? ZodArray<InternalDeepPartial<Type>, Card> - // : ZodOptional<T>; - - // { - // // optional: T extends ZodOptional<ZodTypeAny> ? T : ZodOptional<T>; - // // array: T extends ZodArray<infer Type> ? ZodArray<DeepPartial<Type>> : never; - // object: T extends AnyZodObject - // ? ZodObject< - // { [k in keyof T["_shape"]]: DeepPartial<T["_shape"][k]> }, - // T["_unknownKeys"], - // T["_catchall"] - // > - // : never; - // rest: ReturnType<T["optional"]>; // ZodOptional<T>; - // }[T extends AnyZodObject - // ? "object" // T extends ZodOptional<any> // ? 'optional' // : - // : "rest"]; - export type DeepPartial<T extends ZodTypeAny> = T extends ZodObject<ZodRawShape> ? ZodObject< @@ -55,20 +30,4 @@ export namespace partialUtil { : never : never : T; - // { - // // optional: T extends ZodOptional<ZodTypeAny> ? T : ZodOptional<T>; - // // array: T extends ZodArray<infer Type> ? ZodArray<DeepPartial<Type>> : never; - // object: T extends ZodObject<infer Shape, infer Params, infer Catchall> - // ? ZodOptional< - // ZodObject< - // { [k in keyof Shape]: DeepPartial<Shape[k]> }, - // Params, - // Catchall - // > - // > - // : never; - // rest: ReturnType<T["optional"]>; - // }[T extends ZodObject<any> - // ? "object" // T extends ZodOptional<any> // ? 'optional' // : - // : "rest"]; } diff --git a/src/types/void.ts b/src/types/void/index.ts similarity index 78% rename from src/types/void.ts rename to src/types/void/index.ts index 3139da61f..651ae4825 100644 --- a/src/types/void.ts +++ b/src/types/void/index.ts @@ -1,13 +1,18 @@ -import { ZodIssueCode } from "./error"; -import { RawCreateParams, ZodFirstPartyTypeKind,ZodType, ZodTypeDef } from "./index"; -import { processCreateParams, ZodParsedType } from "./utils"; +import { ZodIssueCode } from "../error"; +import { + RawCreateParams, + ZodFirstPartyTypeKind, + ZodType, + ZodTypeDef, +} from "../index"; +import { processCreateParams, ZodParsedType } from "../utils"; import { addIssueToContext, INVALID, OK, ParseInput, ParseReturnType, -} from "./utils/parseUtil"; +} from "../utils/parseUtil"; export interface ZodVoidDef extends ZodTypeDef { typeName: ZodFirstPartyTypeKind.ZodVoid; diff --git a/src/__tests__/void.test.ts b/src/types/void/void.test.ts similarity index 80% rename from src/__tests__/void.test.ts rename to src/types/void/void.test.ts index c27ecf86a..55c94925a 100644 --- a/src/__tests__/void.test.ts +++ b/src/types/void/void.test.ts @@ -1,8 +1,8 @@ // @ts-ignore TS6133 import { expect, test } from "@jest/globals"; -import { util } from "../helpers/util"; -import * as z from "../index"; +import * as z from "../../index"; +import { util } from "../utils"; test("void", () => { const v = z.void(); v.parse(undefined); diff --git a/src/z.ts b/src/z.ts index c01dd09f6..7783fbdfa 100644 --- a/src/z.ts +++ b/src/z.ts @@ -203,3 +203,10 @@ export { }; export const NEVER = INVALID as never; + +export * from "./types"; +export * from "./types/error"; +export * from "./types/utils"; +export * from "./types/utils/parseUtil"; +export * from "./types/utils/typeAliases"; +export * from "./z";