This commit is contained in:
2026-10-19 12:16:49 -04:00
parent d7ecab6494
commit 6d3f470922
10446 changed files with 1626249 additions and 2216 deletions
+53
View File
@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.slugify = exports.toUpperCase = exports.toLowerCase = exports.trim = exports.normalize = exports.overwrite = exports.mime = exports.properties = exports.property = exports.endsWith = exports.startsWith = exports.includes = exports.uppercase = exports.lowercase = exports.regex = exports.length = exports.minLength = exports.maxLength = exports.size = exports.minSize = exports.maxSize = exports.multipleOf = exports.nonnegative = exports.nonpositive = exports.negative = exports.positive = exports.gte = exports.gt = exports.lte = exports.lt = void 0;
var index_js_1 = require("../core/index.cjs");
Object.defineProperty(exports, "lt", { enumerable: true, get: function () { return index_js_1._lt; } });
Object.defineProperty(exports, "lte", { enumerable: true, get: function () { return index_js_1._lte; } });
Object.defineProperty(exports, "gt", { enumerable: true, get: function () { return index_js_1._gt; } });
Object.defineProperty(exports, "gte", { enumerable: true, get: function () { return index_js_1._gte; } });
Object.defineProperty(exports, "positive", { enumerable: true, get: function () { return index_js_1._positive; } });
Object.defineProperty(exports, "negative", { enumerable: true, get: function () { return index_js_1._negative; } });
Object.defineProperty(exports, "nonpositive", { enumerable: true, get: function () { return index_js_1._nonpositive; } });
Object.defineProperty(exports, "nonnegative", { enumerable: true, get: function () { return index_js_1._nonnegative; } });
Object.defineProperty(exports, "multipleOf", { enumerable: true, get: function () { return index_js_1._multipleOf; } });
Object.defineProperty(exports, "maxSize", { enumerable: true, get: function () { return index_js_1._maxSize; } });
Object.defineProperty(exports, "minSize", { enumerable: true, get: function () { return index_js_1._minSize; } });
Object.defineProperty(exports, "size", { enumerable: true, get: function () { return index_js_1._size; } });
Object.defineProperty(exports, "maxLength", { enumerable: true, get: function () { return index_js_1._maxLength; } });
Object.defineProperty(exports, "minLength", { enumerable: true, get: function () { return index_js_1._minLength; } });
Object.defineProperty(exports, "length", { enumerable: true, get: function () { return index_js_1._length; } });
Object.defineProperty(exports, "regex", { enumerable: true, get: function () { return index_js_1._regex; } });
Object.defineProperty(exports, "lowercase", { enumerable: true, get: function () { return index_js_1._lowercase; } });
Object.defineProperty(exports, "uppercase", { enumerable: true, get: function () { return index_js_1._uppercase; } });
Object.defineProperty(exports, "includes", { enumerable: true, get: function () { return index_js_1._includes; } });
Object.defineProperty(exports, "startsWith", { enumerable: true, get: function () { return index_js_1._startsWith; } });
Object.defineProperty(exports, "endsWith", { enumerable: true, get: function () { return index_js_1._endsWith; } });
Object.defineProperty(exports, "property", { enumerable: true, get: function () { return index_js_1._property; } });
Object.defineProperty(exports, "properties", { enumerable: true, get: function () { return index_js_1._properties; } });
Object.defineProperty(exports, "mime", { enumerable: true, get: function () { return index_js_1._mime; } });
Object.defineProperty(exports, "overwrite", { enumerable: true, get: function () { return index_js_1._overwrite; } });
Object.defineProperty(exports, "normalize", { enumerable: true, get: function () { return index_js_1._normalize; } });
Object.defineProperty(exports, "trim", { enumerable: true, get: function () { return index_js_1._trim; } });
Object.defineProperty(exports, "toLowerCase", { enumerable: true, get: function () { return index_js_1._toLowerCase; } });
Object.defineProperty(exports, "toUpperCase", { enumerable: true, get: function () { return index_js_1._toUpperCase; } });
Object.defineProperty(exports, "slugify", { enumerable: true, get: function () { return index_js_1._slugify; } });
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+1
View File
@@ -0,0 +1 @@
export { _lt as lt, _lte as lte, _gt as gt, _gte as gte, _positive as positive, _negative as negative, _nonpositive as nonpositive, _nonnegative as nonnegative, _multipleOf as multipleOf, _maxSize as maxSize, _minSize as minSize, _size as size, _maxLength as maxLength, _minLength as minLength, _length as length, _regex as regex, _lowercase as lowercase, _uppercase as uppercase, _includes as includes, _startsWith as startsWith, _endsWith as endsWith, _property as property, _properties as properties, _mime as mime, _overwrite as overwrite, _normalize as normalize, _trim as trim, _toLowerCase as toLowerCase, _toUpperCase as toUpperCase, _slugify as slugify, type $RefinementCtx as RefinementCtx, } from "../core/index.cjs";
+1
View File
@@ -0,0 +1 @@
export { _lt as lt, _lte as lte, _gt as gt, _gte as gte, _positive as positive, _negative as negative, _nonpositive as nonpositive, _nonnegative as nonnegative, _multipleOf as multipleOf, _maxSize as maxSize, _minSize as minSize, _size as size, _maxLength as maxLength, _minLength as minLength, _length as length, _regex as regex, _lowercase as lowercase, _uppercase as uppercase, _includes as includes, _startsWith as startsWith, _endsWith as endsWith, _property as property, _properties as properties, _mime as mime, _overwrite as overwrite, _normalize as normalize, _trim as trim, _toLowerCase as toLowerCase, _toUpperCase as toUpperCase, _slugify as slugify, type $RefinementCtx as RefinementCtx, } from "../core/index.js";
+1
View File
@@ -0,0 +1 @@
export { _lt as lt, _lte as lte, _gt as gt, _gte as gte, _positive as positive, _negative as negative, _nonpositive as nonpositive, _nonnegative as nonnegative, _multipleOf as multipleOf, _maxSize as maxSize, _minSize as minSize, _size as size, _maxLength as maxLength, _minLength as minLength, _length as length, _regex as regex, _lowercase as lowercase, _uppercase as uppercase, _includes as includes, _startsWith as startsWith, _endsWith as endsWith, _property as property, _properties as properties, _mime as mime, _overwrite as overwrite, _normalize as normalize, _trim as trim, _toLowerCase as toLowerCase, _toUpperCase as toUpperCase, _slugify as slugify, } from "../core/index.js";
+66
View File
@@ -0,0 +1,66 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.string = string;
exports.number = number;
exports.boolean = boolean;
exports.bigint = bigint;
exports.date = date;
const core = __importStar(require("../core/index.cjs"));
const schemas = __importStar(require("./schemas.cjs"));
function string(params) {
return core._coercedString(schemas.ZodString, params);
}
function number(params) {
return core._coercedNumber(schemas.ZodNumber, params);
}
function boolean(params) {
return core._coercedBoolean(schemas.ZodBoolean, params);
}
function bigint(params) {
return core._coercedBigint(schemas.ZodBigInt, params);
}
function date(params) {
return core._coercedDate(schemas.ZodDate, params);
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+17
View File
@@ -0,0 +1,17 @@
import * as core from "../core/index.cjs";
import * as schemas from "./schemas.cjs";
export interface ZodCoercedString<T = unknown> extends schemas._ZodString<core.$ZodStringInternals<T>> {
}
export declare function string<T = unknown>(params?: string | core.$ZodStringParams): ZodCoercedString<T>;
export interface ZodCoercedNumber<T = unknown> extends schemas._ZodNumber<core.$ZodNumberInternals<T>> {
}
export declare function number<T = unknown>(params?: string | core.$ZodNumberParams): ZodCoercedNumber<T>;
export interface ZodCoercedBoolean<T = unknown> extends schemas._ZodBoolean<core.$ZodBooleanInternals<T>> {
}
export declare function boolean<T = unknown>(params?: string | core.$ZodBooleanParams): ZodCoercedBoolean<T>;
export interface ZodCoercedBigInt<T = unknown> extends schemas._ZodBigInt<core.$ZodBigIntInternals<T>> {
}
export declare function bigint<T = unknown>(params?: string | core.$ZodBigIntParams): ZodCoercedBigInt<T>;
export interface ZodCoercedDate<T = unknown> extends schemas._ZodDate<core.$ZodDateInternals<T>> {
}
export declare function date<T = unknown>(params?: string | core.$ZodDateParams): ZodCoercedDate<T>;
+17
View File
@@ -0,0 +1,17 @@
import * as core from "../core/index.js";
import * as schemas from "./schemas.js";
export interface ZodCoercedString<T = unknown> extends schemas._ZodString<core.$ZodStringInternals<T>> {
}
export declare function string<T = unknown>(params?: string | core.$ZodStringParams): ZodCoercedString<T>;
export interface ZodCoercedNumber<T = unknown> extends schemas._ZodNumber<core.$ZodNumberInternals<T>> {
}
export declare function number<T = unknown>(params?: string | core.$ZodNumberParams): ZodCoercedNumber<T>;
export interface ZodCoercedBoolean<T = unknown> extends schemas._ZodBoolean<core.$ZodBooleanInternals<T>> {
}
export declare function boolean<T = unknown>(params?: string | core.$ZodBooleanParams): ZodCoercedBoolean<T>;
export interface ZodCoercedBigInt<T = unknown> extends schemas._ZodBigInt<core.$ZodBigIntInternals<T>> {
}
export declare function bigint<T = unknown>(params?: string | core.$ZodBigIntParams): ZodCoercedBigInt<T>;
export interface ZodCoercedDate<T = unknown> extends schemas._ZodDate<core.$ZodDateInternals<T>> {
}
export declare function date<T = unknown>(params?: string | core.$ZodDateParams): ZodCoercedDate<T>;
+17
View File
@@ -0,0 +1,17 @@
import * as core from "../core/index.js";
import * as schemas from "./schemas.js";
export function string(params) {
return core._coercedString(schemas.ZodString, params);
}
export function number(params) {
return core._coercedNumber(schemas.ZodNumber, params);
}
export function boolean(params) {
return core._coercedBoolean(schemas.ZodBoolean, params);
}
export function bigint(params) {
return core._coercedBigint(schemas.ZodBigInt, params);
}
export function date(params) {
return core._coercedDate(schemas.ZodDate, params);
}
+80
View File
@@ -0,0 +1,80 @@
"use strict";
// Zod 3 compat layer
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodFirstPartyTypeKind = exports.config = exports.$brand = exports.ZodIssueCode = void 0;
exports.setErrorMap = setErrorMap;
exports.getErrorMap = getErrorMap;
const core = __importStar(require("../core/index.cjs"));
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
exports.ZodIssueCode = {
invalid_type: "invalid_type",
too_big: "too_big",
too_small: "too_small",
invalid_format: "invalid_format",
not_multiple_of: "not_multiple_of",
unrecognized_keys: "unrecognized_keys",
invalid_union: "invalid_union",
invalid_key: "invalid_key",
invalid_element: "invalid_element",
invalid_value: "invalid_value",
custom: "custom",
};
var index_js_1 = require("../core/index.cjs");
Object.defineProperty(exports, "$brand", { enumerable: true, get: function () { return index_js_1.$brand; } });
Object.defineProperty(exports, "config", { enumerable: true, get: function () { return index_js_1.config; } });
/** @deprecated Use `z.config(params)` instead. */
function setErrorMap(map) {
core.config({
customError: map,
});
}
/** @deprecated Use `z.config()` instead. */
function getErrorMap() {
return core.config().customError;
}
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
var ZodFirstPartyTypeKind;
(function (ZodFirstPartyTypeKind) {
})(ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind = {}));
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+48
View File
@@ -0,0 +1,48 @@
import * as core from "../core/index.cjs";
import type { ZodType } from "./schemas.cjs";
/** @deprecated Use `z.output<T>` instead. */
export type TypeOf<T> = core.output<T>;
/** @deprecated Use `z.output<T>` instead. */
export type Infer<T> = core.output<T>;
/** @deprecated Use `z.core.$ZodTypes` instead */
export type ZodFirstPartySchemaTypes = core.$ZodTypes;
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
export declare const ZodIssueCode: {
readonly invalid_type: "invalid_type";
readonly too_big: "too_big";
readonly too_small: "too_small";
readonly invalid_format: "invalid_format";
readonly not_multiple_of: "not_multiple_of";
readonly unrecognized_keys: "unrecognized_keys";
readonly invalid_union: "invalid_union";
readonly invalid_key: "invalid_key";
readonly invalid_element: "invalid_element";
readonly invalid_value: "invalid_value";
readonly custom: "custom";
};
/** @deprecated Use `z.core.$ZodFlattenedError<z.output<T>>` instead; it takes an inferred type, not a schema. */
export type inferFlattenedErrors<T extends core.$ZodType, U = string> = core.$ZodFlattenedError<core.output<T>, U>;
/** @deprecated Use `z.core.$ZodFormattedError<z.output<T>>` instead; it takes an inferred type, not a schema. */
export type inferFormattedError<T extends core.$ZodType<any, any>, U = string> = core.$ZodFormattedError<core.output<T>, U>;
/** Use `z.$brand` instead */
export type BRAND<T extends string | number | symbol = string | number | symbol> = {
[core.$brand]: {
[k in T]: true;
};
};
export { $brand, config } from "../core/index.cjs";
/** @deprecated Use `z.config(params)` instead. */
export declare function setErrorMap(map: core.$ZodErrorMap): void;
/** @deprecated Use `z.config()` instead. */
export declare function getErrorMap(): core.$ZodErrorMap<core.$ZodIssue> | undefined;
/** @deprecated Use z.ZodType (without generics) instead. */
export type ZodTypeAny<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** @deprecated Use `z.ZodType` */
export type ZodSchema<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** @deprecated Use `z.ZodType` */
export type Schema<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** Included for Zod 3 compatibility */
export type ZodRawShape = core.$ZodShape;
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
export declare enum ZodFirstPartyTypeKind {
}
+48
View File
@@ -0,0 +1,48 @@
import * as core from "../core/index.js";
import type { ZodType } from "./schemas.js";
/** @deprecated Use `z.output<T>` instead. */
export type TypeOf<T> = core.output<T>;
/** @deprecated Use `z.output<T>` instead. */
export type Infer<T> = core.output<T>;
/** @deprecated Use `z.core.$ZodTypes` instead */
export type ZodFirstPartySchemaTypes = core.$ZodTypes;
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
export declare const ZodIssueCode: {
readonly invalid_type: "invalid_type";
readonly too_big: "too_big";
readonly too_small: "too_small";
readonly invalid_format: "invalid_format";
readonly not_multiple_of: "not_multiple_of";
readonly unrecognized_keys: "unrecognized_keys";
readonly invalid_union: "invalid_union";
readonly invalid_key: "invalid_key";
readonly invalid_element: "invalid_element";
readonly invalid_value: "invalid_value";
readonly custom: "custom";
};
/** @deprecated Use `z.core.$ZodFlattenedError<z.output<T>>` instead; it takes an inferred type, not a schema. */
export type inferFlattenedErrors<T extends core.$ZodType, U = string> = core.$ZodFlattenedError<core.output<T>, U>;
/** @deprecated Use `z.core.$ZodFormattedError<z.output<T>>` instead; it takes an inferred type, not a schema. */
export type inferFormattedError<T extends core.$ZodType<any, any>, U = string> = core.$ZodFormattedError<core.output<T>, U>;
/** Use `z.$brand` instead */
export type BRAND<T extends string | number | symbol = string | number | symbol> = {
[core.$brand]: {
[k in T]: true;
};
};
export { $brand, config } from "../core/index.js";
/** @deprecated Use `z.config(params)` instead. */
export declare function setErrorMap(map: core.$ZodErrorMap): void;
/** @deprecated Use `z.config()` instead. */
export declare function getErrorMap(): core.$ZodErrorMap<core.$ZodIssue> | undefined;
/** @deprecated Use z.ZodType (without generics) instead. */
export type ZodTypeAny<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** @deprecated Use `z.ZodType` */
export type ZodSchema<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** @deprecated Use `z.ZodType` */
export type Schema<Output = unknown, Input = unknown, Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> = ZodType<Output, Input, Internals>;
/** Included for Zod 3 compatibility */
export type ZodRawShape = core.$ZodShape;
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
export declare enum ZodFirstPartyTypeKind {
}
+31
View File
@@ -0,0 +1,31 @@
// Zod 3 compat layer
import * as core from "../core/index.js";
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
export const ZodIssueCode = {
invalid_type: "invalid_type",
too_big: "too_big",
too_small: "too_small",
invalid_format: "invalid_format",
not_multiple_of: "not_multiple_of",
unrecognized_keys: "unrecognized_keys",
invalid_union: "invalid_union",
invalid_key: "invalid_key",
invalid_element: "invalid_element",
invalid_value: "invalid_value",
custom: "custom",
};
export { $brand, config } from "../core/index.js";
/** @deprecated Use `z.config(params)` instead. */
export function setErrorMap(map) {
core.config({
customError: map,
});
}
/** @deprecated Use `z.config()` instead. */
export function getErrorMap() {
return core.config().customError;
}
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
export var ZodFirstPartyTypeKind;
(function (ZodFirstPartyTypeKind) {
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
+58
View File
@@ -0,0 +1,58 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deepPartial = deepPartial;
const visit_js_1 = require("../core/visit.cjs");
const schemas = __importStar(require("./schemas.cjs"));
/** Returns a copy of the schema with every nested object's properties made optional. */
function deepPartial(schema) {
return (0, visit_js_1.visit)(schema, {
object: (s) => s.partial(),
// Every partialed option now admits `undefined`, which the constructor rejects as a duplicate.
union: (s) => {
const def = s._zod.def;
return def.discriminator === undefined ? s : schemas.union(def.options);
},
});
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+14
View File
@@ -0,0 +1,14 @@
import type * as core from "../core/index.cjs";
import * as schemas from "./schemas.cjs";
/** Distributes `.partial()` through every object in a schema type, preserving the wrappers around them. */
export type DeepPartial<T extends core.SomeType> = T extends schemas.ZodObject<infer Shape, infer Config> ? schemas.ZodObject<{
-readonly [K in keyof Shape]: schemas.ZodOptional<DeepPartial<Shape[K]>>;
}, Config> : T extends schemas.ZodDiscriminatedUnion<infer Options, any> ? schemas.ZodUnion<{
-readonly [I in keyof Options]: Options[I] extends core.SomeType ? DeepPartial<Options[I]> : Options[I];
}> : T extends schemas.ZodUnion<infer Options> ? schemas.ZodUnion<{
-readonly [I in keyof Options]: Options[I] extends core.SomeType ? DeepPartial<Options[I]> : Options[I];
}> : T extends schemas.ZodArray<infer El> ? schemas.ZodArray<DeepPartial<El>> : T extends schemas.ZodTuple<infer Items, infer Rest> ? schemas.ZodTuple<{
-readonly [K in keyof Items]: Items[K] extends core.SomeType ? DeepPartial<Items[K]> : Items[K];
}, Rest extends core.SomeType ? DeepPartial<Rest> : Rest> : T extends schemas.ZodIntersection<infer A, infer B> ? schemas.ZodIntersection<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodRecord<infer K, infer V> ? schemas.ZodRecord<K, DeepPartial<V>> : T extends schemas.ZodMap<infer K, infer V> ? schemas.ZodMap<K, DeepPartial<V>> : T extends schemas.ZodSet<infer El> ? schemas.ZodSet<DeepPartial<El>> : T extends schemas.ZodOptional<infer Inner> ? schemas.ZodOptional<DeepPartial<Inner>> : T extends schemas.ZodNullable<infer Inner> ? schemas.ZodNullable<DeepPartial<Inner>> : T extends schemas.ZodDefault<infer Inner> ? schemas.ZodDefault<DeepPartial<Inner>> : T extends schemas.ZodPrefault<infer Inner> ? schemas.ZodPrefault<DeepPartial<Inner>> : T extends schemas.ZodNonOptional<infer Inner> ? schemas.ZodNonOptional<DeepPartial<Inner>> : T extends schemas.ZodCatch<infer Inner> ? schemas.ZodCatch<DeepPartial<Inner>> : T extends schemas.ZodReadonly<infer Inner> ? schemas.ZodReadonly<DeepPartial<Inner>> : T extends schemas.ZodSuccess<infer Inner> ? schemas.ZodSuccess<DeepPartial<Inner>> : T extends schemas.ZodPromise<infer Inner> ? schemas.ZodPromise<DeepPartial<Inner>> : T extends schemas.ZodCodec<infer A, infer B> ? schemas.ZodCodec<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodPreprocess<infer B> ? schemas.ZodPreprocess<DeepPartial<B>> : T extends schemas.ZodPipe<infer A, infer B> ? schemas.ZodPipe<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodLazy<infer Inner> ? schemas.ZodLazy<DeepPartial<Inner>> : T;
/** Returns a copy of the schema with every nested object's properties made optional. */
export declare function deepPartial<T extends core.SomeType>(schema: T): DeepPartial<T>;
+14
View File
@@ -0,0 +1,14 @@
import type * as core from "../core/index.js";
import * as schemas from "./schemas.js";
/** Distributes `.partial()` through every object in a schema type, preserving the wrappers around them. */
export type DeepPartial<T extends core.SomeType> = T extends schemas.ZodObject<infer Shape, infer Config> ? schemas.ZodObject<{
-readonly [K in keyof Shape]: schemas.ZodOptional<DeepPartial<Shape[K]>>;
}, Config> : T extends schemas.ZodDiscriminatedUnion<infer Options, any> ? schemas.ZodUnion<{
-readonly [I in keyof Options]: Options[I] extends core.SomeType ? DeepPartial<Options[I]> : Options[I];
}> : T extends schemas.ZodUnion<infer Options> ? schemas.ZodUnion<{
-readonly [I in keyof Options]: Options[I] extends core.SomeType ? DeepPartial<Options[I]> : Options[I];
}> : T extends schemas.ZodArray<infer El> ? schemas.ZodArray<DeepPartial<El>> : T extends schemas.ZodTuple<infer Items, infer Rest> ? schemas.ZodTuple<{
-readonly [K in keyof Items]: Items[K] extends core.SomeType ? DeepPartial<Items[K]> : Items[K];
}, Rest extends core.SomeType ? DeepPartial<Rest> : Rest> : T extends schemas.ZodIntersection<infer A, infer B> ? schemas.ZodIntersection<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodRecord<infer K, infer V> ? schemas.ZodRecord<K, DeepPartial<V>> : T extends schemas.ZodMap<infer K, infer V> ? schemas.ZodMap<K, DeepPartial<V>> : T extends schemas.ZodSet<infer El> ? schemas.ZodSet<DeepPartial<El>> : T extends schemas.ZodOptional<infer Inner> ? schemas.ZodOptional<DeepPartial<Inner>> : T extends schemas.ZodNullable<infer Inner> ? schemas.ZodNullable<DeepPartial<Inner>> : T extends schemas.ZodDefault<infer Inner> ? schemas.ZodDefault<DeepPartial<Inner>> : T extends schemas.ZodPrefault<infer Inner> ? schemas.ZodPrefault<DeepPartial<Inner>> : T extends schemas.ZodNonOptional<infer Inner> ? schemas.ZodNonOptional<DeepPartial<Inner>> : T extends schemas.ZodCatch<infer Inner> ? schemas.ZodCatch<DeepPartial<Inner>> : T extends schemas.ZodReadonly<infer Inner> ? schemas.ZodReadonly<DeepPartial<Inner>> : T extends schemas.ZodSuccess<infer Inner> ? schemas.ZodSuccess<DeepPartial<Inner>> : T extends schemas.ZodPromise<infer Inner> ? schemas.ZodPromise<DeepPartial<Inner>> : T extends schemas.ZodCodec<infer A, infer B> ? schemas.ZodCodec<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodPreprocess<infer B> ? schemas.ZodPreprocess<DeepPartial<B>> : T extends schemas.ZodPipe<infer A, infer B> ? schemas.ZodPipe<DeepPartial<A>, DeepPartial<B>> : T extends schemas.ZodLazy<infer Inner> ? schemas.ZodLazy<DeepPartial<Inner>> : T;
/** Returns a copy of the schema with every nested object's properties made optional. */
export declare function deepPartial<T extends core.SomeType>(schema: T): DeepPartial<T>;
+13
View File
@@ -0,0 +1,13 @@
import { visit } from "../core/visit.js";
import * as schemas from "./schemas.js";
/** Returns a copy of the schema with every nested object's properties made optional. */
export function deepPartial(schema) {
return visit(schema, {
object: (s) => s.partial(),
// Every partialed option now admits `undefined`, which the constructor rejects as a duplicate.
union: (s) => {
const def = s._zod.def;
return def.discriminator === undefined ? s : schemas.union(def.options);
},
});
}
+102
View File
@@ -0,0 +1,102 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodRealError = exports.ZodError = void 0;
const core = __importStar(require("../core/index.cjs"));
const index_js_1 = require("../core/index.cjs");
const util = __importStar(require("../core/util.cjs"));
/* Prototypes that already carry the lazy helper methods. Seeded with the
* intrinsics so that `init` on a foreign object — it accepts any object —
* can never install an accessor onto a prototype we do not own. */
const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
/* Helper methods live as non-enumerable lazy getters on the shared
* prototype instead of own properties on every instance. On first
* access the getter allocates the per-instance closure and caches it
* as a non-enumerable own property, so detached usage still works and
* the allocation only happens for methods actually touched. */
function _lazyMethod(proto, key, make) {
Object.defineProperty(proto, key, {
configurable: true,
enumerable: false,
get() {
const value = make(this);
Object.defineProperty(this, key, { value, configurable: true, writable: true });
return value;
},
set(value) {
Object.defineProperty(this, key, { value, configurable: true, writable: true });
},
});
}
const initializer = (inst, issues) => {
index_js_1.$ZodError.init(inst, issues);
inst.name = "ZodError";
const proto = Object.getPrototypeOf(inst);
if (_installedErrorProtos.has(proto))
return;
_installedErrorProtos.add(proto);
_lazyMethod(proto, "format", (self) => (mapper) => core.formatError(self, mapper));
_lazyMethod(proto, "flatten", (self) => (mapper) => core.flattenError(self, mapper));
_lazyMethod(proto, "addIssue", (self) => (issue) => {
self.issues.push(issue);
self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);
});
_lazyMethod(proto, "addIssues", (self) => (issues) => {
self.issues.push(...issues);
self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);
});
Object.defineProperty(proto, "isEmpty", {
configurable: true,
enumerable: false,
get() {
return this.issues.length === 0;
},
});
};
exports.ZodError = core.$constructor("ZodError", initializer);
exports.ZodRealError = core.$constructor("ZodError", initializer, undefined, {
Parent: Error,
});
// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
// export type ErrorMapCtx = core.$ZodErrorMapCtx;
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+29
View File
@@ -0,0 +1,29 @@
import * as core from "../core/index.cjs";
import { $ZodError } from "../core/index.cjs";
/** @deprecated Use `z.core.$ZodIssue` from `@zod/core` instead, especially if you are building a library on top of Zod. */
export type ZodIssue = core.$ZodIssue;
/** An Error-like class used to store Zod validation issues. */
export interface ZodError<T = unknown> extends $ZodError<T> {
/** @deprecated Use the `z.treeifyError(err)` function instead. */
format(): core.$ZodFormattedError<T>;
format<U>(mapper: (issue: core.$ZodIssue) => U): core.$ZodFormattedError<T, U>;
/** @deprecated Use the `z.treeifyError(err)` function instead. */
flatten(): core.$ZodFlattenedError<T>;
flatten<U>(mapper: (issue: core.$ZodIssue) => U): core.$ZodFlattenedError<T, U>;
/** @deprecated Push directly to `.issues` instead. */
addIssue(issue: core.$ZodIssue): void;
/** @deprecated Push directly to `.issues` instead. */
addIssues(issues: core.$ZodIssue[]): void;
/** @deprecated Check `err.issues.length === 0` instead. */
isEmpty: boolean;
}
export declare const ZodError: core.$constructor<ZodError>;
export declare const ZodRealError: core.$constructor<ZodError>;
/** @deprecated Use `z.core.$ZodFlattenedError` instead. */
export type ZodFlattenedError<T, U = string> = core.$ZodFlattenedError<T, U>;
/** @deprecated Use `z.core.$ZodFormattedError` instead. */
export type ZodFormattedError<T, U = string> = core.$ZodFormattedError<T, U>;
/** @deprecated Use `z.core.$ZodErrorMap` instead. */
export type ZodErrorMap<T extends core.$ZodIssueBase = core.$ZodIssue> = core.$ZodErrorMap<T>;
/** @deprecated Use `z.core.$ZodRawIssue` instead. */
export type IssueData = core.$ZodRawIssue;
+29
View File
@@ -0,0 +1,29 @@
import * as core from "../core/index.js";
import { $ZodError } from "../core/index.js";
/** @deprecated Use `z.core.$ZodIssue` from `@zod/core` instead, especially if you are building a library on top of Zod. */
export type ZodIssue = core.$ZodIssue;
/** An Error-like class used to store Zod validation issues. */
export interface ZodError<T = unknown> extends $ZodError<T> {
/** @deprecated Use the `z.treeifyError(err)` function instead. */
format(): core.$ZodFormattedError<T>;
format<U>(mapper: (issue: core.$ZodIssue) => U): core.$ZodFormattedError<T, U>;
/** @deprecated Use the `z.treeifyError(err)` function instead. */
flatten(): core.$ZodFlattenedError<T>;
flatten<U>(mapper: (issue: core.$ZodIssue) => U): core.$ZodFlattenedError<T, U>;
/** @deprecated Push directly to `.issues` instead. */
addIssue(issue: core.$ZodIssue): void;
/** @deprecated Push directly to `.issues` instead. */
addIssues(issues: core.$ZodIssue[]): void;
/** @deprecated Check `err.issues.length === 0` instead. */
isEmpty: boolean;
}
export declare const ZodError: core.$constructor<ZodError>;
export declare const ZodRealError: core.$constructor<ZodError>;
/** @deprecated Use `z.core.$ZodFlattenedError` instead. */
export type ZodFlattenedError<T, U = string> = core.$ZodFlattenedError<T, U>;
/** @deprecated Use `z.core.$ZodFormattedError` instead. */
export type ZodFormattedError<T, U = string> = core.$ZodFormattedError<T, U>;
/** @deprecated Use `z.core.$ZodErrorMap` instead. */
export type ZodErrorMap<T extends core.$ZodIssueBase = core.$ZodIssue> = core.$ZodErrorMap<T>;
/** @deprecated Use `z.core.$ZodRawIssue` instead. */
export type IssueData = core.$ZodRawIssue;
+57
View File
@@ -0,0 +1,57 @@
import * as core from "../core/index.js";
import { $ZodError } from "../core/index.js";
import * as util from "../core/util.js";
/* Prototypes that already carry the lazy helper methods. Seeded with the
* intrinsics so that `init` on a foreign object — it accepts any object —
* can never install an accessor onto a prototype we do not own. */
const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
/* Helper methods live as non-enumerable lazy getters on the shared
* prototype instead of own properties on every instance. On first
* access the getter allocates the per-instance closure and caches it
* as a non-enumerable own property, so detached usage still works and
* the allocation only happens for methods actually touched. */
function _lazyMethod(proto, key, make) {
Object.defineProperty(proto, key, {
configurable: true,
enumerable: false,
get() {
const value = make(this);
Object.defineProperty(this, key, { value, configurable: true, writable: true });
return value;
},
set(value) {
Object.defineProperty(this, key, { value, configurable: true, writable: true });
},
});
}
const initializer = (inst, issues) => {
$ZodError.init(inst, issues);
inst.name = "ZodError";
const proto = Object.getPrototypeOf(inst);
if (_installedErrorProtos.has(proto))
return;
_installedErrorProtos.add(proto);
_lazyMethod(proto, "format", (self) => (mapper) => core.formatError(self, mapper));
_lazyMethod(proto, "flatten", (self) => (mapper) => core.flattenError(self, mapper));
_lazyMethod(proto, "addIssue", (self) => (issue) => {
self.issues.push(issue);
self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);
});
_lazyMethod(proto, "addIssues", (self) => (issues) => {
self.issues.push(...issues);
self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);
});
Object.defineProperty(proto, "isEmpty", {
configurable: true,
enumerable: false,
get() {
return this.issues.length === 0;
},
});
};
export const ZodError = /*@__PURE__*/ core.$constructor("ZodError", initializer);
export const ZodRealError = /*@__PURE__*/ core.$constructor("ZodError", initializer, undefined, {
Parent: Error,
});
// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
// export type ErrorMapCtx = core.$ZodErrorMapCtx;
+97
View File
@@ -0,0 +1,97 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.coerce = exports.iso = exports.ZodISODuration = exports.ZodISOTime = exports.ZodISODate = exports.ZodISODateTime = exports.locales = exports.output = exports.input = exports.deepPartial = exports.fromJSONSchema = exports.toJSONSchema = exports.getDiscriminatedOption = exports.ZodCompileUnsupportedError = exports.ZodCompileAsyncError = exports.withParser = exports.compile = exports.toZod = exports.INVALID = exports.NEVER = exports.util = exports.TimePrecision = exports.flattenError = exports.formatError = exports.prettifyError = exports.treeifyError = exports.regexes = exports.clone = exports.$brand = exports.$input = exports.$output = exports.memoizer = exports.config = exports.registry = exports.globalRegistry = exports.core = void 0;
exports.core = __importStar(require("../core/index.cjs"));
__exportStar(require("./schemas.cjs"), exports);
__exportStar(require("./checks.cjs"), exports);
__exportStar(require("./errors.cjs"), exports);
__exportStar(require("./parse.cjs"), exports);
__exportStar(require("./compat.cjs"), exports);
var index_js_1 = require("../core/index.cjs");
Object.defineProperty(exports, "globalRegistry", { enumerable: true, get: function () { return index_js_1.globalRegistry; } });
Object.defineProperty(exports, "registry", { enumerable: true, get: function () { return index_js_1.registry; } });
Object.defineProperty(exports, "config", { enumerable: true, get: function () { return index_js_1.config; } });
Object.defineProperty(exports, "memoizer", { enumerable: true, get: function () { return index_js_1.memoizer; } });
Object.defineProperty(exports, "$output", { enumerable: true, get: function () { return index_js_1.$output; } });
Object.defineProperty(exports, "$input", { enumerable: true, get: function () { return index_js_1.$input; } });
Object.defineProperty(exports, "$brand", { enumerable: true, get: function () { return index_js_1.$brand; } });
Object.defineProperty(exports, "clone", { enumerable: true, get: function () { return index_js_1.clone; } });
Object.defineProperty(exports, "regexes", { enumerable: true, get: function () { return index_js_1.regexes; } });
Object.defineProperty(exports, "treeifyError", { enumerable: true, get: function () { return index_js_1.treeifyError; } });
Object.defineProperty(exports, "prettifyError", { enumerable: true, get: function () { return index_js_1.prettifyError; } });
Object.defineProperty(exports, "formatError", { enumerable: true, get: function () { return index_js_1.formatError; } });
Object.defineProperty(exports, "flattenError", { enumerable: true, get: function () { return index_js_1.flattenError; } });
Object.defineProperty(exports, "TimePrecision", { enumerable: true, get: function () { return index_js_1.TimePrecision; } });
Object.defineProperty(exports, "util", { enumerable: true, get: function () { return index_js_1.util; } });
Object.defineProperty(exports, "NEVER", { enumerable: true, get: function () { return index_js_1.NEVER; } });
Object.defineProperty(exports, "INVALID", { enumerable: true, get: function () { return index_js_1.INVALID; } });
Object.defineProperty(exports, "toZod", { enumerable: true, get: function () { return index_js_1.toZod; } });
Object.defineProperty(exports, "compile", { enumerable: true, get: function () { return index_js_1.compile; } });
Object.defineProperty(exports, "withParser", { enumerable: true, get: function () { return index_js_1.withParser; } });
Object.defineProperty(exports, "ZodCompileAsyncError", { enumerable: true, get: function () { return index_js_1.ZodCompileAsyncError; } });
Object.defineProperty(exports, "ZodCompileUnsupportedError", { enumerable: true, get: function () { return index_js_1.ZodCompileUnsupportedError; } });
Object.defineProperty(exports, "getDiscriminatedOption", { enumerable: true, get: function () { return index_js_1.getDiscriminatedOption; } });
var json_schema_processors_js_1 = require("../core/json-schema-processors.cjs");
Object.defineProperty(exports, "toJSONSchema", { enumerable: true, get: function () { return json_schema_processors_js_1.toJSONSchema; } });
var from_json_schema_js_1 = require("./from-json-schema.cjs");
Object.defineProperty(exports, "fromJSONSchema", { enumerable: true, get: function () { return from_json_schema_js_1.fromJSONSchema; } });
var deep_partial_js_1 = require("./deep-partial.cjs");
Object.defineProperty(exports, "deepPartial", { enumerable: true, get: function () { return deep_partial_js_1.deepPartial; } });
// Types and values both, from one module — re-exporting the types from core would collide.
var in_out_js_1 = require("./in-out.cjs");
Object.defineProperty(exports, "input", { enumerable: true, get: function () { return in_out_js_1.input; } });
Object.defineProperty(exports, "output", { enumerable: true, get: function () { return in_out_js_1.output; } });
exports.locales = __importStar(require("../locales/index.cjs"));
// iso must be exported from top-level https://github.com/colinhacks/zod/issues/4491
var iso_js_1 = require("./iso.cjs");
Object.defineProperty(exports, "ZodISODateTime", { enumerable: true, get: function () { return iso_js_1.ZodISODateTime; } });
Object.defineProperty(exports, "ZodISODate", { enumerable: true, get: function () { return iso_js_1.ZodISODate; } });
Object.defineProperty(exports, "ZodISOTime", { enumerable: true, get: function () { return iso_js_1.ZodISOTime; } });
Object.defineProperty(exports, "ZodISODuration", { enumerable: true, get: function () { return iso_js_1.ZodISODuration; } });
exports.iso = __importStar(require("./iso.cjs"));
exports.coerce = __importStar(require("./coerce.cjs"));
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+19
View File
@@ -0,0 +1,19 @@
export * as core from "../core/index.cjs";
export * from "./schemas.cjs";
export * from "./checks.cjs";
export * from "./errors.cjs";
export * from "./parse.cjs";
export * from "./compat.cjs";
export type { infer } from "../core/index.cjs";
export type { JSONType } from "../core/util.cjs";
export type { CompileOptions } from "../core/index.cjs";
export { globalRegistry, type GlobalMeta, registry, config, memoizer, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, INVALID, toZod, compile, withParser, ZodCompileAsyncError, ZodCompileUnsupportedError, getDiscriminatedOption, } from "../core/index.cjs";
export { toJSONSchema } from "../core/json-schema-processors.cjs";
export { fromJSONSchema } from "./from-json-schema.cjs";
export { deepPartial } from "./deep-partial.cjs";
export { input, output } from "./in-out.cjs";
export * as locales from "../locales/index.cjs";
export { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from "./iso.cjs";
export * as iso from "./iso.cjs";
export type { ZodCoercedString, ZodCoercedNumber, ZodCoercedBigInt, ZodCoercedBoolean, ZodCoercedDate, } from "./coerce.cjs";
export * as coerce from "./coerce.cjs";
+19
View File
@@ -0,0 +1,19 @@
export * as core from "../core/index.js";
export * from "./schemas.js";
export * from "./checks.js";
export * from "./errors.js";
export * from "./parse.js";
export * from "./compat.js";
export type { infer } from "../core/index.js";
export type { JSONType } from "../core/util.js";
export type { CompileOptions } from "../core/index.js";
export { globalRegistry, type GlobalMeta, registry, config, memoizer, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, INVALID, toZod, compile, withParser, ZodCompileAsyncError, ZodCompileUnsupportedError, getDiscriminatedOption, } from "../core/index.js";
export { toJSONSchema } from "../core/json-schema-processors.js";
export { fromJSONSchema } from "./from-json-schema.js";
export { deepPartial } from "./deep-partial.js";
export { input, output } from "./in-out.js";
export * as locales from "../locales/index.js";
export { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from "./iso.js";
export * as iso from "./iso.js";
export type { ZodCoercedString, ZodCoercedNumber, ZodCoercedBigInt, ZodCoercedBoolean, ZodCoercedDate, } from "./coerce.js";
export * as coerce from "./coerce.js";
+17
View File
@@ -0,0 +1,17 @@
export * as core from "../core/index.js";
export * from "./schemas.js";
export * from "./checks.js";
export * from "./errors.js";
export * from "./parse.js";
export * from "./compat.js";
export { globalRegistry, registry, config, memoizer, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, INVALID, toZod, compile, withParser, ZodCompileAsyncError, ZodCompileUnsupportedError, getDiscriminatedOption, } from "../core/index.js";
export { toJSONSchema } from "../core/json-schema-processors.js";
export { fromJSONSchema } from "./from-json-schema.js";
export { deepPartial } from "./deep-partial.js";
// Types and values both, from one module — re-exporting the types from core would collide.
export { input, output } from "./in-out.js";
export * as locales from "../locales/index.js";
// iso must be exported from top-level https://github.com/colinhacks/zod/issues/4491
export { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from "./iso.js";
export * as iso from "./iso.js";
export * as coerce from "./coerce.js";
+926
View File
@@ -0,0 +1,926 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromJSONSchema = fromJSONSchema;
const registries_js_1 = require("../core/registries.cjs");
const util_js_1 = require("../core/util.cjs");
const _checks = __importStar(require("./checks.cjs"));
const _iso = __importStar(require("./iso.cjs"));
const _schemas = __importStar(require("./schemas.cjs"));
// Local z object to avoid circular dependency with ../index.js
const z = {
..._schemas,
..._checks,
iso: _iso,
};
// Keys that are recognized and handled by the conversion logic
const RECOGNIZED_KEYS = /*@__PURE__*/ new Set([
// Schema identification
"$schema",
"$ref",
"$defs",
"definitions",
// Core schema keywords
"$id",
"id",
"$comment",
"$anchor",
"$vocabulary",
"$dynamicRef",
"$dynamicAnchor",
// Type
"type",
"enum",
"const",
// Composition
"anyOf",
"oneOf",
"allOf",
"not",
// Object
"properties",
"required",
"additionalProperties",
"patternProperties",
"propertyNames",
"minProperties",
"maxProperties",
// Array
"items",
"prefixItems",
"additionalItems",
"minItems",
"maxItems",
"uniqueItems",
"contains",
"minContains",
"maxContains",
// String
"minLength",
"maxLength",
"pattern",
"format",
// Number
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
// Already handled metadata
"description",
"default",
// Content
"contentEncoding",
"contentMediaType",
"contentSchema",
// Unsupported (error-throwing)
"unevaluatedItems",
"unevaluatedProperties",
"if",
"then",
"else",
"dependentSchemas",
"dependentRequired",
// OpenAPI
"nullable",
"readOnly",
]);
function detectVersion(schema, defaultTarget) {
const $schema = schema.$schema;
if ($schema === "https://json-schema.org/draft/2020-12/schema") {
return "draft-2020-12";
}
if ($schema === "http://json-schema.org/draft-07/schema#") {
return "draft-7";
}
if ($schema === "http://json-schema.org/draft-04/schema#") {
return "draft-4";
}
// Use defaultTarget if provided, otherwise default to draft-2020-12
return defaultTarget ?? "draft-2020-12";
}
// Positional schemas constrain the elements that are present; only minItems makes them required.
function applyMinItems(items, minItems) {
return items.map((item, index) => (index < minItems ? item : item.optional()));
}
// Inverse of the encoding applied to $ref pointer segments in to-json-schema.ts. Per RFC 6901 the `~1` replacement must run before `~0`.
function decodeJSONPointerSegment(segment) {
return segment.replace(/~1/g, "/").replace(/~0/g, "~");
}
function resolveRef(ref, ctx) {
if (!ref.startsWith("#")) {
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
}
const path = ref.slice(1).split("/").filter(Boolean);
// Handle root reference "#"
if (path.length === 0) {
return ctx.rootSchema;
}
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
if (path[0] === defsKey) {
const key = path[1] === undefined ? undefined : decodeJSONPointerSegment(path[1]);
if (!key || !ctx.defs[key]) {
throw new Error(`Reference not found: ${ref}`);
}
return ctx.defs[key];
}
throw new Error(`Reference not found: ${ref}`);
}
/**
* Enforces the keywords that constrain an object's own keys — `propertyNames`,
* `minProperties`, `maxProperties` — before `objectSchema` runs. The guard has
* to see the raw input: an object parse drops `__proto__` and can add keys from
* a property `default`, so its output is not the set of names the instance
* actually carried.
*/
function checkObjectGuards(objectSchema, guards) {
// An identity transform, not z.any(), so `toJSONSchema` reports the object on both the input and the output side of the pipe.
const guard = z
.transform((value) => value)
.check((payload) => {
const value = payload.value;
if (typeof value !== "object" || value === null || Array.isArray(value))
return;
const keys = Object.getOwnPropertyNames(value);
if (guards.minProperties !== undefined && keys.length < guards.minProperties) {
payload.issues.push({
origin: "object",
code: "too_small",
minimum: guards.minProperties,
inclusive: true,
message: `Too small: expected object to have >=${guards.minProperties} properties`,
input: value,
inst: objectSchema,
continue: true,
});
}
if (guards.maxProperties !== undefined && keys.length > guards.maxProperties) {
payload.issues.push({
origin: "object",
code: "too_big",
maximum: guards.maxProperties,
inclusive: true,
message: `Too big: expected object to have <=${guards.maxProperties} properties`,
input: value,
inst: objectSchema,
continue: true,
});
}
if (guards.keySchema) {
for (const key of keys) {
const result = guards.keySchema.safeParse(key);
if (result.success)
continue;
payload.issues.push({
code: "invalid_key",
origin: "record",
issues: result.error.issues,
input: key,
path: [key],
continue: true,
});
}
}
});
return guard.pipe(objectSchema);
}
/**
* An injective string for JSON data: two values share a key exactly when `uniqueItems` calls them
* equal, so duplicate detection is a Map lookup rather than a pairwise walk. Strings and keys are
* length-prefixed so no value can spell another one. `null` means "never equal to anything" — a
* cycle or a NaN, neither of which JSON can express.
*/
function canonicalKey(value, seen) {
if (value === null)
return "z";
const type = typeof value;
if (type !== "object") {
if (type === "number" && Number.isNaN(value))
return null;
const raw = String(value);
return `${type[0]}${raw.length}:${raw}`;
}
if (seen.has(value))
return null;
seen.add(value);
try {
if (Array.isArray(value)) {
const parts = [];
for (const item of value) {
const key = canonicalKey(item, seen);
if (key === null)
return null;
parts.push(key);
}
return `a${parts.length}:[${parts.join(",")}]`;
}
const keys = Object.keys(value).sort();
const parts = [];
for (const k of keys) {
const key = canonicalKey(value[k], seen);
if (key === null)
return null;
parts.push(`${k.length}:${k}=${key}`);
}
return `o${parts.length}:{${parts.join(",")}}`;
}
finally {
seen.delete(value);
}
}
// keywords whose value is a schema or an array of them
const SCHEMA_KEYWORDS = /*@__PURE__*/ new Set([
"items",
"prefixItems",
"additionalItems",
"additionalProperties",
"contains",
"propertyNames",
"not",
"if",
"then",
"else",
"allOf",
"anyOf",
"oneOf",
"unevaluatedItems",
"unevaluatedProperties",
"contentSchema",
]);
// keywords whose value maps names to schemas. draft-7 `dependencies` also allows an array of property names, which holds no schema to walk
const SCHEMA_MAP_KEYWORDS = /*@__PURE__*/ new Set([
"properties",
"patternProperties",
"dependentSchemas",
"dependencies",
"$defs",
"definitions",
]);
/**
* True when a subschema holds a `$ref` anywhere a schema can appear. Only those positions are
* walked: `$ref` under `default` or an `x-` annotation is instance data with an ordinary key, and
* reading it as a reference would drop a constraint that resolves perfectly well.
*/
function containsRef(value) {
if (typeof value !== "object" || value === null)
return false;
if (Array.isArray(value))
return value.some(containsRef);
if (typeof value.$ref === "string")
return true;
return Object.entries(value).some(([key, sub]) => {
if (SCHEMA_KEYWORDS.has(key))
return containsRef(sub);
if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null)
return false;
return Object.values(sub).some(containsRef);
});
}
function plural(n) {
return n === 1 ? "element" : "elements";
}
/**
* Enforces `uniqueItems` and the `contains` family before `arraySchema` runs, for the same reason
* `checkObjectGuards` runs pre-pipe: an item parse can apply a nested `default`, so the parsed
* array is not the instance the keywords are defined over. A guard issue aborts the pipe, so
* `minItems`/`maxItems` are not also reported on the same parse — instance correctness is worth
* more than co-reporting two issues.
*/
function checkArrayGuards(arraySchema, guards) {
// An identity transform, not z.any(), so `toJSONSchema` reports the array on both the input and the output side of the pipe.
const guard = z
.transform((value) => value)
.check((payload) => {
const items = payload.value;
if (!Array.isArray(items))
return;
if (guards.uniqueItems === true) {
const firstSeen = new Map();
for (let i = 0; i < items.length; i++) {
const key = canonicalKey(items[i], new Set());
if (key === null)
continue;
const first = firstSeen.get(key);
if (first === undefined) {
firstSeen.set(key, i);
continue;
}
payload.issues.push({
code: "custom",
message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`,
input: items,
path: [i],
continue: true,
});
}
}
if (guards.containsSchema) {
const minContains = guards.minContains ?? 1;
// one past the ceiling already proves the failure, and nothing above it changes the verdict
const ceiling = guards.maxContains !== undefined ? guards.maxContains + 1 : Number.POSITIVE_INFINITY;
let matches = 0;
for (const item of items) {
if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling)
break;
}
if (matches < minContains) {
// the scan ran to the end, so this count is exact
payload.issues.push({
code: "custom",
message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,
input: items,
continue: true,
});
}
if (guards.maxContains !== undefined && matches > guards.maxContains) {
payload.issues.push({
code: "custom",
message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,
input: items,
continue: true,
});
}
}
});
return guard.pipe(arraySchema);
}
function getTupleRest(restSchema, ctx) {
if (restSchema === false) {
return undefined;
}
if (restSchema === undefined || restSchema === true) {
return z.any();
}
return convertSchema(restSchema, ctx);
}
// the RFC 3339 full-time keyword, narrower than `z.iso.time()`; local because sharing it via `timeSource` pins that builder into every bundle (+139 B gzipped on a mini `z.boolean()`)
const fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
function convertBaseSchema(schema, ctx) {
// Handle unsupported features
if (schema.not !== undefined) {
// Special case: { not: {} } represents never
if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
return z.never();
}
throw new Error("not is not supported in Zod (except { not: {} } for never)");
}
if (schema.unevaluatedItems !== undefined) {
throw new Error("unevaluatedItems is not supported");
}
if (schema.unevaluatedProperties !== undefined) {
throw new Error("unevaluatedProperties is not supported");
}
if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) {
throw new Error("Conditional schemas (if/then/else) are not supported");
}
if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) {
throw new Error("dependentSchemas and dependentRequired are not supported");
}
// Handle $ref
if (schema.$ref) {
const refPath = schema.$ref;
if (ctx.refs.has(refPath)) {
return ctx.refs.get(refPath);
}
if (ctx.processing.has(refPath)) {
// Circular reference - use lazy
return z.lazy(() => {
if (!ctx.refs.has(refPath)) {
throw new Error(`Circular reference not resolved: ${refPath}`);
}
return ctx.refs.get(refPath);
});
}
ctx.processing.add(refPath);
const resolved = resolveRef(refPath, ctx);
const zodSchema = convertSchema(resolved, ctx);
ctx.refs.set(refPath, zodSchema);
ctx.processing.delete(refPath);
return zodSchema;
}
// Handle enum
if (schema.enum !== undefined) {
const enumValues = schema.enum;
// Special case: OpenAPI 3.0 null representation { type: "string", nullable: true, enum: [null] }
if (ctx.version === "openapi-3.0" &&
schema.nullable === true &&
enumValues.length === 1 &&
enumValues[0] === null) {
return z.null();
}
if (enumValues.length === 0) {
return z.never();
}
if (enumValues.length === 1) {
return z.literal(enumValues[0]);
}
// Check if all values are strings
if (enumValues.every((v) => typeof v === "string")) {
return z.enum(enumValues);
}
// Mixed types - use union of literals
const literalSchemas = enumValues.map((v) => z.literal(v));
if (literalSchemas.length < 2) {
return literalSchemas[0];
}
return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
}
// Handle const
if (schema.const !== undefined) {
return z.literal(schema.const);
}
// Handle type
const type = schema.type;
if (Array.isArray(type)) {
// Expand type array into anyOf union
const typeSchemas = type.map((t) => {
const typeSchema = { ...schema, type: t };
return convertBaseSchema(typeSchema, ctx);
});
if (typeSchemas.length === 0) {
return z.never();
}
if (typeSchemas.length === 1) {
return typeSchemas[0];
}
return z.union(typeSchemas);
}
if (!type) {
// No type specified - empty schema (any)
return z.any();
}
let zodSchema;
switch (type) {
case "string": {
let stringSchema = z.string();
// Apply format using .check() with Zod format functions
if (schema.format) {
const format = schema.format;
// Map common formats to Zod check functions
if (format === "email") {
stringSchema = stringSchema.check(z.email());
}
else if (format === "uri" || format === "uri-reference") {
stringSchema = stringSchema.check(z.url());
}
else if (format === "uuid" || format === "guid") {
stringSchema = stringSchema.check(z.uuid());
}
else if (format === "date-time") {
stringSchema = stringSchema.check(z.iso.datetime({ offset: true }));
}
else if (format === "date") {
stringSchema = stringSchema.check(z.iso.date());
}
else if (format === "time") {
stringSchema = stringSchema.check(z.regex(fullTime));
}
else if (format === "duration") {
stringSchema = stringSchema.check(z.iso.duration());
}
else if (format === "hostname") {
stringSchema = stringSchema.check(z.hostname());
}
else if (format === "ipv4") {
stringSchema = stringSchema.check(z.ipv4());
}
else if (format === "ipv6") {
stringSchema = stringSchema.check(z.ipv6());
}
else if (format === "mac") {
stringSchema = stringSchema.check(z.mac());
}
else if (format === "cidr") {
stringSchema = stringSchema.check(z.cidrv4());
}
else if (format === "cidr-v6") {
stringSchema = stringSchema.check(z.cidrv6());
}
else if (format === "base64") {
stringSchema = stringSchema.check(z.base64());
}
else if (format === "base64url") {
stringSchema = stringSchema.check(z.base64url());
}
else if (format === "e164") {
stringSchema = stringSchema.check(z.e164());
}
else if (format === "credit_card") {
stringSchema = stringSchema.check(z.creditCard());
}
else if (format === "iban") {
stringSchema = stringSchema.check(z.iban());
}
else if (format === "jwt") {
stringSchema = stringSchema.check(z.jwt());
}
else if (format === "emoji") {
stringSchema = stringSchema.check(z.emoji());
}
else if (format === "nanoid") {
stringSchema = stringSchema.check(z.nanoid());
}
else if (format === "cuid") {
stringSchema = stringSchema.check(z.cuid());
}
else if (format === "cuid2") {
stringSchema = stringSchema.check(z.cuid2());
}
else if (format === "ulid") {
stringSchema = stringSchema.check(z.ulid());
}
else if (format === "xid") {
stringSchema = stringSchema.check(z.xid());
}
else if (format === "ksuid") {
stringSchema = stringSchema.check(z.ksuid());
}
// Note: json-string format is not currently supported by Zod
// Custom formats are ignored - keep as plain string
}
// Apply constraints
if (typeof schema.minLength === "number") {
stringSchema = stringSchema.min(schema.minLength);
}
if (typeof schema.maxLength === "number") {
stringSchema = stringSchema.max(schema.maxLength);
}
if (schema.pattern) {
// JSON Schema patterns are not implicitly anchored (match anywhere in string)
stringSchema = stringSchema.regex(new RegExp(schema.pattern));
}
zodSchema = stringSchema;
break;
}
case "number":
case "integer": {
let numberSchema = type === "integer" ? z.number().int() : z.number();
// Apply constraints
// In draft-04, `exclusiveMinimum: true` makes the sibling `minimum` exclusive rather than an independent bound, so the inclusive `.min()` is skipped; emitting it too would be dominated by the exclusive check and report a second, weaker issue.
if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) {
numberSchema = numberSchema.min(schema.minimum);
}
if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) {
numberSchema = numberSchema.max(schema.maximum);
}
if (typeof schema.exclusiveMinimum === "number") {
numberSchema = numberSchema.gt(schema.exclusiveMinimum);
}
else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
numberSchema = numberSchema.gt(schema.minimum);
}
if (typeof schema.exclusiveMaximum === "number") {
numberSchema = numberSchema.lt(schema.exclusiveMaximum);
}
else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
numberSchema = numberSchema.lt(schema.maximum);
}
if (typeof schema.multipleOf === "number") {
numberSchema = numberSchema.multipleOf(schema.multipleOf);
}
zodSchema = numberSchema;
break;
}
case "boolean": {
zodSchema = z.boolean();
break;
}
case "null": {
zodSchema = z.null();
break;
}
case "object": {
const shape = {};
const properties = schema.properties || {};
const requiredSet = new Set(schema.required || []);
const additionalSchema = typeof schema.additionalProperties === "object"
? convertSchema(schema.additionalProperties, ctx)
: undefined;
// Convert properties - mark optional ones
for (const [key, propSchema] of Object.entries(properties)) {
const propZodSchema = convertSchema(propSchema, ctx);
// If not in required array, make it optional. assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter
(0, util_js_1.assignProp)(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional());
}
// Handle patternProperties
if (schema.patternProperties) {
// patternProperties: keys matching pattern must satisfy corresponding schema. Use loose records so non-matching keys pass through
const patternProps = schema.patternProperties;
const patternKeys = Object.keys(patternProps);
const looseRecords = [];
for (const pattern of patternKeys) {
const patternValue = convertSchema(patternProps[pattern], ctx);
const keySchema = z.string().regex(new RegExp(pattern));
looseRecords.push(z.looseRecord(keySchema, patternValue));
}
// Build intersection: object schema + all pattern property records
const schemasToIntersect = [];
if (Object.keys(shape).length > 0) {
// Use passthrough so patternProperties can validate additional keys
schemasToIntersect.push(z.object(shape).passthrough());
}
schemasToIntersect.push(...looseRecords);
if (schemasToIntersect.length === 0) {
zodSchema = z.object({}).passthrough();
}
else if (schemasToIntersect.length === 1) {
zodSchema = schemasToIntersect[0];
}
else {
// Chain intersections: (A & B) & C & D ...
let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
for (let i = 2; i < schemasToIntersect.length; i++) {
result = z.intersection(result, schemasToIntersect[i]);
}
zodSchema = result;
}
// When additionalProperties is false, reject keys that are neither defined in properties nor matched by any patternProperty.
if (schema.additionalProperties === false) {
const propertyKeys = Object.keys(shape);
const patterns = patternKeys.map((p) => new RegExp(p));
const basePatternSchema = zodSchema;
zodSchema = zodSchema.check((payload) => {
if (!(0, util_js_1.isPlainObject)(payload.value))
return;
const unrecognized = [];
for (const key of Object.keys(payload.value)) {
if (propertyKeys.includes(key))
continue;
if (patterns.some((regex) => regex.test(key)))
continue;
unrecognized.push(key);
}
if (unrecognized.length) {
payload.issues.push({
code: "unrecognized_keys",
keys: unrecognized,
input: payload.value,
inst: basePatternSchema,
});
}
});
}
}
else {
// Handle additionalProperties. In JSON Schema, additionalProperties defaults to true (allow any extra properties). In Zod, objects strip unknown keys by default, so we need to handle this explicitly
const objectSchema = z.object(shape);
if (schema.additionalProperties === false) {
// Strict mode - no extra properties allowed
zodSchema = objectSchema.strict();
}
else if (additionalSchema) {
// Extra properties must match the specified schema
zodSchema = objectSchema.catchall(additionalSchema);
}
else {
// additionalProperties is true or undefined - allow any extra properties (passthrough)
zodSchema = objectSchema.passthrough();
}
}
// propertyNames constrains key *names* only, and says nothing about which keys are required or how their values validate. Layering it on top of the result keeps properties/patternProperties/additionalProperties composing underneath. `true` allows every name, so it needs no guard.
const hasKeyGuard = schema.propertyNames !== undefined && schema.propertyNames !== true;
const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : undefined;
const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : undefined;
if (hasKeyGuard || minProperties !== undefined || maxProperties !== undefined) {
let keySchema;
if (hasKeyGuard) {
// Keys are always strings, so a propertyNames subschema that omits `type` still constrains them — without this it would convert to z.any().
const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === undefined
? { type: "string", ...schema.propertyNames }
: schema.propertyNames;
keySchema = convertSchema(keyJSONSchema, ctx);
}
zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties });
}
break;
}
case "array": {
// Check if this is a tuple (prefixItems or items as array)
const prefixItems = schema.prefixItems;
const items = schema.items;
if (prefixItems && Array.isArray(prefixItems)) {
// Tuple with prefixItems (draft-2020-12)
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));
const positionalItems = applyMinItems(tupleItems, minItems);
const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : undefined;
const tupleSchema = z.tuple(positionalItems);
zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema;
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (Array.isArray(items)) {
// Tuple with items array (draft-7)
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
const tupleItems = items.map((item) => convertSchema(item, ctx));
const positionalItems = applyMinItems(tupleItems, minItems);
const rest = getTupleRest(schema.additionalItems, ctx);
const tupleSchema = z.tuple(positionalItems);
zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema;
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (items !== undefined) {
// Regular array
const element = convertSchema(items, ctx);
let arraySchema = z.array(element);
// Apply constraints
if (typeof schema.minItems === "number") {
arraySchema = arraySchema.min(schema.minItems);
}
if (typeof schema.maxItems === "number") {
arraySchema = arraySchema.max(schema.maxItems);
}
zodSchema = arraySchema;
}
else {
// No items specified - array of any
zodSchema = z.array(z.any());
}
// minContains/maxContains only constrain anything when `contains` itself is present
if (schema.uniqueItems === true || schema.contains !== undefined) {
zodSchema = checkArrayGuards(zodSchema, {
uniqueItems: schema.uniqueItems === true,
containsSchema: schema.contains !== undefined ? convertSchema(schema.contains, ctx) : undefined,
minContains: typeof schema.minContains === "number" ? schema.minContains : undefined,
maxContains: typeof schema.maxContains === "number" ? schema.maxContains : undefined,
});
}
break;
}
default:
throw new Error(`Unsupported type: ${type}`);
}
return zodSchema;
}
function convertSchema(schema, ctx) {
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Convert base schema first (ignoring composition keywords)
let baseSchema = convertBaseSchema(schema, ctx);
const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined;
// Process composition keywords LAST (they can appear together)
// Handle anyOf - wrap base schema with union
if (schema.anyOf && Array.isArray(schema.anyOf)) {
const options = schema.anyOf.map((s) => convertSchema(s, ctx));
const anyOfUnion = z.union(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
}
// Handle oneOf - exclusive union (exactly one must match)
if (schema.oneOf && Array.isArray(schema.oneOf)) {
const options = schema.oneOf.map((s) => convertSchema(s, ctx));
const oneOfUnion = z.xor(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
}
// Handle allOf - wrap base schema with intersection
if (schema.allOf && Array.isArray(schema.allOf)) {
if (schema.allOf.length === 0) {
baseSchema = hasExplicitType ? baseSchema : z.any();
}
else {
let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
const startIdx = hasExplicitType ? 0 : 1;
for (let i = startIdx; i < schema.allOf.length; i++) {
result = z.intersection(result, convertSchema(schema.allOf[i], ctx));
}
baseSchema = result;
}
}
// Handle nullable (OpenAPI 3.0)
if (schema.nullable === true && ctx.version === "openapi-3.0") {
baseSchema = z.nullable(baseSchema);
}
// Handle readOnly
if (schema.readOnly === true) {
baseSchema = z.readonly(baseSchema);
}
// Apply `default` so it wraps the fully-composed schema. This ensures `parse(undefined) -> default` works regardless of which branch of `convertBaseSchema` produced the inner schema (enum/const/not/typed/etc.).
if (schema.default !== undefined) {
baseSchema = baseSchema.default(schema.default);
}
// Collect non-description annotation metadata into the user-supplied registry. Description is handled separately below via `.describe()` to preserve the contract that `schema.description` reads from globalRegistry.
const extraMeta = {};
const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
for (const key of coreMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
for (const key of contentMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
// `propertyNames` and `contains` are enforced by a guard, which `toJSONSchema` cannot infer, so the original keyword is carried as metadata to keep the round-trip lossless. Only where it was actually applied: on any other type it is inert, and on a `$ref` the metadata would land on the target every reference shares. A carried subschema is copied verbatim while the root `$defs` stay behind, so one holding a `$ref` is dropped rather than emitted as a dangling reference.
if (schema.type === "object" && schema.$ref === undefined) {
if (schema.propertyNames !== undefined && !containsRef(schema.propertyNames)) {
extraMeta.propertyNames = schema.propertyNames;
}
for (const key of ["minProperties", "maxProperties"]) {
if (schema[key] !== undefined)
extraMeta[key] = schema[key];
}
}
if (schema.type === "array" && schema.$ref === undefined) {
if (schema.contains !== undefined && !containsRef(schema.contains)) {
extraMeta.contains = schema.contains;
}
for (const key of ["uniqueItems", "minContains", "maxContains"]) {
if (schema[key] !== undefined)
extraMeta[key] = schema[key];
}
}
for (const key of Object.keys(schema)) {
if (!RECOGNIZED_KEYS.has(key)) {
(0, util_js_1.assignProp)(extraMeta, key, schema[key]);
}
}
if (Object.keys(extraMeta).length > 0) {
ctx.registry.add(baseSchema, extraMeta);
}
// Apply description last. `.describe()` clones the schema and sets `_zod.parent` on the clone, so registry lookups on the returned reference still resolve `extraMeta` via parent inheritance.
if (schema.description) {
baseSchema = baseSchema.describe(schema.description);
}
return baseSchema;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
function fromJSONSchema(schema, params) {
// Handle boolean schemas
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Normalize input via a JSON round-trip. This guarantees the converter walks a plain, finite, JSON-valid object graph: cyclic inputs fail here, getter/Proxy-based properties are materialized into static values, and class instances collapse to plain objects.
let normalized;
try {
normalized = JSON.parse(JSON.stringify(schema));
}
catch {
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
}
const version = detectVersion(normalized, params?.defaultTarget);
const defs = (normalized.$defs || normalized.definitions || {});
const ctx = {
version,
defs,
refs: new Map(),
processing: new Set(),
rootSchema: normalized,
registry: params?.registry ?? registries_js_1.globalRegistry,
};
return convertSchema(normalized, ctx);
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+12
View File
@@ -0,0 +1,12 @@
import type * as JSONSchema from "../core/json-schema.cjs";
import { type $ZodRegistry } from "../core/registries.cjs";
import type { ZodType } from "./schemas.cjs";
type JSONSchemaVersion = "draft-2020-12" | "draft-7" | "draft-4" | "openapi-3.0";
interface FromJSONSchemaParams {
defaultTarget?: JSONSchemaVersion;
registry?: $ZodRegistry<any>;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
export declare function fromJSONSchema(schema: JSONSchema.JSONSchema | boolean, params?: FromJSONSchemaParams): ZodType;
export {};
+12
View File
@@ -0,0 +1,12 @@
import type * as JSONSchema from "../core/json-schema.js";
import { type $ZodRegistry } from "../core/registries.js";
import type { ZodType } from "./schemas.js";
type JSONSchemaVersion = "draft-2020-12" | "draft-7" | "draft-4" | "openapi-3.0";
interface FromJSONSchemaParams {
defaultTarget?: JSONSchemaVersion;
registry?: $ZodRegistry<any>;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
export declare function fromJSONSchema(schema: JSONSchema.JSONSchema | boolean, params?: FromJSONSchemaParams): ZodType;
export {};
+881
View File
@@ -0,0 +1,881 @@
import { globalRegistry } from "../core/registries.js";
import { assignProp, isPlainObject } from "../core/util.js";
import * as _checks from "./checks.js";
import * as _iso from "./iso.js";
import * as _schemas from "./schemas.js";
// Local z object to avoid circular dependency with ../index.js
const z = {
..._schemas,
..._checks,
iso: _iso,
};
// Keys that are recognized and handled by the conversion logic
const RECOGNIZED_KEYS = /*@__PURE__*/ new Set([
// Schema identification
"$schema",
"$ref",
"$defs",
"definitions",
// Core schema keywords
"$id",
"id",
"$comment",
"$anchor",
"$vocabulary",
"$dynamicRef",
"$dynamicAnchor",
// Type
"type",
"enum",
"const",
// Composition
"anyOf",
"oneOf",
"allOf",
"not",
// Object
"properties",
"required",
"additionalProperties",
"patternProperties",
"propertyNames",
"minProperties",
"maxProperties",
// Array
"items",
"prefixItems",
"additionalItems",
"minItems",
"maxItems",
"uniqueItems",
"contains",
"minContains",
"maxContains",
// String
"minLength",
"maxLength",
"pattern",
"format",
// Number
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
// Already handled metadata
"description",
"default",
// Content
"contentEncoding",
"contentMediaType",
"contentSchema",
// Unsupported (error-throwing)
"unevaluatedItems",
"unevaluatedProperties",
"if",
"then",
"else",
"dependentSchemas",
"dependentRequired",
// OpenAPI
"nullable",
"readOnly",
]);
function detectVersion(schema, defaultTarget) {
const $schema = schema.$schema;
if ($schema === "https://json-schema.org/draft/2020-12/schema") {
return "draft-2020-12";
}
if ($schema === "http://json-schema.org/draft-07/schema#") {
return "draft-7";
}
if ($schema === "http://json-schema.org/draft-04/schema#") {
return "draft-4";
}
// Use defaultTarget if provided, otherwise default to draft-2020-12
return defaultTarget ?? "draft-2020-12";
}
// Positional schemas constrain the elements that are present; only minItems makes them required.
function applyMinItems(items, minItems) {
return items.map((item, index) => (index < minItems ? item : item.optional()));
}
// Inverse of the encoding applied to $ref pointer segments in to-json-schema.ts. Per RFC 6901 the `~1` replacement must run before `~0`.
function decodeJSONPointerSegment(segment) {
return segment.replace(/~1/g, "/").replace(/~0/g, "~");
}
function resolveRef(ref, ctx) {
if (!ref.startsWith("#")) {
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
}
const path = ref.slice(1).split("/").filter(Boolean);
// Handle root reference "#"
if (path.length === 0) {
return ctx.rootSchema;
}
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
if (path[0] === defsKey) {
const key = path[1] === undefined ? undefined : decodeJSONPointerSegment(path[1]);
if (!key || !ctx.defs[key]) {
throw new Error(`Reference not found: ${ref}`);
}
return ctx.defs[key];
}
throw new Error(`Reference not found: ${ref}`);
}
/**
* Enforces the keywords that constrain an object's own keys — `propertyNames`,
* `minProperties`, `maxProperties` — before `objectSchema` runs. The guard has
* to see the raw input: an object parse drops `__proto__` and can add keys from
* a property `default`, so its output is not the set of names the instance
* actually carried.
*/
function checkObjectGuards(objectSchema, guards) {
// An identity transform, not z.any(), so `toJSONSchema` reports the object on both the input and the output side of the pipe.
const guard = z
.transform((value) => value)
.check((payload) => {
const value = payload.value;
if (typeof value !== "object" || value === null || Array.isArray(value))
return;
const keys = Object.getOwnPropertyNames(value);
if (guards.minProperties !== undefined && keys.length < guards.minProperties) {
payload.issues.push({
origin: "object",
code: "too_small",
minimum: guards.minProperties,
inclusive: true,
message: `Too small: expected object to have >=${guards.minProperties} properties`,
input: value,
inst: objectSchema,
continue: true,
});
}
if (guards.maxProperties !== undefined && keys.length > guards.maxProperties) {
payload.issues.push({
origin: "object",
code: "too_big",
maximum: guards.maxProperties,
inclusive: true,
message: `Too big: expected object to have <=${guards.maxProperties} properties`,
input: value,
inst: objectSchema,
continue: true,
});
}
if (guards.keySchema) {
for (const key of keys) {
const result = guards.keySchema.safeParse(key);
if (result.success)
continue;
payload.issues.push({
code: "invalid_key",
origin: "record",
issues: result.error.issues,
input: key,
path: [key],
continue: true,
});
}
}
});
return guard.pipe(objectSchema);
}
/**
* An injective string for JSON data: two values share a key exactly when `uniqueItems` calls them
* equal, so duplicate detection is a Map lookup rather than a pairwise walk. Strings and keys are
* length-prefixed so no value can spell another one. `null` means "never equal to anything" — a
* cycle or a NaN, neither of which JSON can express.
*/
function canonicalKey(value, seen) {
if (value === null)
return "z";
const type = typeof value;
if (type !== "object") {
if (type === "number" && Number.isNaN(value))
return null;
const raw = String(value);
return `${type[0]}${raw.length}:${raw}`;
}
if (seen.has(value))
return null;
seen.add(value);
try {
if (Array.isArray(value)) {
const parts = [];
for (const item of value) {
const key = canonicalKey(item, seen);
if (key === null)
return null;
parts.push(key);
}
return `a${parts.length}:[${parts.join(",")}]`;
}
const keys = Object.keys(value).sort();
const parts = [];
for (const k of keys) {
const key = canonicalKey(value[k], seen);
if (key === null)
return null;
parts.push(`${k.length}:${k}=${key}`);
}
return `o${parts.length}:{${parts.join(",")}}`;
}
finally {
seen.delete(value);
}
}
// keywords whose value is a schema or an array of them
const SCHEMA_KEYWORDS = /*@__PURE__*/ new Set([
"items",
"prefixItems",
"additionalItems",
"additionalProperties",
"contains",
"propertyNames",
"not",
"if",
"then",
"else",
"allOf",
"anyOf",
"oneOf",
"unevaluatedItems",
"unevaluatedProperties",
"contentSchema",
]);
// keywords whose value maps names to schemas. draft-7 `dependencies` also allows an array of property names, which holds no schema to walk
const SCHEMA_MAP_KEYWORDS = /*@__PURE__*/ new Set([
"properties",
"patternProperties",
"dependentSchemas",
"dependencies",
"$defs",
"definitions",
]);
/**
* True when a subschema holds a `$ref` anywhere a schema can appear. Only those positions are
* walked: `$ref` under `default` or an `x-` annotation is instance data with an ordinary key, and
* reading it as a reference would drop a constraint that resolves perfectly well.
*/
function containsRef(value) {
if (typeof value !== "object" || value === null)
return false;
if (Array.isArray(value))
return value.some(containsRef);
if (typeof value.$ref === "string")
return true;
return Object.entries(value).some(([key, sub]) => {
if (SCHEMA_KEYWORDS.has(key))
return containsRef(sub);
if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null)
return false;
return Object.values(sub).some(containsRef);
});
}
function plural(n) {
return n === 1 ? "element" : "elements";
}
/**
* Enforces `uniqueItems` and the `contains` family before `arraySchema` runs, for the same reason
* `checkObjectGuards` runs pre-pipe: an item parse can apply a nested `default`, so the parsed
* array is not the instance the keywords are defined over. A guard issue aborts the pipe, so
* `minItems`/`maxItems` are not also reported on the same parse — instance correctness is worth
* more than co-reporting two issues.
*/
function checkArrayGuards(arraySchema, guards) {
// An identity transform, not z.any(), so `toJSONSchema` reports the array on both the input and the output side of the pipe.
const guard = z
.transform((value) => value)
.check((payload) => {
const items = payload.value;
if (!Array.isArray(items))
return;
if (guards.uniqueItems === true) {
const firstSeen = new Map();
for (let i = 0; i < items.length; i++) {
const key = canonicalKey(items[i], new Set());
if (key === null)
continue;
const first = firstSeen.get(key);
if (first === undefined) {
firstSeen.set(key, i);
continue;
}
payload.issues.push({
code: "custom",
message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`,
input: items,
path: [i],
continue: true,
});
}
}
if (guards.containsSchema) {
const minContains = guards.minContains ?? 1;
// one past the ceiling already proves the failure, and nothing above it changes the verdict
const ceiling = guards.maxContains !== undefined ? guards.maxContains + 1 : Number.POSITIVE_INFINITY;
let matches = 0;
for (const item of items) {
if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling)
break;
}
if (matches < minContains) {
// the scan ran to the end, so this count is exact
payload.issues.push({
code: "custom",
message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,
input: items,
continue: true,
});
}
if (guards.maxContains !== undefined && matches > guards.maxContains) {
payload.issues.push({
code: "custom",
message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,
input: items,
continue: true,
});
}
}
});
return guard.pipe(arraySchema);
}
function getTupleRest(restSchema, ctx) {
if (restSchema === false) {
return undefined;
}
if (restSchema === undefined || restSchema === true) {
return z.any();
}
return convertSchema(restSchema, ctx);
}
// the RFC 3339 full-time keyword, narrower than `z.iso.time()`; local because sharing it via `timeSource` pins that builder into every bundle (+139 B gzipped on a mini `z.boolean()`)
const fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
function convertBaseSchema(schema, ctx) {
// Handle unsupported features
if (schema.not !== undefined) {
// Special case: { not: {} } represents never
if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
return z.never();
}
throw new Error("not is not supported in Zod (except { not: {} } for never)");
}
if (schema.unevaluatedItems !== undefined) {
throw new Error("unevaluatedItems is not supported");
}
if (schema.unevaluatedProperties !== undefined) {
throw new Error("unevaluatedProperties is not supported");
}
if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) {
throw new Error("Conditional schemas (if/then/else) are not supported");
}
if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) {
throw new Error("dependentSchemas and dependentRequired are not supported");
}
// Handle $ref
if (schema.$ref) {
const refPath = schema.$ref;
if (ctx.refs.has(refPath)) {
return ctx.refs.get(refPath);
}
if (ctx.processing.has(refPath)) {
// Circular reference - use lazy
return z.lazy(() => {
if (!ctx.refs.has(refPath)) {
throw new Error(`Circular reference not resolved: ${refPath}`);
}
return ctx.refs.get(refPath);
});
}
ctx.processing.add(refPath);
const resolved = resolveRef(refPath, ctx);
const zodSchema = convertSchema(resolved, ctx);
ctx.refs.set(refPath, zodSchema);
ctx.processing.delete(refPath);
return zodSchema;
}
// Handle enum
if (schema.enum !== undefined) {
const enumValues = schema.enum;
// Special case: OpenAPI 3.0 null representation { type: "string", nullable: true, enum: [null] }
if (ctx.version === "openapi-3.0" &&
schema.nullable === true &&
enumValues.length === 1 &&
enumValues[0] === null) {
return z.null();
}
if (enumValues.length === 0) {
return z.never();
}
if (enumValues.length === 1) {
return z.literal(enumValues[0]);
}
// Check if all values are strings
if (enumValues.every((v) => typeof v === "string")) {
return z.enum(enumValues);
}
// Mixed types - use union of literals
const literalSchemas = enumValues.map((v) => z.literal(v));
if (literalSchemas.length < 2) {
return literalSchemas[0];
}
return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
}
// Handle const
if (schema.const !== undefined) {
return z.literal(schema.const);
}
// Handle type
const type = schema.type;
if (Array.isArray(type)) {
// Expand type array into anyOf union
const typeSchemas = type.map((t) => {
const typeSchema = { ...schema, type: t };
return convertBaseSchema(typeSchema, ctx);
});
if (typeSchemas.length === 0) {
return z.never();
}
if (typeSchemas.length === 1) {
return typeSchemas[0];
}
return z.union(typeSchemas);
}
if (!type) {
// No type specified - empty schema (any)
return z.any();
}
let zodSchema;
switch (type) {
case "string": {
let stringSchema = z.string();
// Apply format using .check() with Zod format functions
if (schema.format) {
const format = schema.format;
// Map common formats to Zod check functions
if (format === "email") {
stringSchema = stringSchema.check(z.email());
}
else if (format === "uri" || format === "uri-reference") {
stringSchema = stringSchema.check(z.url());
}
else if (format === "uuid" || format === "guid") {
stringSchema = stringSchema.check(z.uuid());
}
else if (format === "date-time") {
stringSchema = stringSchema.check(z.iso.datetime({ offset: true }));
}
else if (format === "date") {
stringSchema = stringSchema.check(z.iso.date());
}
else if (format === "time") {
stringSchema = stringSchema.check(z.regex(fullTime));
}
else if (format === "duration") {
stringSchema = stringSchema.check(z.iso.duration());
}
else if (format === "hostname") {
stringSchema = stringSchema.check(z.hostname());
}
else if (format === "ipv4") {
stringSchema = stringSchema.check(z.ipv4());
}
else if (format === "ipv6") {
stringSchema = stringSchema.check(z.ipv6());
}
else if (format === "mac") {
stringSchema = stringSchema.check(z.mac());
}
else if (format === "cidr") {
stringSchema = stringSchema.check(z.cidrv4());
}
else if (format === "cidr-v6") {
stringSchema = stringSchema.check(z.cidrv6());
}
else if (format === "base64") {
stringSchema = stringSchema.check(z.base64());
}
else if (format === "base64url") {
stringSchema = stringSchema.check(z.base64url());
}
else if (format === "e164") {
stringSchema = stringSchema.check(z.e164());
}
else if (format === "credit_card") {
stringSchema = stringSchema.check(z.creditCard());
}
else if (format === "iban") {
stringSchema = stringSchema.check(z.iban());
}
else if (format === "jwt") {
stringSchema = stringSchema.check(z.jwt());
}
else if (format === "emoji") {
stringSchema = stringSchema.check(z.emoji());
}
else if (format === "nanoid") {
stringSchema = stringSchema.check(z.nanoid());
}
else if (format === "cuid") {
stringSchema = stringSchema.check(z.cuid());
}
else if (format === "cuid2") {
stringSchema = stringSchema.check(z.cuid2());
}
else if (format === "ulid") {
stringSchema = stringSchema.check(z.ulid());
}
else if (format === "xid") {
stringSchema = stringSchema.check(z.xid());
}
else if (format === "ksuid") {
stringSchema = stringSchema.check(z.ksuid());
}
// Note: json-string format is not currently supported by Zod
// Custom formats are ignored - keep as plain string
}
// Apply constraints
if (typeof schema.minLength === "number") {
stringSchema = stringSchema.min(schema.minLength);
}
if (typeof schema.maxLength === "number") {
stringSchema = stringSchema.max(schema.maxLength);
}
if (schema.pattern) {
// JSON Schema patterns are not implicitly anchored (match anywhere in string)
stringSchema = stringSchema.regex(new RegExp(schema.pattern));
}
zodSchema = stringSchema;
break;
}
case "number":
case "integer": {
let numberSchema = type === "integer" ? z.number().int() : z.number();
// Apply constraints
// In draft-04, `exclusiveMinimum: true` makes the sibling `minimum` exclusive rather than an independent bound, so the inclusive `.min()` is skipped; emitting it too would be dominated by the exclusive check and report a second, weaker issue.
if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) {
numberSchema = numberSchema.min(schema.minimum);
}
if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) {
numberSchema = numberSchema.max(schema.maximum);
}
if (typeof schema.exclusiveMinimum === "number") {
numberSchema = numberSchema.gt(schema.exclusiveMinimum);
}
else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
numberSchema = numberSchema.gt(schema.minimum);
}
if (typeof schema.exclusiveMaximum === "number") {
numberSchema = numberSchema.lt(schema.exclusiveMaximum);
}
else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
numberSchema = numberSchema.lt(schema.maximum);
}
if (typeof schema.multipleOf === "number") {
numberSchema = numberSchema.multipleOf(schema.multipleOf);
}
zodSchema = numberSchema;
break;
}
case "boolean": {
zodSchema = z.boolean();
break;
}
case "null": {
zodSchema = z.null();
break;
}
case "object": {
const shape = {};
const properties = schema.properties || {};
const requiredSet = new Set(schema.required || []);
const additionalSchema = typeof schema.additionalProperties === "object"
? convertSchema(schema.additionalProperties, ctx)
: undefined;
// Convert properties - mark optional ones
for (const [key, propSchema] of Object.entries(properties)) {
const propZodSchema = convertSchema(propSchema, ctx);
// If not in required array, make it optional. assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter
assignProp(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional());
}
// Handle patternProperties
if (schema.patternProperties) {
// patternProperties: keys matching pattern must satisfy corresponding schema. Use loose records so non-matching keys pass through
const patternProps = schema.patternProperties;
const patternKeys = Object.keys(patternProps);
const looseRecords = [];
for (const pattern of patternKeys) {
const patternValue = convertSchema(patternProps[pattern], ctx);
const keySchema = z.string().regex(new RegExp(pattern));
looseRecords.push(z.looseRecord(keySchema, patternValue));
}
// Build intersection: object schema + all pattern property records
const schemasToIntersect = [];
if (Object.keys(shape).length > 0) {
// Use passthrough so patternProperties can validate additional keys
schemasToIntersect.push(z.object(shape).passthrough());
}
schemasToIntersect.push(...looseRecords);
if (schemasToIntersect.length === 0) {
zodSchema = z.object({}).passthrough();
}
else if (schemasToIntersect.length === 1) {
zodSchema = schemasToIntersect[0];
}
else {
// Chain intersections: (A & B) & C & D ...
let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
for (let i = 2; i < schemasToIntersect.length; i++) {
result = z.intersection(result, schemasToIntersect[i]);
}
zodSchema = result;
}
// When additionalProperties is false, reject keys that are neither defined in properties nor matched by any patternProperty.
if (schema.additionalProperties === false) {
const propertyKeys = Object.keys(shape);
const patterns = patternKeys.map((p) => new RegExp(p));
const basePatternSchema = zodSchema;
zodSchema = zodSchema.check((payload) => {
if (!isPlainObject(payload.value))
return;
const unrecognized = [];
for (const key of Object.keys(payload.value)) {
if (propertyKeys.includes(key))
continue;
if (patterns.some((regex) => regex.test(key)))
continue;
unrecognized.push(key);
}
if (unrecognized.length) {
payload.issues.push({
code: "unrecognized_keys",
keys: unrecognized,
input: payload.value,
inst: basePatternSchema,
});
}
});
}
}
else {
// Handle additionalProperties. In JSON Schema, additionalProperties defaults to true (allow any extra properties). In Zod, objects strip unknown keys by default, so we need to handle this explicitly
const objectSchema = z.object(shape);
if (schema.additionalProperties === false) {
// Strict mode - no extra properties allowed
zodSchema = objectSchema.strict();
}
else if (additionalSchema) {
// Extra properties must match the specified schema
zodSchema = objectSchema.catchall(additionalSchema);
}
else {
// additionalProperties is true or undefined - allow any extra properties (passthrough)
zodSchema = objectSchema.passthrough();
}
}
// propertyNames constrains key *names* only, and says nothing about which keys are required or how their values validate. Layering it on top of the result keeps properties/patternProperties/additionalProperties composing underneath. `true` allows every name, so it needs no guard.
const hasKeyGuard = schema.propertyNames !== undefined && schema.propertyNames !== true;
const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : undefined;
const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : undefined;
if (hasKeyGuard || minProperties !== undefined || maxProperties !== undefined) {
let keySchema;
if (hasKeyGuard) {
// Keys are always strings, so a propertyNames subschema that omits `type` still constrains them — without this it would convert to z.any().
const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === undefined
? { type: "string", ...schema.propertyNames }
: schema.propertyNames;
keySchema = convertSchema(keyJSONSchema, ctx);
}
zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties });
}
break;
}
case "array": {
// Check if this is a tuple (prefixItems or items as array)
const prefixItems = schema.prefixItems;
const items = schema.items;
if (prefixItems && Array.isArray(prefixItems)) {
// Tuple with prefixItems (draft-2020-12)
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));
const positionalItems = applyMinItems(tupleItems, minItems);
const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : undefined;
const tupleSchema = z.tuple(positionalItems);
zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema;
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (Array.isArray(items)) {
// Tuple with items array (draft-7)
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
const tupleItems = items.map((item) => convertSchema(item, ctx));
const positionalItems = applyMinItems(tupleItems, minItems);
const rest = getTupleRest(schema.additionalItems, ctx);
const tupleSchema = z.tuple(positionalItems);
zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema;
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (items !== undefined) {
// Regular array
const element = convertSchema(items, ctx);
let arraySchema = z.array(element);
// Apply constraints
if (typeof schema.minItems === "number") {
arraySchema = arraySchema.min(schema.minItems);
}
if (typeof schema.maxItems === "number") {
arraySchema = arraySchema.max(schema.maxItems);
}
zodSchema = arraySchema;
}
else {
// No items specified - array of any
zodSchema = z.array(z.any());
}
// minContains/maxContains only constrain anything when `contains` itself is present
if (schema.uniqueItems === true || schema.contains !== undefined) {
zodSchema = checkArrayGuards(zodSchema, {
uniqueItems: schema.uniqueItems === true,
containsSchema: schema.contains !== undefined ? convertSchema(schema.contains, ctx) : undefined,
minContains: typeof schema.minContains === "number" ? schema.minContains : undefined,
maxContains: typeof schema.maxContains === "number" ? schema.maxContains : undefined,
});
}
break;
}
default:
throw new Error(`Unsupported type: ${type}`);
}
return zodSchema;
}
function convertSchema(schema, ctx) {
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Convert base schema first (ignoring composition keywords)
let baseSchema = convertBaseSchema(schema, ctx);
const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined;
// Process composition keywords LAST (they can appear together)
// Handle anyOf - wrap base schema with union
if (schema.anyOf && Array.isArray(schema.anyOf)) {
const options = schema.anyOf.map((s) => convertSchema(s, ctx));
const anyOfUnion = z.union(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
}
// Handle oneOf - exclusive union (exactly one must match)
if (schema.oneOf && Array.isArray(schema.oneOf)) {
const options = schema.oneOf.map((s) => convertSchema(s, ctx));
const oneOfUnion = z.xor(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
}
// Handle allOf - wrap base schema with intersection
if (schema.allOf && Array.isArray(schema.allOf)) {
if (schema.allOf.length === 0) {
baseSchema = hasExplicitType ? baseSchema : z.any();
}
else {
let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
const startIdx = hasExplicitType ? 0 : 1;
for (let i = startIdx; i < schema.allOf.length; i++) {
result = z.intersection(result, convertSchema(schema.allOf[i], ctx));
}
baseSchema = result;
}
}
// Handle nullable (OpenAPI 3.0)
if (schema.nullable === true && ctx.version === "openapi-3.0") {
baseSchema = z.nullable(baseSchema);
}
// Handle readOnly
if (schema.readOnly === true) {
baseSchema = z.readonly(baseSchema);
}
// Apply `default` so it wraps the fully-composed schema. This ensures `parse(undefined) -> default` works regardless of which branch of `convertBaseSchema` produced the inner schema (enum/const/not/typed/etc.).
if (schema.default !== undefined) {
baseSchema = baseSchema.default(schema.default);
}
// Collect non-description annotation metadata into the user-supplied registry. Description is handled separately below via `.describe()` to preserve the contract that `schema.description` reads from globalRegistry.
const extraMeta = {};
const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
for (const key of coreMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
for (const key of contentMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
// `propertyNames` and `contains` are enforced by a guard, which `toJSONSchema` cannot infer, so the original keyword is carried as metadata to keep the round-trip lossless. Only where it was actually applied: on any other type it is inert, and on a `$ref` the metadata would land on the target every reference shares. A carried subschema is copied verbatim while the root `$defs` stay behind, so one holding a `$ref` is dropped rather than emitted as a dangling reference.
if (schema.type === "object" && schema.$ref === undefined) {
if (schema.propertyNames !== undefined && !containsRef(schema.propertyNames)) {
extraMeta.propertyNames = schema.propertyNames;
}
for (const key of ["minProperties", "maxProperties"]) {
if (schema[key] !== undefined)
extraMeta[key] = schema[key];
}
}
if (schema.type === "array" && schema.$ref === undefined) {
if (schema.contains !== undefined && !containsRef(schema.contains)) {
extraMeta.contains = schema.contains;
}
for (const key of ["uniqueItems", "minContains", "maxContains"]) {
if (schema[key] !== undefined)
extraMeta[key] = schema[key];
}
}
for (const key of Object.keys(schema)) {
if (!RECOGNIZED_KEYS.has(key)) {
assignProp(extraMeta, key, schema[key]);
}
}
if (Object.keys(extraMeta).length > 0) {
ctx.registry.add(baseSchema, extraMeta);
}
// Apply description last. `.describe()` clones the schema and sets `_zod.parent` on the clone, so registry lookups on the returned reference still resolve `extraMeta` via parent inheritance.
if (schema.description) {
baseSchema = baseSchema.describe(schema.description);
}
return baseSchema;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
export function fromJSONSchema(schema, params) {
// Handle boolean schemas
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Normalize input via a JSON round-trip. This guarantees the converter walks a plain, finite, JSON-valid object graph: cyclic inputs fail here, getter/Proxy-based properties are materialized into static values, and class instances collapse to plain objects.
let normalized;
try {
normalized = JSON.parse(JSON.stringify(schema));
}
catch {
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
}
const version = detectVersion(normalized, params?.defaultTarget);
const defs = (normalized.$defs || normalized.definitions || {});
const ctx = {
version,
defs,
refs: new Map(),
processing: new Set(),
rootSchema: normalized,
registry: params?.registry ?? globalRegistry,
};
return convertSchema(normalized, ctx);
}
+82
View File
@@ -0,0 +1,82 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.input = input;
exports.output = output;
const util_js_1 = require("../core/util.cjs");
const visit_js_1 = require("../core/visit.cjs");
const schemas = __importStar(require("./schemas.cjs"));
/** Appends a pipe's own checks to the side that replaces it, mirroring how `.check()` clones. */
function withChecks(side, checks) {
if (!checks?.length)
return side;
const def = side._zod.def;
return (0, util_js_1.clone)(side, (0, util_js_1.mergeDefs)(def, { checks: [...(def.checks ?? []), ...checks] }), { parent: true });
}
/** The out side, carrying the pipe's own checks: those run against the decoded value, which is what `out` produces. */
function outSide(def) {
return withChecks(def.out, def.checks);
}
/** The in side. `z.preprocess` pipes a transform into a schema, and a bare transform validates nothing, so the schema it feeds is the real input side — the resolution `toJSONSchema` already makes for this case. */
function inSide(def) {
return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in;
}
/** Returns a copy of the schema with every pipe replaced by its input side. A codec's checks are dropped: they constrain the decoded value the input side never produces. */
function input(schema) {
return (0, visit_js_1.visit)(schema, {
pipe: (s) => inSide(s._zod.def),
// A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across.
default: (s, rewritten) => (rewritten ? schemas.optional(s._zod.def.innerType) : s),
// A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own.
catch: (s, rewritten) => (rewritten ? s._zod.def.innerType : s),
});
}
/** Returns a copy of the schema with every pipe replaced by its output side, carrying over the pipe's own checks. */
function output(schema) {
return (0, visit_js_1.visit)(schema, {
pipe: (s) => outSide(s._zod.def),
// A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded.
prefault: (s, rewritten) => (rewritten ? s._zod.def.innerType : s),
});
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+8
View File
@@ -0,0 +1,8 @@
import type * as core from "../core/index.cjs";
import * as schemas from "./schemas.cjs";
export type input<T> = core.input<T>;
export type output<T> = core.output<T>;
/** Returns a copy of the schema with every pipe replaced by its input side. A codec's checks are dropped: they constrain the decoded value the input side never produces. */
export declare function input<T extends core.$ZodType>(schema: T): schemas.ZodType<core.input<T>, core.input<T>>;
/** Returns a copy of the schema with every pipe replaced by its output side, carrying over the pipe's own checks. */
export declare function output<T extends core.$ZodType>(schema: T): schemas.ZodType<core.output<T>, core.output<T>>;
+8
View File
@@ -0,0 +1,8 @@
import type * as core from "../core/index.js";
import * as schemas from "./schemas.js";
export type input<T> = core.input<T>;
export type output<T> = core.output<T>;
/** Returns a copy of the schema with every pipe replaced by its input side. A codec's checks are dropped: they constrain the decoded value the input side never produces. */
export declare function input<T extends core.$ZodType>(schema: T): schemas.ZodType<core.input<T>, core.input<T>>;
/** Returns a copy of the schema with every pipe replaced by its output side, carrying over the pipe's own checks. */
export declare function output<T extends core.$ZodType>(schema: T): schemas.ZodType<core.output<T>, core.output<T>>;
+36
View File
@@ -0,0 +1,36 @@
import { clone, mergeDefs } from "../core/util.js";
import { visit } from "../core/visit.js";
import * as schemas from "./schemas.js";
/** Appends a pipe's own checks to the side that replaces it, mirroring how `.check()` clones. */
function withChecks(side, checks) {
if (!checks?.length)
return side;
const def = side._zod.def;
return clone(side, mergeDefs(def, { checks: [...(def.checks ?? []), ...checks] }), { parent: true });
}
/** The out side, carrying the pipe's own checks: those run against the decoded value, which is what `out` produces. */
function outSide(def) {
return withChecks(def.out, def.checks);
}
/** The in side. `z.preprocess` pipes a transform into a schema, and a bare transform validates nothing, so the schema it feeds is the real input side — the resolution `toJSONSchema` already makes for this case. */
function inSide(def) {
return def.in._zod.traits.has("$ZodTransform") ? outSide(def) : def.in;
}
/** Returns a copy of the schema with every pipe replaced by its input side. A codec's checks are dropped: they constrain the decoded value the input side never produces. */
export function input(schema) {
return visit(schema, {
pipe: (s) => inSide(s._zod.def),
// A default value belongs to the output side, so a rewritten inner type leaves it stranded. `.default()` widens the declared input type with `undefined`, and `optional` is what carries that across.
default: (s, rewritten) => (rewritten ? schemas.optional(s._zod.def.innerType) : s),
// A catch value is output-side too, but `.catch()` leaves the declared input type alone, so the inner schema stands on its own.
catch: (s, rewritten) => (rewritten ? s._zod.def.innerType : s),
});
}
/** Returns a copy of the schema with every pipe replaced by its output side, carrying over the pipe's own checks. */
export function output(schema) {
return visit(schema, {
pipe: (s) => outSide(s._zod.def),
// A prefault value is fed through the schema, which makes it input-side, so a rewritten inner type leaves it stranded.
prefault: (s, rewritten) => (rewritten ? s._zod.def.innerType : s),
});
}
+52
View File
@@ -0,0 +1,52 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exports.z = void 0;
const z = __importStar(require("./external.cjs"));
exports.z = z;
exports.default = z;
__exportStar(require("./external.cjs"), exports);
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+3
View File
@@ -0,0 +1,3 @@
import * as z from "./external.cjs";
export * from "./external.cjs";
export { z, z as default };
+3
View File
@@ -0,0 +1,3 @@
import * as z from "./external.js";
export * from "./external.js";
export { z, z as default };
+4
View File
@@ -0,0 +1,4 @@
import * as z from "./external.js";
export * from "./external.js";
// See the note in `src/index.ts` — aliasing keeps the default export shakable.
export { z, z as default };
+68
View File
@@ -0,0 +1,68 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodISOTime = exports.ZodISODuration = exports.ZodISODateTime = exports.ZodISODate = void 0;
exports.datetime = datetime;
exports.date = date;
exports.time = time;
exports.duration = duration;
const core = __importStar(require("../core/index.cjs"));
const schemas_js_1 = require("./schemas.cjs");
var schemas_js_2 = require("./schemas.cjs");
Object.defineProperty(exports, "ZodISODate", { enumerable: true, get: function () { return schemas_js_2.ZodISODate; } });
Object.defineProperty(exports, "ZodISODateTime", { enumerable: true, get: function () { return schemas_js_2.ZodISODateTime; } });
Object.defineProperty(exports, "ZodISODuration", { enumerable: true, get: function () { return schemas_js_2.ZodISODuration; } });
Object.defineProperty(exports, "ZodISOTime", { enumerable: true, get: function () { return schemas_js_2.ZodISOTime; } });
function datetime(params) {
return core._isoDateTime(schemas_js_1.ZodISODateTime, params);
}
function date(params) {
return core._isoDate(schemas_js_1.ZodISODate, params);
}
function time(params) {
return core._isoTime(schemas_js_1.ZodISOTime, params);
}
function duration(params) {
return core._isoDuration(schemas_js_1.ZodISODuration, params);
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+7
View File
@@ -0,0 +1,7 @@
import * as core from "../core/index.cjs";
import { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.cjs";
export { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.cjs";
export declare function datetime(params?: string | core.$ZodISODateTimeParams): ZodISODateTime;
export declare function date(params?: string | core.$ZodISODateParams): ZodISODate;
export declare function time(params?: string | core.$ZodISOTimeParams): ZodISOTime;
export declare function duration(params?: string | core.$ZodISODurationParams): ZodISODuration;
+7
View File
@@ -0,0 +1,7 @@
import * as core from "../core/index.js";
import { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.js";
export { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.js";
export declare function datetime(params?: string | core.$ZodISODateTimeParams): ZodISODateTime;
export declare function date(params?: string | core.$ZodISODateParams): ZodISODate;
export declare function time(params?: string | core.$ZodISOTimeParams): ZodISOTime;
export declare function duration(params?: string | core.$ZodISODurationParams): ZodISODuration;
+15
View File
@@ -0,0 +1,15 @@
import * as core from "../core/index.js";
import { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.js";
export { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from "./schemas.js";
export function datetime(params) {
return core._isoDateTime(ZodISODateTime, params);
}
export function date(params) {
return core._isoDate(ZodISODate, params);
}
export function time(params) {
return core._isoTime(ZodISOTime, params);
}
export function duration(params) {
return core._isoDuration(ZodISODuration, params);
}
+7
View File
@@ -0,0 +1,7 @@
{
"type": "module",
"main": "./index.cjs",
"module": "./index.js",
"types": "./index.d.cts",
"sideEffects": false
}
+63
View File
@@ -0,0 +1,63 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.safeDecodeAsync = exports.safeEncodeAsync = exports.safeDecode = exports.safeEncode = exports.decodeAsync = exports.encodeAsync = exports.decode = exports.encode = exports.validateAsync = exports.validate = exports.safeParseAsync = exports.safeParse = exports.parseAsync = exports.parse = void 0;
const core = __importStar(require("../core/index.cjs"));
const errors_js_1 = require("./errors.cjs");
exports.parse = core._parse(errors_js_1.ZodRealError);
exports.parseAsync = core._parseAsync(errors_js_1.ZodRealError);
exports.safeParse = core._safeParse(errors_js_1.ZodRealError);
exports.safeParseAsync = core._safeParseAsync(errors_js_1.ZodRealError);
var index_js_1 = require("../core/index.cjs");
Object.defineProperty(exports, "validate", { enumerable: true, get: function () { return index_js_1.validate; } });
Object.defineProperty(exports, "validateAsync", { enumerable: true, get: function () { return index_js_1.validateAsync; } });
// Codec functions
exports.encode = core._encode(errors_js_1.ZodRealError);
exports.decode = core._decode(errors_js_1.ZodRealError);
exports.encodeAsync = core._encodeAsync(errors_js_1.ZodRealError);
exports.decodeAsync = core._decodeAsync(errors_js_1.ZodRealError);
exports.safeEncode = core._safeEncode(errors_js_1.ZodRealError);
exports.safeDecode = core._safeDecode(errors_js_1.ZodRealError);
exports.safeEncodeAsync = core._safeEncodeAsync(errors_js_1.ZodRealError);
exports.safeDecodeAsync = core._safeDecodeAsync(errors_js_1.ZodRealError);
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
+44
View File
@@ -0,0 +1,44 @@
import * as core from "../core/index.cjs";
import { type ZodError } from "./errors.cjs";
export type ZodSafeParseResult<T> = ZodSafeParseSuccess<T> | ZodSafeParseError<T>;
export type ZodSafeParseSuccess<T> = {
success: true;
data: T;
error?: never;
};
export type ZodSafeParseError<T> = {
success: false;
data?: never;
error: ZodError<T>;
};
export declare const parse: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.output<T>;
export declare const parseAsync: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.output<T>>;
export declare const safeParse: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.output<T>>;
export declare const safeParseAsync: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.output<T>>>;
export { validate, validateAsync } from "../core/index.cjs";
export declare const encode: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.input<T>;
export declare const decode: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.output<T>;
export declare const encodeAsync: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.input<T>>;
export declare const decodeAsync: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.output<T>>;
export declare const safeEncode: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.input<T>>;
export declare const safeDecode: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.output<T>>;
export declare const safeEncodeAsync: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.input<T>>>;
export declare const safeDecodeAsync: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.output<T>>>;
+44
View File
@@ -0,0 +1,44 @@
import * as core from "../core/index.js";
import { type ZodError } from "./errors.js";
export type ZodSafeParseResult<T> = ZodSafeParseSuccess<T> | ZodSafeParseError<T>;
export type ZodSafeParseSuccess<T> = {
success: true;
data: T;
error?: never;
};
export type ZodSafeParseError<T> = {
success: false;
data?: never;
error: ZodError<T>;
};
export declare const parse: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.output<T>;
export declare const parseAsync: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.output<T>>;
export declare const safeParse: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.output<T>>;
export declare const safeParseAsync: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.output<T>>>;
export { validate, validateAsync } from "../core/index.js";
export declare const encode: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.input<T>;
export declare const decode: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.output<T>;
export declare const encodeAsync: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.input<T>>;
export declare const decodeAsync: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.output<T>>;
export declare const safeEncode: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.input<T>>;
export declare const safeDecode: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.output<T>>;
export declare const safeEncodeAsync: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.input<T>>>;
export declare const safeDecodeAsync: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.output<T>>>;
+16
View File
@@ -0,0 +1,16 @@
import * as core from "../core/index.js";
import { ZodRealError } from "./errors.js";
export const parse = /* @__PURE__ */ core._parse(ZodRealError);
export const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);
export const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);
export const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);
export { validate, validateAsync } from "../core/index.js";
// Codec functions
export const encode = /* @__PURE__ */ core._encode(ZodRealError);
export const decode = /* @__PURE__ */ core._decode(ZodRealError);
export const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);
export const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);
export const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);
export const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);
export const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);
export const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);
+1676
View File
File diff suppressed because it is too large Load Diff
+816
View File
@@ -0,0 +1,816 @@
import type { $ZodBigIntFormats } from "../core/checks.cjs";
import * as core from "../core/index.cjs";
import { util, type $ZodNumberFormats } from "../core/index.cjs";
import type { StandardSchemaWithJSONProps } from "../core/standard-schema.cjs";
import * as parse from "./parse.cjs";
export type ZodStandardSchemaWithJSON<T> = StandardSchemaWithJSONProps<core.input<T>, core.output<T>>;
export interface ZodType<out Output = unknown, out Input = unknown, out Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> extends core.$ZodType<Output, Input, Internals> {
def: Internals["def"];
type: Internals["def"]["type"];
/** @deprecated Use `.def` instead. */
_def: Internals["def"];
/** @deprecated Use `z.output<typeof schema>` instead. */
_output: Internals["output"];
/** @deprecated Use `z.input<typeof schema>` instead. */
_input: Internals["input"];
"~standard": ZodStandardSchemaWithJSON<this>;
/** Converts this schema to a JSON Schema representation. */
toJSONSchema(params?: core.ToJSONSchemaParams): core.ZodStandardJSONSchemaPayload<this>;
check(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
with(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
clone(def?: Internals["def"], params?: {
parent: boolean;
}): this;
register<R extends core.$ZodRegistry>(registry: R, ...meta: this extends R["_schema"] ? undefined extends R["_meta"] ? [core.$replace<R["_meta"], this>?] : [core.$replace<R["_meta"], this>] : ["Incompatible schema"]): this;
brand<T extends PropertyKey = PropertyKey, Dir extends "in" | "out" | "inout" = "out">(value?: T): PropertyKey extends T ? this : core.$ZodBranded<this, T, Dir>;
parse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
safeParse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
parseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
safeParseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
spa: (data: unknown, params?: core.ParseContext<core.$ZodIssue>) => Promise<parse.ZodSafeParseResult<core.output<this>>>;
validate(data: unknown, params?: core.ParseContext<core.$ZodIssue>): data is core.input<this>;
validateAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<boolean>;
encode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): core.input<this>;
decode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
encodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.input<this>>;
decodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
safeEncode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.input<this>>;
safeDecode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
safeEncodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.input<this>>>;
safeDecodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
refine<Ch extends (arg: core.output<this>) => unknown | Promise<unknown>>(check: Ch, params?: string | core.$ZodCustomParams): Ch extends (arg: any) => arg is infer R ? this & ZodType<R, core.input<this>> : this;
superRefine(refinement: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): this;
overwrite(fn: (x: core.output<this>) => core.output<this>): this;
optional(): ZodOptional<this>;
exactOptional(): ZodExactOptional<this>;
nonoptional(params?: string | core.$ZodNonOptionalParams): ZodNonOptional<this>;
nullable(): ZodNullable<this>;
nullish(): ZodOptional<ZodNullable<this>>;
default(def: util.NoUndefined<core.output<this>>): ZodDefault<this>;
default(def: () => util.NoUndefined<core.output<this>>): ZodDefault<this>;
prefault(def: () => core.input<this>): ZodPrefault<this>;
prefault(def: core.input<this>): ZodPrefault<this>;
array(): ZodArray<this>;
or<T extends core.SomeType>(option: T): ZodUnion<[this, T]>;
and<T extends core.SomeType>(incoming: T): ZodIntersection<this, T>;
transform<NewOut>(transform: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => NewOut | Promise<NewOut>): ZodPipe<this, ZodTransform<Awaited<NewOut>, core.output<this>>>;
catch(def: core.output<this>): ZodCatch<this>;
catch(def: (ctx: core.$ZodCatchCtx) => core.output<this>): ZodCatch<this>;
pipe<T extends core.$ZodType<any, core.output<this>>>(target: T | core.$ZodType<any, core.output<this>>): ZodPipe<this, T>;
readonly(): ZodReadonly<this>;
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified description */
describe(description: string): this;
description?: string;
/** Returns the metadata associated with this instance in `z.globalRegistry` */
meta(): core.$replace<core.GlobalMeta, this> | undefined;
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified metadata */
meta(data: core.$replace<core.GlobalMeta, this>): this;
/** @deprecated Try safe-parsing `undefined` (this is what `isOptional` does internally):
*
* ```ts
* const schema = z.string().optional();
* const isOptional = schema.safeParse(undefined).success; // true
* ```
*/
isOptional(): boolean;
/**
* @deprecated Try safe-parsing `null` (this is what `isNullable` does internally):
*
* ```ts
* const schema = z.string().nullable();
* const isNullable = schema.safeParse(null).success; // true
* ```
*/
isNullable(): boolean;
apply<T, TArgs extends unknown[] = []>(fn: (schema: this, ...args: TArgs) => T, ...args: TArgs): T;
}
export interface _ZodType<out Internals extends core.$ZodTypeInternals = core.$ZodTypeInternals> extends ZodType<any, any, Internals> {
}
export declare const ZodType: core.$constructor<ZodType>;
export interface _ZodString<T extends core.$ZodStringInternals<unknown> = core.$ZodStringInternals<unknown>> extends _ZodType<T> {
format: string | null;
minLength: number | null;
maxLength: number | null;
regex(regex: RegExp, params?: string | core.$ZodCheckRegexParams): this;
includes(value: string, params?: string | core.$ZodCheckIncludesParams): this;
startsWith(value: string, params?: string | core.$ZodCheckStartsWithParams): this;
endsWith(value: string, params?: string | core.$ZodCheckEndsWithParams): this;
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
lowercase(params?: string | core.$ZodCheckLowerCaseParams): this;
uppercase(params?: string | core.$ZodCheckUpperCaseParams): this;
trim(): this;
normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): this;
toLowerCase(): this;
toUpperCase(): this;
slugify(): this;
}
/** @internal */
export declare const _ZodString: core.$constructor<_ZodString>;
export interface ZodString extends _ZodString<core.$ZodStringInternals<string>> {
/** @deprecated Use `z.email()` instead. */
email(params?: string | core.$ZodCheckEmailParams): this;
/** @deprecated Use `z.url()` instead. */
url(params?: string | core.$ZodCheckURLParams): this;
/** @deprecated Use `z.jwt()` instead. */
jwt(params?: string | core.$ZodCheckJWTParams): this;
/** @deprecated Use `z.emoji()` instead. */
emoji(params?: string | core.$ZodCheckEmojiParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuid(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv4(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv6(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv7(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.nanoid()` instead. */
nanoid(params?: string | core.$ZodCheckNanoIDParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use `z.cuid2()` instead.
* See https://github.com/paralleldrive/cuid.
*/
cuid(params?: string | core.$ZodCheckCUIDParams): this;
/** @deprecated Use `z.cuid2()` instead. */
cuid2(params?: string | core.$ZodCheckCUID2Params): this;
/** @deprecated Use `z.ulid()` instead. */
ulid(params?: string | core.$ZodCheckULIDParams): this;
/** @deprecated Use `z.base64()` instead. */
base64(params?: string | core.$ZodCheckBase64Params): this;
/** @deprecated Use `z.base64url()` instead. */
base64url(params?: string | core.$ZodCheckBase64URLParams): this;
/** @deprecated Use `z.xid()` instead. */
xid(params?: string | core.$ZodCheckXIDParams): this;
/** @deprecated Use `z.ksuid()` instead. */
ksuid(params?: string | core.$ZodCheckKSUIDParams): this;
/** @deprecated Use `z.ipv4()` instead. */
ipv4(params?: string | core.$ZodCheckIPv4Params): this;
/** @deprecated Use `z.ipv6()` instead. */
ipv6(params?: string | core.$ZodCheckIPv6Params): this;
/** @deprecated Use `z.cidrv4()` instead. */
cidrv4(params?: string | core.$ZodCheckCIDRv4Params): this;
/** @deprecated Use `z.cidrv6()` instead. */
cidrv6(params?: string | core.$ZodCheckCIDRv6Params): this;
/** @deprecated Use `z.e164()` instead. */
e164(params?: string | core.$ZodCheckE164Params): this;
/** @deprecated Use `z.iso.datetime()` instead. */
datetime(params?: string | core.$ZodCheckISODateTimeParams): this;
/** @deprecated Use `z.iso.date()` instead. */
date(params?: string | core.$ZodCheckISODateParams): this;
/** @deprecated Use `z.iso.time()` instead. */
time(params?: string | core.$ZodCheckISOTimeParams): this;
/** @deprecated Use `z.iso.duration()` instead. */
duration(params?: string | core.$ZodCheckISODurationParams): this;
}
export declare const ZodString: core.$constructor<ZodString>;
export declare function string(params?: string | core.$ZodStringParams): ZodString;
export declare function string<T extends string>(params?: string | core.$ZodStringParams): core.$ZodType<T, T>;
export interface ZodStringFormat<Format extends string = string> extends _ZodString<core.$ZodStringFormatInternals<Format>> {
}
export declare const ZodStringFormat: core.$constructor<ZodStringFormat>;
export interface ZodISODateTime extends ZodStringFormat {
_zod: core.$ZodISODateTimeInternals;
}
export declare const ZodISODateTime: core.$constructor<ZodISODateTime>;
export interface ZodISODate extends ZodStringFormat {
_zod: core.$ZodISODateInternals;
}
export declare const ZodISODate: core.$constructor<ZodISODate>;
export interface ZodISOTime extends ZodStringFormat {
_zod: core.$ZodISOTimeInternals;
}
export declare const ZodISOTime: core.$constructor<ZodISOTime>;
export interface ZodISODuration extends ZodStringFormat {
_zod: core.$ZodISODurationInternals;
}
export declare const ZodISODuration: core.$constructor<ZodISODuration>;
export interface ZodEmail extends ZodStringFormat<"email"> {
_zod: core.$ZodEmailInternals;
}
export declare const ZodEmail: core.$constructor<ZodEmail>;
export declare function email(params?: string | core.$ZodEmailParams): ZodEmail;
export interface ZodGUID extends ZodStringFormat<"guid"> {
_zod: core.$ZodGUIDInternals;
}
export declare const ZodGUID: core.$constructor<ZodGUID>;
export declare function guid(params?: string | core.$ZodGUIDParams): ZodGUID;
export interface ZodUUID extends ZodStringFormat<"uuid"> {
_zod: core.$ZodUUIDInternals;
}
export declare const ZodUUID: core.$constructor<ZodUUID>;
export declare function uuid(params?: string | core.$ZodUUIDParams): ZodUUID;
export declare function uuidv4(params?: string | core.$ZodUUIDv4Params): ZodUUID;
export declare function uuidv6(params?: string | core.$ZodUUIDv6Params): ZodUUID;
export declare function uuidv7(params?: string | core.$ZodUUIDv7Params): ZodUUID;
export interface ZodURL extends ZodStringFormat<"url"> {
_zod: core.$ZodURLInternals;
}
export declare const ZodURL: core.$constructor<ZodURL>;
export declare function url(params?: string | core.$ZodURLParams): ZodURL;
export declare function httpUrl(params?: string | Omit<core.$ZodURLParams, "protocol" | "hostname">): ZodURL;
export interface ZodEmoji extends ZodStringFormat<"emoji"> {
_zod: core.$ZodEmojiInternals;
}
export declare const ZodEmoji: core.$constructor<ZodEmoji>;
export declare function emoji(params?: string | core.$ZodEmojiParams): ZodEmoji;
export interface ZodNanoID extends ZodStringFormat<"nanoid"> {
_zod: core.$ZodNanoIDInternals;
}
export declare const ZodNanoID: core.$constructor<ZodNanoID>;
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export interface ZodCUID extends ZodStringFormat<"cuid"> {
_zod: core.$ZodCUIDInternals;
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const ZodCUID: core.$constructor<ZodCUID>;
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodCUID;
export interface ZodCUID2 extends ZodStringFormat<"cuid2"> {
_zod: core.$ZodCUID2Internals;
}
export declare const ZodCUID2: core.$constructor<ZodCUID2>;
export declare function cuid2(params?: string | core.$ZodCUID2Params): ZodCUID2;
export interface ZodULID extends ZodStringFormat<"ulid"> {
_zod: core.$ZodULIDInternals;
}
export declare const ZodULID: core.$constructor<ZodULID>;
export declare function ulid(params?: string | core.$ZodULIDParams): ZodULID;
export interface ZodXID extends ZodStringFormat<"xid"> {
_zod: core.$ZodXIDInternals;
}
export declare const ZodXID: core.$constructor<ZodXID>;
export declare function xid(params?: string | core.$ZodXIDParams): ZodXID;
export interface ZodKSUID extends ZodStringFormat<"ksuid"> {
_zod: core.$ZodKSUIDInternals;
}
export declare const ZodKSUID: core.$constructor<ZodKSUID>;
export declare function ksuid(params?: string | core.$ZodKSUIDParams): ZodKSUID;
export interface ZodIPv4 extends ZodStringFormat<"ipv4"> {
_zod: core.$ZodIPv4Internals;
}
export declare const ZodIPv4: core.$constructor<ZodIPv4>;
export declare function ipv4(params?: string | core.$ZodIPv4Params): ZodIPv4;
export interface ZodMAC extends ZodStringFormat<"mac"> {
_zod: core.$ZodMACInternals;
}
export declare const ZodMAC: core.$constructor<ZodMAC>;
export declare function mac(params?: string | core.$ZodMACParams): ZodMAC;
export interface ZodIPv6 extends ZodStringFormat<"ipv6"> {
_zod: core.$ZodIPv6Internals;
}
export declare const ZodIPv6: core.$constructor<ZodIPv6>;
export declare function ipv6(params?: string | core.$ZodIPv6Params): ZodIPv6;
export interface ZodCIDRv4 extends ZodStringFormat<"cidrv4"> {
_zod: core.$ZodCIDRv4Internals;
}
export declare const ZodCIDRv4: core.$constructor<ZodCIDRv4>;
export declare function cidrv4(params?: string | core.$ZodCIDRv4Params): ZodCIDRv4;
export interface ZodCIDRv6 extends ZodStringFormat<"cidrv6"> {
_zod: core.$ZodCIDRv6Internals;
}
export declare const ZodCIDRv6: core.$constructor<ZodCIDRv6>;
export declare function cidrv6(params?: string | core.$ZodCIDRv6Params): ZodCIDRv6;
export interface ZodBase64 extends ZodStringFormat<"base64"> {
_zod: core.$ZodBase64Internals;
}
export declare const ZodBase64: core.$constructor<ZodBase64>;
export declare function base64(params?: string | core.$ZodBase64Params): ZodBase64;
export interface ZodBase64URL extends ZodStringFormat<"base64url"> {
_zod: core.$ZodBase64URLInternals;
}
export declare const ZodBase64URL: core.$constructor<ZodBase64URL>;
export declare function base64url(params?: string | core.$ZodBase64URLParams): ZodBase64URL;
export interface ZodE164 extends ZodStringFormat<"e164"> {
_zod: core.$ZodE164Internals;
}
export declare const ZodE164: core.$constructor<ZodE164>;
export declare function e164(params?: string | core.$ZodE164Params): ZodE164;
export interface ZodCreditCard extends ZodStringFormat<"credit_card"> {
_zod: core.$ZodCreditCardInternals;
}
export declare const ZodCreditCard: core.$constructor<ZodCreditCard>;
export declare function creditCard(params?: string | core.$ZodCreditCardParams): ZodCreditCard;
export interface ZodIBAN extends ZodStringFormat<"iban"> {
_zod: core.$ZodIBANInternals;
}
export declare const ZodIBAN: core.$constructor<ZodIBAN>;
export declare function iban(params?: string | core.$ZodIBANParams): ZodIBAN;
export interface ZodJWT extends ZodStringFormat<"jwt"> {
_zod: core.$ZodJWTInternals;
}
export declare const ZodJWT: core.$constructor<ZodJWT>;
export declare function jwt(params?: string | core.$ZodJWTParams): ZodJWT;
export interface ZodCustomStringFormat<Format extends string = string> extends ZodStringFormat<Format>, core.$ZodCustomStringFormat<Format> {
_zod: core.$ZodCustomStringFormatInternals<Format>;
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodCustomStringFormat: core.$constructor<ZodCustomStringFormat>;
export declare function stringFormat<Format extends string>(format: Format, fnOrRegex: ((arg: string) => util.MaybeAsync<unknown>) | RegExp, _params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<Format>;
export declare function hostname(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hostname">;
export declare function hex(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hex">;
export declare function currencyCode(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"currency_code">;
export declare function hash<Alg extends util.HashAlgorithm, Enc extends util.HashEncoding = "hex">(alg: Alg, params?: {
enc?: Enc;
} & core.$ZodStringFormatParams): ZodCustomStringFormat<`${Alg}_${Enc}`>;
export interface _ZodNumber<Internals extends core.$ZodNumberInternals = core.$ZodNumberInternals> extends _ZodType<Internals> {
gt(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Identical to .min() */
gte(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
min(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
lt(value: number, params?: string | core.$ZodCheckLessThanParams): this;
/** Identical to .max() */
lte(value: number, params?: string | core.$ZodCheckLessThanParams): this;
max(value: number, params?: string | core.$ZodCheckLessThanParams): this;
/** Consider `z.int()` instead. This API is considered *legacy*; it will never be removed but a better alternative exists. */
int(params?: string | core.$ZodCheckNumberFormatParams): this;
/** @deprecated This is now identical to `.int()`. Only numbers in the safe integer range are accepted. */
safe(params?: string | core.$ZodCheckNumberFormatParams): this;
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
negative(params?: string | core.$ZodCheckLessThanParams): this;
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
multipleOf(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
/** @deprecated Use `.multipleOf()` instead. */
step(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
/** @deprecated In v4 and later, z.number() does not allow infinite values by default. This is a no-op. */
finite(params?: unknown): this;
minValue: number | null;
maxValue: number | null;
/** @deprecated Check the `format` property instead. */
isInt: boolean;
/** @deprecated Number schemas no longer accept infinite values, so this always returns `true`. */
isFinite: boolean;
format: string | null;
}
export interface ZodNumber extends _ZodNumber<core.$ZodNumberInternals<number>> {
}
export declare const ZodNumber: core.$constructor<ZodNumber>;
export declare function number(params?: string | core.$ZodNumberParams): ZodNumber;
export interface ZodNumberFormat<Format extends $ZodNumberFormats = $ZodNumberFormats> extends ZodNumber {
_zod: core.$ZodNumberFormatInternals<Format>;
}
export declare const ZodNumberFormat: core.$constructor<ZodNumberFormat>;
export interface ZodInt extends ZodNumberFormat<"safeint"> {
}
export declare function int(params?: string | core.$ZodCheckNumberFormatParams): ZodInt;
export interface ZodFloat32 extends ZodNumberFormat<"float32"> {
}
export declare function float32(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat32;
export interface ZodFloat64 extends ZodNumberFormat<"float64"> {
}
export declare function float64(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat64;
export interface ZodInt32 extends ZodNumberFormat<"int32"> {
}
export declare function int32(params?: string | core.$ZodCheckNumberFormatParams): ZodInt32;
export interface ZodUInt32 extends ZodNumberFormat<"uint32"> {
}
export declare function uint32(params?: string | core.$ZodCheckNumberFormatParams): ZodUInt32;
export interface _ZodBoolean<T extends core.$ZodBooleanInternals = core.$ZodBooleanInternals> extends _ZodType<T> {
}
export interface ZodBoolean extends _ZodBoolean<core.$ZodBooleanInternals<boolean>> {
}
export declare const ZodBoolean: core.$constructor<ZodBoolean>;
export declare function boolean(params?: string | core.$ZodBooleanParams): ZodBoolean;
export interface _ZodBigInt<T extends core.$ZodBigIntInternals = core.$ZodBigIntInternals> extends _ZodType<T> {
gte(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Alias of `.gte()` */
min(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
gt(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Alias of `.lte()` */
lte(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
max(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
lt(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
negative(params?: string | core.$ZodCheckLessThanParams): this;
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
multipleOf(value: bigint, params?: string | core.$ZodCheckMultipleOfParams): this;
minValue: bigint | null;
maxValue: bigint | null;
format: string | null;
}
export interface ZodBigInt extends _ZodBigInt<core.$ZodBigIntInternals<bigint>> {
}
export declare const ZodBigInt: core.$constructor<ZodBigInt>;
export declare function bigint(params?: string | core.$ZodBigIntParams): ZodBigInt;
export interface ZodBigIntFormat<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends ZodBigInt {
_zod: core.$ZodBigIntFormatInternals<Format>;
}
export declare const ZodBigIntFormat: core.$constructor<ZodBigIntFormat>;
export interface ZodInt64 extends ZodBigIntFormat<"int64"> {
}
export declare function int64(params?: string | core.$ZodBigIntFormatParams): ZodInt64;
export interface ZodUInt64 extends ZodBigIntFormat<"uint64"> {
}
export declare function uint64(params?: string | core.$ZodBigIntFormatParams): ZodUInt64;
export interface ZodSymbol extends _ZodType<core.$ZodSymbolInternals> {
}
export declare const ZodSymbol: core.$constructor<ZodSymbol>;
export declare function symbol(params?: string | core.$ZodSymbolParams): ZodSymbol;
export interface ZodUndefined extends _ZodType<core.$ZodUndefinedInternals> {
}
export declare const ZodUndefined: core.$constructor<ZodUndefined>;
declare function _undefined(params?: string | core.$ZodUndefinedParams): ZodUndefined;
export { _undefined as undefined };
export interface ZodNull extends _ZodType<core.$ZodNullInternals> {
}
export declare const ZodNull: core.$constructor<ZodNull>;
declare function _null(params?: string | core.$ZodNullParams): ZodNull;
export { _null as null };
export interface ZodAny extends _ZodType<core.$ZodAnyInternals> {
}
export declare const ZodAny: core.$constructor<ZodAny>;
export declare function any(): ZodAny;
export interface ZodUnknown extends _ZodType<core.$ZodUnknownInternals> {
}
export declare const ZodUnknown: core.$constructor<ZodUnknown>;
export declare function unknown(): ZodUnknown;
export interface ZodNever extends _ZodType<core.$ZodNeverInternals> {
}
export declare const ZodNever: core.$constructor<ZodNever>;
export declare function never(params?: string | core.$ZodNeverParams): ZodNever;
export interface ZodVoid extends _ZodType<core.$ZodVoidInternals> {
}
export declare const ZodVoid: core.$constructor<ZodVoid>;
declare function _void(params?: string | core.$ZodVoidParams): ZodVoid;
export { _void as void };
export interface _ZodDate<T extends core.$ZodDateInternals = core.$ZodDateInternals> extends _ZodType<T> {
min(value: number | Date, params?: string | core.$ZodCheckGreaterThanParams): this;
max(value: number | Date, params?: string | core.$ZodCheckLessThanParams): this;
/** @deprecated Not recommended. */
minDate: Date | null;
/** @deprecated Not recommended. */
maxDate: Date | null;
}
export interface ZodDate extends _ZodDate<core.$ZodDateInternals<Date>> {
}
export declare const ZodDate: core.$constructor<ZodDate>;
export declare function date(params?: string | core.$ZodDateParams): ZodDate;
export interface ZodArray<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodArrayInternals<T>>, core.$ZodArray<T> {
element: T;
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
unwrap(): T;
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodArray: core.$constructor<ZodArray>;
export declare function array<T extends core.SomeType>(element: T, params?: string | core.$ZodArrayParams): ZodArray<T>;
export declare function keyof<T extends ZodObject>(schema: T): ZodEnum<util.KeysEnum<T["_zod"]["output"]>>;
export type SafeExtendShape<Base extends core.$ZodShape, Ext extends core.$ZodLooseShape> = {
[K in keyof Ext]: K extends keyof Base ? core.output<Ext[K]> extends core.output<Base[K]> ? core.input<Ext[K]> extends core.input<Base[K]> ? Ext[K] : never : never : Ext[K];
};
export interface ZodObject<
/** @ts-ignore Cast variance */
out Shape extends core.$ZodShape = core.$ZodLooseShape, out Config extends core.$ZodObjectConfig = core.$strip> extends _ZodType<core.$ZodObjectInternals<Shape, Config>>, core.$ZodObject<Shape, Config> {
"~standard": ZodStandardSchemaWithJSON<this>;
shape: Shape;
keyof(): ZodEnum<util.ToEnum<keyof Shape & string>>;
/** Define a schema to validate all unrecognized keys. This overrides the existing strict/loose behavior. */
catchall<T extends core.SomeType>(schema: T): ZodObject<Shape, core.$catchall<T>>;
/** @deprecated Use `z.looseObject()` or `.loose()` instead. */
passthrough(): ZodObject<Shape, core.$loose>;
/** Consider `z.looseObject(A.shape)` instead */
loose(): ZodObject<Shape, core.$loose>;
/** Consider `z.strictObject(A.shape)` instead */
strict(): ZodObject<Shape, core.$strict>;
/** This is the default behavior. This method call is likely unnecessary. */
strip(): ZodObject<Shape, core.$strip>;
extend<U extends core.$ZodLooseShape>(shape: U): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
safeExtend<U extends core.$ZodLooseShape>(shape: SafeExtendShape<Shape, U> & Partial<Record<keyof Shape, core.SomeType>>): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
/**
* @deprecated Use [`A.extend(B.shape)`](https://zod.dev/api?id=extend) instead.
*/
merge<U extends ZodObject>(other: U): ZodObject<util.Extend<Shape, U["shape"]>, U["_zod"]["config"]>;
pick<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Pick<Shape, Extract<keyof Shape, keyof M>>>, Config>;
omit<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Omit<Shape, Extract<keyof Shape, keyof M>>>, Config>;
partial(): ZodObject<{
-readonly [k in keyof Shape]: ZodOptional<Shape[k]>;
}, Config>;
partial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodOptional<Shape[k]> : Shape[k];
}, Config>;
exactPartial(): ZodObject<{
-readonly [k in keyof Shape]: ZodExactOptional<Shape[k]>;
}, Config>;
exactPartial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodExactOptional<Shape[k]> : Shape[k];
}, Config>;
required(): ZodObject<{
-readonly [k in keyof Shape]: ZodNonOptional<Shape[k]>;
}, Config>;
required<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodNonOptional<Shape[k]> : Shape[k];
}, Config>;
}
export declare const ZodObject: core.$constructor<ZodObject>;
export declare function object<T extends core.$ZodLooseShape = Partial<Record<never, core.SomeType>>>(shape?: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$loose>;
export interface ZodUnion<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodUnionInternals<T>>, core.$ZodUnion<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
}
export declare const ZodUnion: core.$constructor<ZodUnion>;
export declare function union<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodUnionParams): ZodUnion<T>;
export interface ZodXor<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodXorInternals<T>>, core.$ZodXor<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
}
export declare const ZodXor: core.$constructor<ZodXor>;
/** Creates an exclusive union (XOR) where exactly one option must match.
* Unlike regular unions that succeed when any option matches, xor fails if
* zero or more than one option matches the input. */
export declare function xor<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodXorParams): ZodXor<T>;
export interface ZodDiscriminatedUnion<Options extends readonly core.SomeType[] = readonly core.$ZodType[], Disc extends string = string> extends ZodUnion<Options>, core.$ZodDiscriminatedUnion<Options, Disc> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodDiscriminatedUnionInternals<Options, Disc>;
def: core.$ZodDiscriminatedUnionDef<Options, Disc>;
}
export declare const ZodDiscriminatedUnion: core.$constructor<ZodDiscriminatedUnion>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable, ...core.$ZodTypeDiscriminable[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodDiscriminatedUnion<Types, Disc>;
export interface ZodIntersection<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodIntersectionInternals<A, B>>, core.$ZodIntersection<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodIntersection: core.$constructor<ZodIntersection>;
export declare function intersection<T extends core.SomeType, U extends core.SomeType>(left: T, right: U): ZodIntersection<T, U>;
export interface ZodTuple<T extends util.TupleItems = readonly core.$ZodType[], Rest extends core.SomeType | null = core.$ZodType | null> extends _ZodType<core.$ZodTupleInternals<T, Rest>>, core.$ZodTuple<T, Rest> {
"~standard": ZodStandardSchemaWithJSON<this>;
rest<Rest extends core.SomeType = core.$ZodType>(rest: Rest): ZodTuple<T, Rest>;
partial(): ZodTuple<{
-readonly [k in keyof T]: ZodOptional<T[k]>;
}, Rest>;
}
export declare const ZodTuple: core.$constructor<ZodTuple>;
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]]>(items: T, params?: string | core.$ZodTupleParams): ZodTuple<T, null>;
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]], Rest extends core.SomeType>(items: T, rest: Rest, params?: string | core.$ZodTupleParams): ZodTuple<T, Rest>;
export declare function tuple(items: [], params?: string | core.$ZodTupleParams): ZodTuple<[], null>;
export interface ZodRecord<Key extends core.$ZodRecordKey = core.$ZodRecordKey, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodRecordInternals<Key, Value>>, core.$ZodRecord<Key, Value> {
"~standard": ZodStandardSchemaWithJSON<this>;
keyType: Key;
valueType: Value;
}
export declare const ZodRecord: core.$constructor<ZodRecord>;
export declare function record<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
export declare function partialRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key & core.$partial, Value>;
export declare function looseRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
export interface ZodMap<Key extends core.SomeType = core.$ZodType, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodMapInternals<Key, Value>>, core.$ZodMap<Key, Value> {
"~standard": ZodStandardSchemaWithJSON<this>;
keyType: Key;
valueType: Value;
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
}
export declare const ZodMap: core.$constructor<ZodMap>;
export declare function map<Key extends core.SomeType, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodMapParams): ZodMap<Key, Value>;
export interface ZodSet<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSetInternals<T>>, core.$ZodSet<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
}
export declare const ZodSet: core.$constructor<ZodSet>;
export declare function set<Value extends core.SomeType>(valueType: Value, params?: string | core.$ZodSetParams): ZodSet<Value>;
export interface ZodEnum<
/** @ts-ignore Cast variance */
out T extends util.EnumLike = util.EnumLike> extends _ZodType<core.$ZodEnumInternals<T>>, core.$ZodEnum<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
enum: T;
options: Array<T[keyof T]>;
extract<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Pick<T, U[number]>>>;
exclude<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Omit<T, U[number]>>>;
}
export declare const ZodEnum: core.$constructor<ZodEnum>;
declare function _enum<const T extends readonly string[]>(values: T, params?: string | core.$ZodEnumParams): ZodEnum<util.ToEnum<T[number]>>;
declare function _enum<const T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
export { _enum as enum };
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
*
* ```ts
* enum Colors { red, green, blue }
* z.enum(Colors);
* ```
*/
export declare function nativeEnum<T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
export interface ZodLiteral<T extends util.Literal = util.Literal> extends _ZodType<core.$ZodLiteralInternals<T>>, core.$ZodLiteral<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
values: Set<T>;
/** @legacy Use `.values` instead. Accessing this property will throw an error if the literal accepts multiple values. */
value: T;
}
export declare const ZodLiteral: core.$constructor<ZodLiteral>;
export declare function literal<const T extends ReadonlyArray<util.Literal>>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T[number]>;
export declare function literal<const T extends util.Literal>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T>;
export interface ZodFile extends _ZodType<core.$ZodFileInternals>, core.$ZodFile {
"~standard": ZodStandardSchemaWithJSON<this>;
min(size: number, params?: string | core.$ZodCheckMinSizeParams): this;
max(size: number, params?: string | core.$ZodCheckMaxSizeParams): this;
mime(types: util.MimeTypes | Array<util.MimeTypes>, params?: string | core.$ZodCheckMimeTypeParams): this;
}
export declare const ZodFile: core.$constructor<ZodFile>;
export declare function file(params?: string | core.$ZodFileParams): ZodFile;
export interface ZodTransform<O = unknown, I = unknown> extends _ZodType<core.$ZodTransformInternals<O, I>>, core.$ZodTransform<O, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTransform: core.$constructor<ZodTransform>;
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.$RefinementCtx) => O): ZodTransform<Awaited<O>, I>;
export interface ZodOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodOptionalInternals<T>>, core.$ZodOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodOptional: core.$constructor<ZodOptional>;
export declare function optional<T extends core.SomeType>(innerType: T): ZodOptional<T>;
export interface ZodExactOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodExactOptionalInternals<T>>, core.$ZodExactOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodExactOptional: core.$constructor<ZodExactOptional>;
export declare function exactOptional<T extends core.SomeType>(innerType: T): ZodExactOptional<T>;
export interface ZodNullable<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNullableInternals<T>>, core.$ZodNullable<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodNullable: core.$constructor<ZodNullable>;
export declare function nullable<T extends core.SomeType>(innerType: T): ZodNullable<T>;
export declare function nullish<T extends core.SomeType>(innerType: T): ZodOptional<ZodNullable<T>>;
export interface ZodDefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodDefaultInternals<T>>, core.$ZodDefault<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
/** @deprecated Use `.unwrap()` instead. */
removeDefault(): T;
}
export declare const ZodDefault: core.$constructor<ZodDefault>;
export declare function _default<T extends core.SomeType>(innerType: T, defaultValue: util.NoUndefined<core.output<T>> | (() => util.NoUndefined<core.output<T>>)): ZodDefault<T>;
export interface ZodPrefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPrefaultInternals<T>>, core.$ZodPrefault<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodPrefault: core.$constructor<ZodPrefault>;
export declare function prefault<T extends core.SomeType>(innerType: T, defaultValue: core.input<T> | (() => core.input<T>)): ZodPrefault<T>;
export interface ZodNonOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNonOptionalInternals<T>>, core.$ZodNonOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodNonOptional: core.$constructor<ZodNonOptional>;
export declare function nonoptional<T extends core.SomeType>(innerType: T, params?: string | core.$ZodNonOptionalParams): ZodNonOptional<T>;
export interface ZodSuccess<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSuccessInternals<T>>, core.$ZodSuccess<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodSuccess: core.$constructor<ZodSuccess>;
export declare function success<T extends core.SomeType>(innerType: T): ZodSuccess<T>;
export interface ZodCatch<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodCatchInternals<T>>, core.$ZodCatch<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
/** @deprecated Use `.unwrap()` instead. */
removeCatch(): T;
}
export declare const ZodCatch: core.$constructor<ZodCatch>;
declare function _catch<T extends core.SomeType>(innerType: T, catchValue: core.output<T> | ((ctx: core.$ZodCatchCtx) => core.output<T>)): ZodCatch<T>;
export { _catch as catch };
export interface ZodNaN extends _ZodType<core.$ZodNaNInternals>, core.$ZodNaN {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodNaN: core.$constructor<ZodNaN>;
export declare function nan(params?: string | core.$ZodNaNParams): ZodNaN;
export interface ZodPipe<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPipeInternals<A, B>>, core.$ZodPipe<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
in: A;
out: B;
}
export declare const ZodPipe: core.$constructor<ZodPipe>;
export declare function pipe<const A extends core.SomeType, B extends core.$ZodType<unknown, core.output<A>> = core.$ZodType<unknown, core.output<A>>>(in_: A, out: B | core.$ZodType<unknown, core.output<A>>): ZodPipe<A, B>;
export interface ZodCodec<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends ZodPipe<A, B>, core.$ZodCodec<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodCodecInternals<A, B>;
def: core.$ZodCodecDef<A, B>;
}
export declare const ZodCodec: core.$constructor<ZodCodec>;
export declare function codec<const A extends core.SomeType, B extends core.SomeType = core.$ZodType>(in_: A, out: B, params: {
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
}): ZodCodec<A, B>;
export declare function invertCodec<A extends core.SomeType, B extends core.SomeType>(codec: ZodCodec<A, B>): ZodCodec<B, A>;
export interface ZodPreprocess<B extends core.SomeType = core.$ZodType, I = unknown> extends ZodPipe<core.$ZodTransform<unknown, I>, B>, core.$ZodPreprocess<B, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodPreprocessInternals<B, I>;
def: core.$ZodPreprocessDef<B, I>;
}
export declare const ZodPreprocess: core.$constructor<ZodPreprocess>;
export interface ZodReadonly<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodReadonlyInternals<T>>, core.$ZodReadonly<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodReadonly: core.$constructor<ZodReadonly>;
export declare function readonly<T extends core.SomeType>(innerType: T): ZodReadonly<T>;
export interface ZodTemplateLiteral<Template extends string = string> extends _ZodType<core.$ZodTemplateLiteralInternals<Template>>, core.$ZodTemplateLiteral<Template> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTemplateLiteral: core.$constructor<ZodTemplateLiteral>;
export declare function templateLiteral<const Parts extends core.$ZodTemplateLiteralPart[]>(parts: Parts, params?: string | core.$ZodTemplateLiteralParams): ZodTemplateLiteral<core.$PartsToTemplateLiteral<Parts>>;
export interface ZodLazy<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodLazyInternals<T>>, core.$ZodLazy<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodLazy: core.$constructor<ZodLazy>;
export declare function lazy<T extends core.SomeType>(getter: () => T): ZodLazy<T>;
export interface ZodPromise<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPromiseInternals<T>>, core.$ZodPromise<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodPromise: core.$constructor<ZodPromise>;
export declare function promise<T extends core.SomeType>(innerType: T): ZodPromise<T>;
export interface ZodFunction<Args extends core.$ZodFunctionIn = core.$ZodFunctionIn, Returns extends core.$ZodFunctionOut = core.$ZodFunctionOut> extends _ZodType<core.$ZodFunctionInternals<Args, Returns>>, core.$ZodFunction<Args, Returns> {
"~standard": ZodStandardSchemaWithJSON<this>;
_def: core.$ZodFunctionDef<Args, Returns>;
_input: core.$InferInnerFunctionType<Args, Returns>;
_output: core.$InferOuterFunctionType<Args, Returns>;
input<const Items extends util.TupleItems, const Rest extends core.$ZodFunctionOut = core.$ZodFunctionOut>(args: Items, rest?: Rest): ZodFunction<core.$ZodTuple<Items, Rest>, Returns>;
input<NewArgs extends core.$ZodFunctionIn>(args: NewArgs): ZodFunction<NewArgs, Returns>;
input(...args: any[]): ZodFunction<any, Returns>;
output<NewReturns extends core.$ZodType>(output: NewReturns): ZodFunction<Args, NewReturns>;
}
export declare const ZodFunction: core.$constructor<ZodFunction>;
export declare function _function(): ZodFunction;
export declare function _function<const In extends ReadonlyArray<core.$ZodType>>(params: {
input: In;
}): ZodFunction<ZodTuple<In, null>, core.$ZodFunctionOut>;
export declare function _function<const In extends ReadonlyArray<core.$ZodType>, const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
input: In;
output: Out;
}): ZodFunction<ZodTuple<In, null>, Out>;
export declare function _function<const In extends core.$ZodFunctionIn = core.$ZodFunctionIn>(params: {
input: In;
}): ZodFunction<In, core.$ZodFunctionOut>;
export declare function _function<const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
output: Out;
}): ZodFunction<core.$ZodFunctionIn, Out>;
export declare function _function<In extends core.$ZodFunctionIn = core.$ZodFunctionIn, Out extends core.$ZodType = core.$ZodType>(params?: {
input: In;
output: Out;
}): ZodFunction<In, Out>;
export { _function as function };
export interface ZodCustom<O = unknown, I = unknown> extends _ZodType<core.$ZodCustomInternals<O, I>>, core.$ZodCustom<O, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodCustom: core.$constructor<ZodCustom>;
export declare function check<O = unknown>(fn: core.CheckFn<O>): core.$ZodCheck<O>;
export declare function custom<O>(fn?: (data: unknown) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodCustom<O, O>;
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
export declare const describe: typeof core.describe;
export declare const meta: typeof core.meta;
type ZodInstanceOfParams = core.Params<ZodCustom, core.$ZodIssueCustom, "type" | "check" | "checks" | "fn" | "abort" | "error" | "params" | "path">;
export interface ZodInstanceOf<T = unknown> extends ZodCustom<T, T> {
properties<Shape extends {
[k in keyof T as T[k] extends Function ? never : k]?: core.$ZodType<unknown, T[k]>;
}>(shape: Shape, params?: string | core.$ZodCheckPropertiesParams): ZodInstanceOf<T & core.$InferObjectInput<Shape, {}>>;
}
export declare const ZodInstanceOf: core.$constructor<ZodInstanceOf>;
declare function _instanceof<T extends typeof util.Class>(cls: T, params?: ZodInstanceOfParams): ZodInstanceOf<InstanceType<T>>;
export { _instanceof as instanceof };
export declare const stringbool: (_params?: string | core.$ZodStringBoolParams) => ZodCodec<ZodString, ZodBoolean>;
type _ZodJSONSchema = ZodUnion<[
ZodString,
ZodNumber,
ZodBoolean,
ZodNull,
ZodArray<ZodJSONSchema>,
ZodRecord<ZodString, ZodJSONSchema>
]>;
type _ZodJSONSchemaInternals = _ZodJSONSchema["_zod"];
export interface ZodJSONSchemaInternals extends _ZodJSONSchemaInternals {
output: util.JSONType;
input: util.JSONType;
}
export interface ZodJSONSchema extends _ZodJSONSchema {
_zod: ZodJSONSchemaInternals;
}
export declare function json(params?: string | core.$ZodCustomParams): ZodJSONSchema;
export declare function preprocess<A, U extends core.SomeType, B = unknown>(fn: (arg: B, ctx: core.$RefinementCtx) => A, schema: U): ZodPreprocess<U, B>;
+816
View File
@@ -0,0 +1,816 @@
import type { $ZodBigIntFormats } from "../core/checks.js";
import * as core from "../core/index.js";
import { util, type $ZodNumberFormats } from "../core/index.js";
import type { StandardSchemaWithJSONProps } from "../core/standard-schema.js";
import * as parse from "./parse.js";
export type ZodStandardSchemaWithJSON<T> = StandardSchemaWithJSONProps<core.input<T>, core.output<T>>;
export interface ZodType<out Output = unknown, out Input = unknown, out Internals extends core.$ZodTypeInternals<Output, Input> = core.$ZodTypeInternals<Output, Input>> extends core.$ZodType<Output, Input, Internals> {
def: Internals["def"];
type: Internals["def"]["type"];
/** @deprecated Use `.def` instead. */
_def: Internals["def"];
/** @deprecated Use `z.output<typeof schema>` instead. */
_output: Internals["output"];
/** @deprecated Use `z.input<typeof schema>` instead. */
_input: Internals["input"];
"~standard": ZodStandardSchemaWithJSON<this>;
/** Converts this schema to a JSON Schema representation. */
toJSONSchema(params?: core.ToJSONSchemaParams): core.ZodStandardJSONSchemaPayload<this>;
check(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
with(...checks: (core.CheckFn<core.output<this>> | core.$ZodCheck<core.output<this>>)[]): this;
clone(def?: Internals["def"], params?: {
parent: boolean;
}): this;
register<R extends core.$ZodRegistry>(registry: R, ...meta: this extends R["_schema"] ? undefined extends R["_meta"] ? [core.$replace<R["_meta"], this>?] : [core.$replace<R["_meta"], this>] : ["Incompatible schema"]): this;
brand<T extends PropertyKey = PropertyKey, Dir extends "in" | "out" | "inout" = "out">(value?: T): PropertyKey extends T ? this : core.$ZodBranded<this, T, Dir>;
parse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
safeParse(data: unknown, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
parseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
safeParseAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
spa: (data: unknown, params?: core.ParseContext<core.$ZodIssue>) => Promise<parse.ZodSafeParseResult<core.output<this>>>;
validate(data: unknown, params?: core.ParseContext<core.$ZodIssue>): data is core.input<this>;
validateAsync(data: unknown, params?: core.ParseContext<core.$ZodIssue>): Promise<boolean>;
encode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): core.input<this>;
decode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): core.output<this>;
encodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.input<this>>;
decodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<core.output<this>>;
safeEncode(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.input<this>>;
safeDecode(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): parse.ZodSafeParseResult<core.output<this>>;
safeEncodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.input<this>>>;
safeDecodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
refine<Ch extends (arg: core.output<this>) => unknown | Promise<unknown>>(check: Ch, params?: string | core.$ZodCustomParams): Ch extends (arg: any) => arg is infer R ? this & ZodType<R, core.input<this>> : this;
superRefine(refinement: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): this;
overwrite(fn: (x: core.output<this>) => core.output<this>): this;
optional(): ZodOptional<this>;
exactOptional(): ZodExactOptional<this>;
nonoptional(params?: string | core.$ZodNonOptionalParams): ZodNonOptional<this>;
nullable(): ZodNullable<this>;
nullish(): ZodOptional<ZodNullable<this>>;
default(def: util.NoUndefined<core.output<this>>): ZodDefault<this>;
default(def: () => util.NoUndefined<core.output<this>>): ZodDefault<this>;
prefault(def: () => core.input<this>): ZodPrefault<this>;
prefault(def: core.input<this>): ZodPrefault<this>;
array(): ZodArray<this>;
or<T extends core.SomeType>(option: T): ZodUnion<[this, T]>;
and<T extends core.SomeType>(incoming: T): ZodIntersection<this, T>;
transform<NewOut>(transform: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => NewOut | Promise<NewOut>): ZodPipe<this, ZodTransform<Awaited<NewOut>, core.output<this>>>;
catch(def: core.output<this>): ZodCatch<this>;
catch(def: (ctx: core.$ZodCatchCtx) => core.output<this>): ZodCatch<this>;
pipe<T extends core.$ZodType<any, core.output<this>>>(target: T | core.$ZodType<any, core.output<this>>): ZodPipe<this, T>;
readonly(): ZodReadonly<this>;
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified description */
describe(description: string): this;
description?: string;
/** Returns the metadata associated with this instance in `z.globalRegistry` */
meta(): core.$replace<core.GlobalMeta, this> | undefined;
/** Returns a new instance that has been registered in `z.globalRegistry` with the specified metadata */
meta(data: core.$replace<core.GlobalMeta, this>): this;
/** @deprecated Try safe-parsing `undefined` (this is what `isOptional` does internally):
*
* ```ts
* const schema = z.string().optional();
* const isOptional = schema.safeParse(undefined).success; // true
* ```
*/
isOptional(): boolean;
/**
* @deprecated Try safe-parsing `null` (this is what `isNullable` does internally):
*
* ```ts
* const schema = z.string().nullable();
* const isNullable = schema.safeParse(null).success; // true
* ```
*/
isNullable(): boolean;
apply<T, TArgs extends unknown[] = []>(fn: (schema: this, ...args: TArgs) => T, ...args: TArgs): T;
}
export interface _ZodType<out Internals extends core.$ZodTypeInternals = core.$ZodTypeInternals> extends ZodType<any, any, Internals> {
}
export declare const ZodType: core.$constructor<ZodType>;
export interface _ZodString<T extends core.$ZodStringInternals<unknown> = core.$ZodStringInternals<unknown>> extends _ZodType<T> {
format: string | null;
minLength: number | null;
maxLength: number | null;
regex(regex: RegExp, params?: string | core.$ZodCheckRegexParams): this;
includes(value: string, params?: string | core.$ZodCheckIncludesParams): this;
startsWith(value: string, params?: string | core.$ZodCheckStartsWithParams): this;
endsWith(value: string, params?: string | core.$ZodCheckEndsWithParams): this;
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
lowercase(params?: string | core.$ZodCheckLowerCaseParams): this;
uppercase(params?: string | core.$ZodCheckUpperCaseParams): this;
trim(): this;
normalize(form?: "NFC" | "NFD" | "NFKC" | "NFKD" | (string & {})): this;
toLowerCase(): this;
toUpperCase(): this;
slugify(): this;
}
/** @internal */
export declare const _ZodString: core.$constructor<_ZodString>;
export interface ZodString extends _ZodString<core.$ZodStringInternals<string>> {
/** @deprecated Use `z.email()` instead. */
email(params?: string | core.$ZodCheckEmailParams): this;
/** @deprecated Use `z.url()` instead. */
url(params?: string | core.$ZodCheckURLParams): this;
/** @deprecated Use `z.jwt()` instead. */
jwt(params?: string | core.$ZodCheckJWTParams): this;
/** @deprecated Use `z.emoji()` instead. */
emoji(params?: string | core.$ZodCheckEmojiParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuid(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv4(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv6(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.uuid()` instead. */
uuidv7(params?: string | core.$ZodCheckUUIDParams): this;
/** @deprecated Use `z.nanoid()` instead. */
nanoid(params?: string | core.$ZodCheckNanoIDParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use `z.cuid2()` instead.
* See https://github.com/paralleldrive/cuid.
*/
cuid(params?: string | core.$ZodCheckCUIDParams): this;
/** @deprecated Use `z.cuid2()` instead. */
cuid2(params?: string | core.$ZodCheckCUID2Params): this;
/** @deprecated Use `z.ulid()` instead. */
ulid(params?: string | core.$ZodCheckULIDParams): this;
/** @deprecated Use `z.base64()` instead. */
base64(params?: string | core.$ZodCheckBase64Params): this;
/** @deprecated Use `z.base64url()` instead. */
base64url(params?: string | core.$ZodCheckBase64URLParams): this;
/** @deprecated Use `z.xid()` instead. */
xid(params?: string | core.$ZodCheckXIDParams): this;
/** @deprecated Use `z.ksuid()` instead. */
ksuid(params?: string | core.$ZodCheckKSUIDParams): this;
/** @deprecated Use `z.ipv4()` instead. */
ipv4(params?: string | core.$ZodCheckIPv4Params): this;
/** @deprecated Use `z.ipv6()` instead. */
ipv6(params?: string | core.$ZodCheckIPv6Params): this;
/** @deprecated Use `z.cidrv4()` instead. */
cidrv4(params?: string | core.$ZodCheckCIDRv4Params): this;
/** @deprecated Use `z.cidrv6()` instead. */
cidrv6(params?: string | core.$ZodCheckCIDRv6Params): this;
/** @deprecated Use `z.e164()` instead. */
e164(params?: string | core.$ZodCheckE164Params): this;
/** @deprecated Use `z.iso.datetime()` instead. */
datetime(params?: string | core.$ZodCheckISODateTimeParams): this;
/** @deprecated Use `z.iso.date()` instead. */
date(params?: string | core.$ZodCheckISODateParams): this;
/** @deprecated Use `z.iso.time()` instead. */
time(params?: string | core.$ZodCheckISOTimeParams): this;
/** @deprecated Use `z.iso.duration()` instead. */
duration(params?: string | core.$ZodCheckISODurationParams): this;
}
export declare const ZodString: core.$constructor<ZodString>;
export declare function string(params?: string | core.$ZodStringParams): ZodString;
export declare function string<T extends string>(params?: string | core.$ZodStringParams): core.$ZodType<T, T>;
export interface ZodStringFormat<Format extends string = string> extends _ZodString<core.$ZodStringFormatInternals<Format>> {
}
export declare const ZodStringFormat: core.$constructor<ZodStringFormat>;
export interface ZodISODateTime extends ZodStringFormat {
_zod: core.$ZodISODateTimeInternals;
}
export declare const ZodISODateTime: core.$constructor<ZodISODateTime>;
export interface ZodISODate extends ZodStringFormat {
_zod: core.$ZodISODateInternals;
}
export declare const ZodISODate: core.$constructor<ZodISODate>;
export interface ZodISOTime extends ZodStringFormat {
_zod: core.$ZodISOTimeInternals;
}
export declare const ZodISOTime: core.$constructor<ZodISOTime>;
export interface ZodISODuration extends ZodStringFormat {
_zod: core.$ZodISODurationInternals;
}
export declare const ZodISODuration: core.$constructor<ZodISODuration>;
export interface ZodEmail extends ZodStringFormat<"email"> {
_zod: core.$ZodEmailInternals;
}
export declare const ZodEmail: core.$constructor<ZodEmail>;
export declare function email(params?: string | core.$ZodEmailParams): ZodEmail;
export interface ZodGUID extends ZodStringFormat<"guid"> {
_zod: core.$ZodGUIDInternals;
}
export declare const ZodGUID: core.$constructor<ZodGUID>;
export declare function guid(params?: string | core.$ZodGUIDParams): ZodGUID;
export interface ZodUUID extends ZodStringFormat<"uuid"> {
_zod: core.$ZodUUIDInternals;
}
export declare const ZodUUID: core.$constructor<ZodUUID>;
export declare function uuid(params?: string | core.$ZodUUIDParams): ZodUUID;
export declare function uuidv4(params?: string | core.$ZodUUIDv4Params): ZodUUID;
export declare function uuidv6(params?: string | core.$ZodUUIDv6Params): ZodUUID;
export declare function uuidv7(params?: string | core.$ZodUUIDv7Params): ZodUUID;
export interface ZodURL extends ZodStringFormat<"url"> {
_zod: core.$ZodURLInternals;
}
export declare const ZodURL: core.$constructor<ZodURL>;
export declare function url(params?: string | core.$ZodURLParams): ZodURL;
export declare function httpUrl(params?: string | Omit<core.$ZodURLParams, "protocol" | "hostname">): ZodURL;
export interface ZodEmoji extends ZodStringFormat<"emoji"> {
_zod: core.$ZodEmojiInternals;
}
export declare const ZodEmoji: core.$constructor<ZodEmoji>;
export declare function emoji(params?: string | core.$ZodEmojiParams): ZodEmoji;
export interface ZodNanoID extends ZodStringFormat<"nanoid"> {
_zod: core.$ZodNanoIDInternals;
}
export declare const ZodNanoID: core.$constructor<ZodNanoID>;
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export interface ZodCUID extends ZodStringFormat<"cuid"> {
_zod: core.$ZodCUIDInternals;
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const ZodCUID: core.$constructor<ZodCUID>;
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodCUID;
export interface ZodCUID2 extends ZodStringFormat<"cuid2"> {
_zod: core.$ZodCUID2Internals;
}
export declare const ZodCUID2: core.$constructor<ZodCUID2>;
export declare function cuid2(params?: string | core.$ZodCUID2Params): ZodCUID2;
export interface ZodULID extends ZodStringFormat<"ulid"> {
_zod: core.$ZodULIDInternals;
}
export declare const ZodULID: core.$constructor<ZodULID>;
export declare function ulid(params?: string | core.$ZodULIDParams): ZodULID;
export interface ZodXID extends ZodStringFormat<"xid"> {
_zod: core.$ZodXIDInternals;
}
export declare const ZodXID: core.$constructor<ZodXID>;
export declare function xid(params?: string | core.$ZodXIDParams): ZodXID;
export interface ZodKSUID extends ZodStringFormat<"ksuid"> {
_zod: core.$ZodKSUIDInternals;
}
export declare const ZodKSUID: core.$constructor<ZodKSUID>;
export declare function ksuid(params?: string | core.$ZodKSUIDParams): ZodKSUID;
export interface ZodIPv4 extends ZodStringFormat<"ipv4"> {
_zod: core.$ZodIPv4Internals;
}
export declare const ZodIPv4: core.$constructor<ZodIPv4>;
export declare function ipv4(params?: string | core.$ZodIPv4Params): ZodIPv4;
export interface ZodMAC extends ZodStringFormat<"mac"> {
_zod: core.$ZodMACInternals;
}
export declare const ZodMAC: core.$constructor<ZodMAC>;
export declare function mac(params?: string | core.$ZodMACParams): ZodMAC;
export interface ZodIPv6 extends ZodStringFormat<"ipv6"> {
_zod: core.$ZodIPv6Internals;
}
export declare const ZodIPv6: core.$constructor<ZodIPv6>;
export declare function ipv6(params?: string | core.$ZodIPv6Params): ZodIPv6;
export interface ZodCIDRv4 extends ZodStringFormat<"cidrv4"> {
_zod: core.$ZodCIDRv4Internals;
}
export declare const ZodCIDRv4: core.$constructor<ZodCIDRv4>;
export declare function cidrv4(params?: string | core.$ZodCIDRv4Params): ZodCIDRv4;
export interface ZodCIDRv6 extends ZodStringFormat<"cidrv6"> {
_zod: core.$ZodCIDRv6Internals;
}
export declare const ZodCIDRv6: core.$constructor<ZodCIDRv6>;
export declare function cidrv6(params?: string | core.$ZodCIDRv6Params): ZodCIDRv6;
export interface ZodBase64 extends ZodStringFormat<"base64"> {
_zod: core.$ZodBase64Internals;
}
export declare const ZodBase64: core.$constructor<ZodBase64>;
export declare function base64(params?: string | core.$ZodBase64Params): ZodBase64;
export interface ZodBase64URL extends ZodStringFormat<"base64url"> {
_zod: core.$ZodBase64URLInternals;
}
export declare const ZodBase64URL: core.$constructor<ZodBase64URL>;
export declare function base64url(params?: string | core.$ZodBase64URLParams): ZodBase64URL;
export interface ZodE164 extends ZodStringFormat<"e164"> {
_zod: core.$ZodE164Internals;
}
export declare const ZodE164: core.$constructor<ZodE164>;
export declare function e164(params?: string | core.$ZodE164Params): ZodE164;
export interface ZodCreditCard extends ZodStringFormat<"credit_card"> {
_zod: core.$ZodCreditCardInternals;
}
export declare const ZodCreditCard: core.$constructor<ZodCreditCard>;
export declare function creditCard(params?: string | core.$ZodCreditCardParams): ZodCreditCard;
export interface ZodIBAN extends ZodStringFormat<"iban"> {
_zod: core.$ZodIBANInternals;
}
export declare const ZodIBAN: core.$constructor<ZodIBAN>;
export declare function iban(params?: string | core.$ZodIBANParams): ZodIBAN;
export interface ZodJWT extends ZodStringFormat<"jwt"> {
_zod: core.$ZodJWTInternals;
}
export declare const ZodJWT: core.$constructor<ZodJWT>;
export declare function jwt(params?: string | core.$ZodJWTParams): ZodJWT;
export interface ZodCustomStringFormat<Format extends string = string> extends ZodStringFormat<Format>, core.$ZodCustomStringFormat<Format> {
_zod: core.$ZodCustomStringFormatInternals<Format>;
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodCustomStringFormat: core.$constructor<ZodCustomStringFormat>;
export declare function stringFormat<Format extends string>(format: Format, fnOrRegex: ((arg: string) => util.MaybeAsync<unknown>) | RegExp, _params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<Format>;
export declare function hostname(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hostname">;
export declare function hex(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"hex">;
export declare function currencyCode(_params?: string | core.$ZodStringFormatParams): ZodCustomStringFormat<"currency_code">;
export declare function hash<Alg extends util.HashAlgorithm, Enc extends util.HashEncoding = "hex">(alg: Alg, params?: {
enc?: Enc;
} & core.$ZodStringFormatParams): ZodCustomStringFormat<`${Alg}_${Enc}`>;
export interface _ZodNumber<Internals extends core.$ZodNumberInternals = core.$ZodNumberInternals> extends _ZodType<Internals> {
gt(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Identical to .min() */
gte(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
min(value: number, params?: string | core.$ZodCheckGreaterThanParams): this;
lt(value: number, params?: string | core.$ZodCheckLessThanParams): this;
/** Identical to .max() */
lte(value: number, params?: string | core.$ZodCheckLessThanParams): this;
max(value: number, params?: string | core.$ZodCheckLessThanParams): this;
/** Consider `z.int()` instead. This API is considered *legacy*; it will never be removed but a better alternative exists. */
int(params?: string | core.$ZodCheckNumberFormatParams): this;
/** @deprecated This is now identical to `.int()`. Only numbers in the safe integer range are accepted. */
safe(params?: string | core.$ZodCheckNumberFormatParams): this;
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
negative(params?: string | core.$ZodCheckLessThanParams): this;
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
multipleOf(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
/** @deprecated Use `.multipleOf()` instead. */
step(value: number, params?: string | core.$ZodCheckMultipleOfParams): this;
/** @deprecated In v4 and later, z.number() does not allow infinite values by default. This is a no-op. */
finite(params?: unknown): this;
minValue: number | null;
maxValue: number | null;
/** @deprecated Check the `format` property instead. */
isInt: boolean;
/** @deprecated Number schemas no longer accept infinite values, so this always returns `true`. */
isFinite: boolean;
format: string | null;
}
export interface ZodNumber extends _ZodNumber<core.$ZodNumberInternals<number>> {
}
export declare const ZodNumber: core.$constructor<ZodNumber>;
export declare function number(params?: string | core.$ZodNumberParams): ZodNumber;
export interface ZodNumberFormat<Format extends $ZodNumberFormats = $ZodNumberFormats> extends ZodNumber {
_zod: core.$ZodNumberFormatInternals<Format>;
}
export declare const ZodNumberFormat: core.$constructor<ZodNumberFormat>;
export interface ZodInt extends ZodNumberFormat<"safeint"> {
}
export declare function int(params?: string | core.$ZodCheckNumberFormatParams): ZodInt;
export interface ZodFloat32 extends ZodNumberFormat<"float32"> {
}
export declare function float32(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat32;
export interface ZodFloat64 extends ZodNumberFormat<"float64"> {
}
export declare function float64(params?: string | core.$ZodCheckNumberFormatParams): ZodFloat64;
export interface ZodInt32 extends ZodNumberFormat<"int32"> {
}
export declare function int32(params?: string | core.$ZodCheckNumberFormatParams): ZodInt32;
export interface ZodUInt32 extends ZodNumberFormat<"uint32"> {
}
export declare function uint32(params?: string | core.$ZodCheckNumberFormatParams): ZodUInt32;
export interface _ZodBoolean<T extends core.$ZodBooleanInternals = core.$ZodBooleanInternals> extends _ZodType<T> {
}
export interface ZodBoolean extends _ZodBoolean<core.$ZodBooleanInternals<boolean>> {
}
export declare const ZodBoolean: core.$constructor<ZodBoolean>;
export declare function boolean(params?: string | core.$ZodBooleanParams): ZodBoolean;
export interface _ZodBigInt<T extends core.$ZodBigIntInternals = core.$ZodBigIntInternals> extends _ZodType<T> {
gte(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Alias of `.gte()` */
min(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
gt(value: bigint, params?: string | core.$ZodCheckGreaterThanParams): this;
/** Alias of `.lte()` */
lte(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
max(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
lt(value: bigint, params?: string | core.$ZodCheckLessThanParams): this;
positive(params?: string | core.$ZodCheckGreaterThanParams): this;
negative(params?: string | core.$ZodCheckLessThanParams): this;
nonpositive(params?: string | core.$ZodCheckLessThanParams): this;
nonnegative(params?: string | core.$ZodCheckGreaterThanParams): this;
multipleOf(value: bigint, params?: string | core.$ZodCheckMultipleOfParams): this;
minValue: bigint | null;
maxValue: bigint | null;
format: string | null;
}
export interface ZodBigInt extends _ZodBigInt<core.$ZodBigIntInternals<bigint>> {
}
export declare const ZodBigInt: core.$constructor<ZodBigInt>;
export declare function bigint(params?: string | core.$ZodBigIntParams): ZodBigInt;
export interface ZodBigIntFormat<Format extends $ZodBigIntFormats = $ZodBigIntFormats> extends ZodBigInt {
_zod: core.$ZodBigIntFormatInternals<Format>;
}
export declare const ZodBigIntFormat: core.$constructor<ZodBigIntFormat>;
export interface ZodInt64 extends ZodBigIntFormat<"int64"> {
}
export declare function int64(params?: string | core.$ZodBigIntFormatParams): ZodInt64;
export interface ZodUInt64 extends ZodBigIntFormat<"uint64"> {
}
export declare function uint64(params?: string | core.$ZodBigIntFormatParams): ZodUInt64;
export interface ZodSymbol extends _ZodType<core.$ZodSymbolInternals> {
}
export declare const ZodSymbol: core.$constructor<ZodSymbol>;
export declare function symbol(params?: string | core.$ZodSymbolParams): ZodSymbol;
export interface ZodUndefined extends _ZodType<core.$ZodUndefinedInternals> {
}
export declare const ZodUndefined: core.$constructor<ZodUndefined>;
declare function _undefined(params?: string | core.$ZodUndefinedParams): ZodUndefined;
export { _undefined as undefined };
export interface ZodNull extends _ZodType<core.$ZodNullInternals> {
}
export declare const ZodNull: core.$constructor<ZodNull>;
declare function _null(params?: string | core.$ZodNullParams): ZodNull;
export { _null as null };
export interface ZodAny extends _ZodType<core.$ZodAnyInternals> {
}
export declare const ZodAny: core.$constructor<ZodAny>;
export declare function any(): ZodAny;
export interface ZodUnknown extends _ZodType<core.$ZodUnknownInternals> {
}
export declare const ZodUnknown: core.$constructor<ZodUnknown>;
export declare function unknown(): ZodUnknown;
export interface ZodNever extends _ZodType<core.$ZodNeverInternals> {
}
export declare const ZodNever: core.$constructor<ZodNever>;
export declare function never(params?: string | core.$ZodNeverParams): ZodNever;
export interface ZodVoid extends _ZodType<core.$ZodVoidInternals> {
}
export declare const ZodVoid: core.$constructor<ZodVoid>;
declare function _void(params?: string | core.$ZodVoidParams): ZodVoid;
export { _void as void };
export interface _ZodDate<T extends core.$ZodDateInternals = core.$ZodDateInternals> extends _ZodType<T> {
min(value: number | Date, params?: string | core.$ZodCheckGreaterThanParams): this;
max(value: number | Date, params?: string | core.$ZodCheckLessThanParams): this;
/** @deprecated Not recommended. */
minDate: Date | null;
/** @deprecated Not recommended. */
maxDate: Date | null;
}
export interface ZodDate extends _ZodDate<core.$ZodDateInternals<Date>> {
}
export declare const ZodDate: core.$constructor<ZodDate>;
export declare function date(params?: string | core.$ZodDateParams): ZodDate;
export interface ZodArray<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodArrayInternals<T>>, core.$ZodArray<T> {
element: T;
min(minLength: number, params?: string | core.$ZodCheckMinLengthParams): this;
nonempty(params?: string | core.$ZodCheckMinLengthParams): this;
max(maxLength: number, params?: string | core.$ZodCheckMaxLengthParams): this;
length(len: number, params?: string | core.$ZodCheckLengthEqualsParams): this;
unwrap(): T;
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodArray: core.$constructor<ZodArray>;
export declare function array<T extends core.SomeType>(element: T, params?: string | core.$ZodArrayParams): ZodArray<T>;
export declare function keyof<T extends ZodObject>(schema: T): ZodEnum<util.KeysEnum<T["_zod"]["output"]>>;
export type SafeExtendShape<Base extends core.$ZodShape, Ext extends core.$ZodLooseShape> = {
[K in keyof Ext]: K extends keyof Base ? core.output<Ext[K]> extends core.output<Base[K]> ? core.input<Ext[K]> extends core.input<Base[K]> ? Ext[K] : never : never : Ext[K];
};
export interface ZodObject<
/** @ts-ignore Cast variance */
out Shape extends core.$ZodShape = core.$ZodLooseShape, out Config extends core.$ZodObjectConfig = core.$strip> extends _ZodType<core.$ZodObjectInternals<Shape, Config>>, core.$ZodObject<Shape, Config> {
"~standard": ZodStandardSchemaWithJSON<this>;
shape: Shape;
keyof(): ZodEnum<util.ToEnum<keyof Shape & string>>;
/** Define a schema to validate all unrecognized keys. This overrides the existing strict/loose behavior. */
catchall<T extends core.SomeType>(schema: T): ZodObject<Shape, core.$catchall<T>>;
/** @deprecated Use `z.looseObject()` or `.loose()` instead. */
passthrough(): ZodObject<Shape, core.$loose>;
/** Consider `z.looseObject(A.shape)` instead */
loose(): ZodObject<Shape, core.$loose>;
/** Consider `z.strictObject(A.shape)` instead */
strict(): ZodObject<Shape, core.$strict>;
/** This is the default behavior. This method call is likely unnecessary. */
strip(): ZodObject<Shape, core.$strip>;
extend<U extends core.$ZodLooseShape>(shape: U): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
safeExtend<U extends core.$ZodLooseShape>(shape: SafeExtendShape<Shape, U> & Partial<Record<keyof Shape, core.SomeType>>): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
/**
* @deprecated Use [`A.extend(B.shape)`](https://zod.dev/api?id=extend) instead.
*/
merge<U extends ZodObject>(other: U): ZodObject<util.Extend<Shape, U["shape"]>, U["_zod"]["config"]>;
pick<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Pick<Shape, Extract<keyof Shape, keyof M>>>, Config>;
omit<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Omit<Shape, Extract<keyof Shape, keyof M>>>, Config>;
partial(): ZodObject<{
-readonly [k in keyof Shape]: ZodOptional<Shape[k]>;
}, Config>;
partial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodOptional<Shape[k]> : Shape[k];
}, Config>;
exactPartial(): ZodObject<{
-readonly [k in keyof Shape]: ZodExactOptional<Shape[k]>;
}, Config>;
exactPartial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodExactOptional<Shape[k]> : Shape[k];
}, Config>;
required(): ZodObject<{
-readonly [k in keyof Shape]: ZodNonOptional<Shape[k]>;
}, Config>;
required<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
-readonly [k in keyof Shape]: k extends keyof M ? ZodNonOptional<Shape[k]> : Shape[k];
}, Config>;
}
export declare const ZodObject: core.$constructor<ZodObject>;
export declare function object<T extends core.$ZodLooseShape = Partial<Record<never, core.SomeType>>>(shape?: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$loose>;
export interface ZodUnion<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodUnionInternals<T>>, core.$ZodUnion<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
}
export declare const ZodUnion: core.$constructor<ZodUnion>;
export declare function union<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodUnionParams): ZodUnion<T>;
export interface ZodXor<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodXorInternals<T>>, core.$ZodXor<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
}
export declare const ZodXor: core.$constructor<ZodXor>;
/** Creates an exclusive union (XOR) where exactly one option must match.
* Unlike regular unions that succeed when any option matches, xor fails if
* zero or more than one option matches the input. */
export declare function xor<const T extends readonly core.SomeType[]>(options: T, params?: string | core.$ZodXorParams): ZodXor<T>;
export interface ZodDiscriminatedUnion<Options extends readonly core.SomeType[] = readonly core.$ZodType[], Disc extends string = string> extends ZodUnion<Options>, core.$ZodDiscriminatedUnion<Options, Disc> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodDiscriminatedUnionInternals<Options, Disc>;
def: core.$ZodDiscriminatedUnionDef<Options, Disc>;
}
export declare const ZodDiscriminatedUnion: core.$constructor<ZodDiscriminatedUnion>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable, ...core.$ZodTypeDiscriminable[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodDiscriminatedUnion<Types, Disc>;
export interface ZodIntersection<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodIntersectionInternals<A, B>>, core.$ZodIntersection<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodIntersection: core.$constructor<ZodIntersection>;
export declare function intersection<T extends core.SomeType, U extends core.SomeType>(left: T, right: U): ZodIntersection<T, U>;
export interface ZodTuple<T extends util.TupleItems = readonly core.$ZodType[], Rest extends core.SomeType | null = core.$ZodType | null> extends _ZodType<core.$ZodTupleInternals<T, Rest>>, core.$ZodTuple<T, Rest> {
"~standard": ZodStandardSchemaWithJSON<this>;
rest<Rest extends core.SomeType = core.$ZodType>(rest: Rest): ZodTuple<T, Rest>;
partial(): ZodTuple<{
-readonly [k in keyof T]: ZodOptional<T[k]>;
}, Rest>;
}
export declare const ZodTuple: core.$constructor<ZodTuple>;
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]]>(items: T, params?: string | core.$ZodTupleParams): ZodTuple<T, null>;
export declare function tuple<T extends readonly [core.SomeType, ...core.SomeType[]], Rest extends core.SomeType>(items: T, rest: Rest, params?: string | core.$ZodTupleParams): ZodTuple<T, Rest>;
export declare function tuple(items: [], params?: string | core.$ZodTupleParams): ZodTuple<[], null>;
export interface ZodRecord<Key extends core.$ZodRecordKey = core.$ZodRecordKey, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodRecordInternals<Key, Value>>, core.$ZodRecord<Key, Value> {
"~standard": ZodStandardSchemaWithJSON<this>;
keyType: Key;
valueType: Value;
}
export declare const ZodRecord: core.$constructor<ZodRecord>;
export declare function record<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
export declare function partialRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key & core.$partial, Value>;
export declare function looseRecord<Key extends core.$ZodRecordKey, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodRecordParams): ZodRecord<Key, Value>;
export interface ZodMap<Key extends core.SomeType = core.$ZodType, Value extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodMapInternals<Key, Value>>, core.$ZodMap<Key, Value> {
"~standard": ZodStandardSchemaWithJSON<this>;
keyType: Key;
valueType: Value;
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
}
export declare const ZodMap: core.$constructor<ZodMap>;
export declare function map<Key extends core.SomeType, Value extends core.SomeType>(keyType: Key, valueType: Value, params?: string | core.$ZodMapParams): ZodMap<Key, Value>;
export interface ZodSet<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSetInternals<T>>, core.$ZodSet<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
min(minSize: number, params?: string | core.$ZodCheckMinSizeParams): this;
nonempty(params?: string | core.$ZodCheckMinSizeParams): this;
max(maxSize: number, params?: string | core.$ZodCheckMaxSizeParams): this;
size(size: number, params?: string | core.$ZodCheckSizeEqualsParams): this;
}
export declare const ZodSet: core.$constructor<ZodSet>;
export declare function set<Value extends core.SomeType>(valueType: Value, params?: string | core.$ZodSetParams): ZodSet<Value>;
export interface ZodEnum<
/** @ts-ignore Cast variance */
out T extends util.EnumLike = util.EnumLike> extends _ZodType<core.$ZodEnumInternals<T>>, core.$ZodEnum<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
enum: T;
options: Array<T[keyof T]>;
extract<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Pick<T, U[number]>>>;
exclude<const U extends readonly (keyof T)[]>(values: U, params?: string | core.$ZodEnumParams): ZodEnum<util.Flatten<Omit<T, U[number]>>>;
}
export declare const ZodEnum: core.$constructor<ZodEnum>;
declare function _enum<const T extends readonly string[]>(values: T, params?: string | core.$ZodEnumParams): ZodEnum<util.ToEnum<T[number]>>;
declare function _enum<const T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
export { _enum as enum };
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
*
* ```ts
* enum Colors { red, green, blue }
* z.enum(Colors);
* ```
*/
export declare function nativeEnum<T extends util.EnumLike>(entries: T, params?: string | core.$ZodEnumParams): ZodEnum<T>;
export interface ZodLiteral<T extends util.Literal = util.Literal> extends _ZodType<core.$ZodLiteralInternals<T>>, core.$ZodLiteral<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
values: Set<T>;
/** @legacy Use `.values` instead. Accessing this property will throw an error if the literal accepts multiple values. */
value: T;
}
export declare const ZodLiteral: core.$constructor<ZodLiteral>;
export declare function literal<const T extends ReadonlyArray<util.Literal>>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T[number]>;
export declare function literal<const T extends util.Literal>(value: T, params?: string | core.$ZodLiteralParams): ZodLiteral<T>;
export interface ZodFile extends _ZodType<core.$ZodFileInternals>, core.$ZodFile {
"~standard": ZodStandardSchemaWithJSON<this>;
min(size: number, params?: string | core.$ZodCheckMinSizeParams): this;
max(size: number, params?: string | core.$ZodCheckMaxSizeParams): this;
mime(types: util.MimeTypes | Array<util.MimeTypes>, params?: string | core.$ZodCheckMimeTypeParams): this;
}
export declare const ZodFile: core.$constructor<ZodFile>;
export declare function file(params?: string | core.$ZodFileParams): ZodFile;
export interface ZodTransform<O = unknown, I = unknown> extends _ZodType<core.$ZodTransformInternals<O, I>>, core.$ZodTransform<O, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTransform: core.$constructor<ZodTransform>;
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.$RefinementCtx) => O): ZodTransform<Awaited<O>, I>;
export interface ZodOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodOptionalInternals<T>>, core.$ZodOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodOptional: core.$constructor<ZodOptional>;
export declare function optional<T extends core.SomeType>(innerType: T): ZodOptional<T>;
export interface ZodExactOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodExactOptionalInternals<T>>, core.$ZodExactOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodExactOptional: core.$constructor<ZodExactOptional>;
export declare function exactOptional<T extends core.SomeType>(innerType: T): ZodExactOptional<T>;
export interface ZodNullable<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNullableInternals<T>>, core.$ZodNullable<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodNullable: core.$constructor<ZodNullable>;
export declare function nullable<T extends core.SomeType>(innerType: T): ZodNullable<T>;
export declare function nullish<T extends core.SomeType>(innerType: T): ZodOptional<ZodNullable<T>>;
export interface ZodDefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodDefaultInternals<T>>, core.$ZodDefault<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
/** @deprecated Use `.unwrap()` instead. */
removeDefault(): T;
}
export declare const ZodDefault: core.$constructor<ZodDefault>;
export declare function _default<T extends core.SomeType>(innerType: T, defaultValue: util.NoUndefined<core.output<T>> | (() => util.NoUndefined<core.output<T>>)): ZodDefault<T>;
export interface ZodPrefault<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPrefaultInternals<T>>, core.$ZodPrefault<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodPrefault: core.$constructor<ZodPrefault>;
export declare function prefault<T extends core.SomeType>(innerType: T, defaultValue: core.input<T> | (() => core.input<T>)): ZodPrefault<T>;
export interface ZodNonOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodNonOptionalInternals<T>>, core.$ZodNonOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodNonOptional: core.$constructor<ZodNonOptional>;
export declare function nonoptional<T extends core.SomeType>(innerType: T, params?: string | core.$ZodNonOptionalParams): ZodNonOptional<T>;
export interface ZodSuccess<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodSuccessInternals<T>>, core.$ZodSuccess<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodSuccess: core.$constructor<ZodSuccess>;
export declare function success<T extends core.SomeType>(innerType: T): ZodSuccess<T>;
export interface ZodCatch<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodCatchInternals<T>>, core.$ZodCatch<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
/** @deprecated Use `.unwrap()` instead. */
removeCatch(): T;
}
export declare const ZodCatch: core.$constructor<ZodCatch>;
declare function _catch<T extends core.SomeType>(innerType: T, catchValue: core.output<T> | ((ctx: core.$ZodCatchCtx) => core.output<T>)): ZodCatch<T>;
export { _catch as catch };
export interface ZodNaN extends _ZodType<core.$ZodNaNInternals>, core.$ZodNaN {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodNaN: core.$constructor<ZodNaN>;
export declare function nan(params?: string | core.$ZodNaNParams): ZodNaN;
export interface ZodPipe<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPipeInternals<A, B>>, core.$ZodPipe<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
in: A;
out: B;
}
export declare const ZodPipe: core.$constructor<ZodPipe>;
export declare function pipe<const A extends core.SomeType, B extends core.$ZodType<unknown, core.output<A>> = core.$ZodType<unknown, core.output<A>>>(in_: A, out: B | core.$ZodType<unknown, core.output<A>>): ZodPipe<A, B>;
export interface ZodCodec<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends ZodPipe<A, B>, core.$ZodCodec<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodCodecInternals<A, B>;
def: core.$ZodCodecDef<A, B>;
}
export declare const ZodCodec: core.$constructor<ZodCodec>;
export declare function codec<const A extends core.SomeType, B extends core.SomeType = core.$ZodType>(in_: A, out: B, params: {
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
}): ZodCodec<A, B>;
export declare function invertCodec<A extends core.SomeType, B extends core.SomeType>(codec: ZodCodec<A, B>): ZodCodec<B, A>;
export interface ZodPreprocess<B extends core.SomeType = core.$ZodType, I = unknown> extends ZodPipe<core.$ZodTransform<unknown, I>, B>, core.$ZodPreprocess<B, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodPreprocessInternals<B, I>;
def: core.$ZodPreprocessDef<B, I>;
}
export declare const ZodPreprocess: core.$constructor<ZodPreprocess>;
export interface ZodReadonly<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodReadonlyInternals<T>>, core.$ZodReadonly<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodReadonly: core.$constructor<ZodReadonly>;
export declare function readonly<T extends core.SomeType>(innerType: T): ZodReadonly<T>;
export interface ZodTemplateLiteral<Template extends string = string> extends _ZodType<core.$ZodTemplateLiteralInternals<Template>>, core.$ZodTemplateLiteral<Template> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTemplateLiteral: core.$constructor<ZodTemplateLiteral>;
export declare function templateLiteral<const Parts extends core.$ZodTemplateLiteralPart[]>(parts: Parts, params?: string | core.$ZodTemplateLiteralParams): ZodTemplateLiteral<core.$PartsToTemplateLiteral<Parts>>;
export interface ZodLazy<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodLazyInternals<T>>, core.$ZodLazy<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodLazy: core.$constructor<ZodLazy>;
export declare function lazy<T extends core.SomeType>(getter: () => T): ZodLazy<T>;
export interface ZodPromise<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodPromiseInternals<T>>, core.$ZodPromise<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
}
export declare const ZodPromise: core.$constructor<ZodPromise>;
export declare function promise<T extends core.SomeType>(innerType: T): ZodPromise<T>;
export interface ZodFunction<Args extends core.$ZodFunctionIn = core.$ZodFunctionIn, Returns extends core.$ZodFunctionOut = core.$ZodFunctionOut> extends _ZodType<core.$ZodFunctionInternals<Args, Returns>>, core.$ZodFunction<Args, Returns> {
"~standard": ZodStandardSchemaWithJSON<this>;
_def: core.$ZodFunctionDef<Args, Returns>;
_input: core.$InferInnerFunctionType<Args, Returns>;
_output: core.$InferOuterFunctionType<Args, Returns>;
input<const Items extends util.TupleItems, const Rest extends core.$ZodFunctionOut = core.$ZodFunctionOut>(args: Items, rest?: Rest): ZodFunction<core.$ZodTuple<Items, Rest>, Returns>;
input<NewArgs extends core.$ZodFunctionIn>(args: NewArgs): ZodFunction<NewArgs, Returns>;
input(...args: any[]): ZodFunction<any, Returns>;
output<NewReturns extends core.$ZodType>(output: NewReturns): ZodFunction<Args, NewReturns>;
}
export declare const ZodFunction: core.$constructor<ZodFunction>;
export declare function _function(): ZodFunction;
export declare function _function<const In extends ReadonlyArray<core.$ZodType>>(params: {
input: In;
}): ZodFunction<ZodTuple<In, null>, core.$ZodFunctionOut>;
export declare function _function<const In extends ReadonlyArray<core.$ZodType>, const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
input: In;
output: Out;
}): ZodFunction<ZodTuple<In, null>, Out>;
export declare function _function<const In extends core.$ZodFunctionIn = core.$ZodFunctionIn>(params: {
input: In;
}): ZodFunction<In, core.$ZodFunctionOut>;
export declare function _function<const Out extends core.$ZodFunctionOut = core.$ZodFunctionOut>(params: {
output: Out;
}): ZodFunction<core.$ZodFunctionIn, Out>;
export declare function _function<In extends core.$ZodFunctionIn = core.$ZodFunctionIn, Out extends core.$ZodType = core.$ZodType>(params?: {
input: In;
output: Out;
}): ZodFunction<In, Out>;
export { _function as function };
export interface ZodCustom<O = unknown, I = unknown> extends _ZodType<core.$ZodCustomInternals<O, I>>, core.$ZodCustom<O, I> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodCustom: core.$constructor<ZodCustom>;
export declare function check<O = unknown>(fn: core.CheckFn<O>): core.$ZodCheck<O>;
export declare function custom<O>(fn?: (data: unknown) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodCustom<O, O>;
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
export declare const describe: typeof core.describe;
export declare const meta: typeof core.meta;
type ZodInstanceOfParams = core.Params<ZodCustom, core.$ZodIssueCustom, "type" | "check" | "checks" | "fn" | "abort" | "error" | "params" | "path">;
export interface ZodInstanceOf<T = unknown> extends ZodCustom<T, T> {
properties<Shape extends {
[k in keyof T as T[k] extends Function ? never : k]?: core.$ZodType<unknown, T[k]>;
}>(shape: Shape, params?: string | core.$ZodCheckPropertiesParams): ZodInstanceOf<T & core.$InferObjectInput<Shape, {}>>;
}
export declare const ZodInstanceOf: core.$constructor<ZodInstanceOf>;
declare function _instanceof<T extends typeof util.Class>(cls: T, params?: ZodInstanceOfParams): ZodInstanceOf<InstanceType<T>>;
export { _instanceof as instanceof };
export declare const stringbool: (_params?: string | core.$ZodStringBoolParams) => ZodCodec<ZodString, ZodBoolean>;
type _ZodJSONSchema = ZodUnion<[
ZodString,
ZodNumber,
ZodBoolean,
ZodNull,
ZodArray<ZodJSONSchema>,
ZodRecord<ZodString, ZodJSONSchema>
]>;
type _ZodJSONSchemaInternals = _ZodJSONSchema["_zod"];
export interface ZodJSONSchemaInternals extends _ZodJSONSchemaInternals {
output: util.JSONType;
input: util.JSONType;
}
export interface ZodJSONSchema extends _ZodJSONSchema {
_zod: ZodJSONSchemaInternals;
}
export declare function json(params?: string | core.$ZodCustomParams): ZodJSONSchema;
export declare function preprocess<A, U extends core.SomeType, B = unknown>(fn: (arg: B, ctx: core.$RefinementCtx) => A, schema: U): ZodPreprocess<U, B>;
+1535
View File
File diff suppressed because it is too large Load Diff