gitea push

This commit is contained in:
2026-05-09 12:19:29 -06:00
parent 06113c95b8
commit 429461e985
1481 changed files with 74306 additions and 52475 deletions
+7 -2
View File
@@ -256,6 +256,11 @@ function _nanoid(Class, params) {
...util.normalizeParams(params),
});
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
// @__NO_SIDE_EFFECTS__
function _cuid(Class, params) {
return new Class({
@@ -1094,7 +1099,7 @@ function _refine(Class, fn, _params) {
return schema;
}
// @__NO_SIDE_EFFECTS__
function _superRefine(fn) {
function _superRefine(fn, params) {
const ch = _check((payload) => {
payload.addIssue = (issue) => {
if (typeof issue === "string") {
@@ -1113,7 +1118,7 @@ function _superRefine(fn) {
}
};
return fn(payload.value, payload);
});
}, params);
return ch;
}
// @__NO_SIDE_EFFECTS__
+26 -5
View File
@@ -49,8 +49,23 @@ export declare function _emoji<T extends schemas.$ZodEmoji>(Class: util.SchemaCl
export type $ZodNanoIDParams = StringFormatParams<schemas.$ZodNanoID, "when">;
export type $ZodCheckNanoIDParams = CheckStringFormatParams<schemas.$ZodNanoID, "when">;
export declare function _nanoid<T extends schemas.$ZodNanoID>(Class: util.SchemaClass<T>, params?: string | $ZodNanoIDParams | $ZodCheckNanoIDParams): T;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export type $ZodCUIDParams = StringFormatParams<schemas.$ZodCUID, "when">;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export type $ZodCheckCUIDParams = CheckStringFormatParams<schemas.$ZodCUID, "when">;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function _cuid<T extends schemas.$ZodCUID>(Class: util.SchemaClass<T>, params?: string | $ZodCUIDParams | $ZodCheckCUIDParams): T;
export type $ZodCUID2Params = StringFormatParams<schemas.$ZodCUID2, "when">;
export type $ZodCheckCUID2Params = CheckStringFormatParams<schemas.$ZodCUID2, "when">;
@@ -210,14 +225,16 @@ export type $ZodUnionParams = TypeParams<schemas.$ZodUnion, "options">;
export declare function _union<const T extends readonly schemas.$ZodObject[]>(Class: util.SchemaClass<schemas.$ZodUnion>, options: T, params?: string | $ZodUnionParams): schemas.$ZodUnion<T>;
export type $ZodXorParams = TypeParams<schemas.$ZodXor, "options">;
export declare function _xor<const T extends readonly schemas.$ZodObject[]>(Class: util.SchemaClass<schemas.$ZodXor>, options: T, params?: string | $ZodXorParams): schemas.$ZodXor<T>;
export interface $ZodTypeDiscriminableInternals extends schemas.$ZodTypeInternals {
export interface $ZodTypeDiscriminableInternals<Disc extends string = string> extends schemas.$ZodTypeInternals<unknown, {
[K in Disc]?: unknown;
}> {
propValues: util.PropValues;
}
export interface $ZodTypeDiscriminable extends schemas.$ZodType {
_zod: $ZodTypeDiscriminableInternals;
export interface $ZodTypeDiscriminable<Disc extends string = string> extends schemas.$ZodType {
_zod: $ZodTypeDiscriminableInternals<Disc>;
}
export type $ZodDiscriminatedUnionParams = TypeParams<schemas.$ZodDiscriminatedUnion, "options" | "discriminator">;
export declare function _discriminatedUnion<Types extends [$ZodTypeDiscriminable, ...$ZodTypeDiscriminable[]], Disc extends string>(Class: util.SchemaClass<schemas.$ZodDiscriminatedUnion>, discriminator: Disc, options: Types, params?: string | $ZodDiscriminatedUnionParams): schemas.$ZodDiscriminatedUnion<Types, Disc>;
export declare function _discriminatedUnion<Types extends [$ZodTypeDiscriminable<Disc>, ...$ZodTypeDiscriminable<Disc>[]], Disc extends string>(Class: util.SchemaClass<schemas.$ZodDiscriminatedUnion>, discriminator: Disc, options: Types, params?: string | $ZodDiscriminatedUnionParams): schemas.$ZodDiscriminatedUnion<Types, Disc>;
export type $ZodIntersectionParams = TypeParams<schemas.$ZodIntersection, "left" | "right">;
export declare function _intersection<T extends schemas.$ZodObject, U extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodIntersection>, left: T, right: U): schemas.$ZodIntersection<T, U>;
export type $ZodTupleParams = TypeParams<schemas.$ZodTuple, "items" | "rest">;
@@ -282,7 +299,11 @@ type RawIssue<T extends errors.$ZodIssueBase> = T extends any ? util.Flatten<uti
export interface $RefinementCtx<T = unknown> extends schemas.ParsePayload<T> {
addIssue(arg: string | $ZodSuperRefineIssue): void;
}
export declare function _superRefine<T>(fn: (arg: T, payload: $RefinementCtx<T>) => void | Promise<void>): checks.$ZodCheck<T>;
export interface $ZodSuperRefineParams {
/** If provided, the refinement runs only when this returns `true`. By default, it is skipped if prior parsing produced aborting issues. */
when?: ((payload: schemas.ParsePayload) => boolean) | undefined;
}
export declare function _superRefine<T>(fn: (arg: T, payload: $RefinementCtx<T>) => void | Promise<void>, params?: $ZodSuperRefineParams): checks.$ZodCheck<T>;
export declare function _check<O = unknown>(fn: schemas.CheckFn<O>, params?: string | $ZodCustomParams): checks.$ZodCheck<O>;
export declare function describe<T>(description: string): checks.$ZodCheck<T>;
export declare function meta<T>(metadata: registries.GlobalMeta): checks.$ZodCheck<T>;
+26 -5
View File
@@ -49,8 +49,23 @@ export declare function _emoji<T extends schemas.$ZodEmoji>(Class: util.SchemaCl
export type $ZodNanoIDParams = StringFormatParams<schemas.$ZodNanoID, "when">;
export type $ZodCheckNanoIDParams = CheckStringFormatParams<schemas.$ZodNanoID, "when">;
export declare function _nanoid<T extends schemas.$ZodNanoID>(Class: util.SchemaClass<T>, params?: string | $ZodNanoIDParams | $ZodCheckNanoIDParams): T;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export type $ZodCUIDParams = StringFormatParams<schemas.$ZodCUID, "when">;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export type $ZodCheckCUIDParams = CheckStringFormatParams<schemas.$ZodCUID, "when">;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function _cuid<T extends schemas.$ZodCUID>(Class: util.SchemaClass<T>, params?: string | $ZodCUIDParams | $ZodCheckCUIDParams): T;
export type $ZodCUID2Params = StringFormatParams<schemas.$ZodCUID2, "when">;
export type $ZodCheckCUID2Params = CheckStringFormatParams<schemas.$ZodCUID2, "when">;
@@ -210,14 +225,16 @@ export type $ZodUnionParams = TypeParams<schemas.$ZodUnion, "options">;
export declare function _union<const T extends readonly schemas.$ZodObject[]>(Class: util.SchemaClass<schemas.$ZodUnion>, options: T, params?: string | $ZodUnionParams): schemas.$ZodUnion<T>;
export type $ZodXorParams = TypeParams<schemas.$ZodXor, "options">;
export declare function _xor<const T extends readonly schemas.$ZodObject[]>(Class: util.SchemaClass<schemas.$ZodXor>, options: T, params?: string | $ZodXorParams): schemas.$ZodXor<T>;
export interface $ZodTypeDiscriminableInternals extends schemas.$ZodTypeInternals {
export interface $ZodTypeDiscriminableInternals<Disc extends string = string> extends schemas.$ZodTypeInternals<unknown, {
[K in Disc]?: unknown;
}> {
propValues: util.PropValues;
}
export interface $ZodTypeDiscriminable extends schemas.$ZodType {
_zod: $ZodTypeDiscriminableInternals;
export interface $ZodTypeDiscriminable<Disc extends string = string> extends schemas.$ZodType {
_zod: $ZodTypeDiscriminableInternals<Disc>;
}
export type $ZodDiscriminatedUnionParams = TypeParams<schemas.$ZodDiscriminatedUnion, "options" | "discriminator">;
export declare function _discriminatedUnion<Types extends [$ZodTypeDiscriminable, ...$ZodTypeDiscriminable[]], Disc extends string>(Class: util.SchemaClass<schemas.$ZodDiscriminatedUnion>, discriminator: Disc, options: Types, params?: string | $ZodDiscriminatedUnionParams): schemas.$ZodDiscriminatedUnion<Types, Disc>;
export declare function _discriminatedUnion<Types extends [$ZodTypeDiscriminable<Disc>, ...$ZodTypeDiscriminable<Disc>[]], Disc extends string>(Class: util.SchemaClass<schemas.$ZodDiscriminatedUnion>, discriminator: Disc, options: Types, params?: string | $ZodDiscriminatedUnionParams): schemas.$ZodDiscriminatedUnion<Types, Disc>;
export type $ZodIntersectionParams = TypeParams<schemas.$ZodIntersection, "left" | "right">;
export declare function _intersection<T extends schemas.$ZodObject, U extends schemas.$ZodObject>(Class: util.SchemaClass<schemas.$ZodIntersection>, left: T, right: U): schemas.$ZodIntersection<T, U>;
export type $ZodTupleParams = TypeParams<schemas.$ZodTuple, "items" | "rest">;
@@ -282,7 +299,11 @@ type RawIssue<T extends errors.$ZodIssueBase> = T extends any ? util.Flatten<uti
export interface $RefinementCtx<T = unknown> extends schemas.ParsePayload<T> {
addIssue(arg: string | $ZodSuperRefineIssue): void;
}
export declare function _superRefine<T>(fn: (arg: T, payload: $RefinementCtx<T>) => void | Promise<void>): checks.$ZodCheck<T>;
export interface $ZodSuperRefineParams {
/** If provided, the refinement runs only when this returns `true`. By default, it is skipped if prior parsing produced aborting issues. */
when?: ((payload: schemas.ParsePayload) => boolean) | undefined;
}
export declare function _superRefine<T>(fn: (arg: T, payload: $RefinementCtx<T>) => void | Promise<void>, params?: $ZodSuperRefineParams): checks.$ZodCheck<T>;
export declare function _check<O = unknown>(fn: schemas.CheckFn<O>, params?: string | $ZodCustomParams): checks.$ZodCheck<O>;
export declare function describe<T>(description: string): checks.$ZodCheck<T>;
export declare function meta<T>(metadata: registries.GlobalMeta): checks.$ZodCheck<T>;
+7 -2
View File
@@ -110,6 +110,11 @@ export function _nanoid(Class, params) {
...util.normalizeParams(params),
});
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
// @__NO_SIDE_EFFECTS__
export function _cuid(Class, params) {
return new Class({
@@ -954,7 +959,7 @@ export function _refine(Class, fn, _params) {
return schema;
}
// @__NO_SIDE_EFFECTS__
export function _superRefine(fn) {
export function _superRefine(fn, params) {
const ch = _check((payload) => {
payload.addIssue = (issue) => {
if (typeof issue === "string") {
@@ -973,7 +978,7 @@ export function _superRefine(fn) {
}
};
return fn(payload.value, payload);
});
}, params);
return ch;
}
// @__NO_SIDE_EFFECTS__
+1 -1
View File
@@ -7,7 +7,7 @@ export interface $ZodCheckDef {
error?: errors.$ZodErrorMap<never> | undefined;
/** If true, no later checks will be executed if this check fails. Default `false`. */
abort?: boolean | undefined;
/** If provided, this check will only be executed if the function returns `true`. Defaults to `payload => z.util.isAborted(payload)`. */
/** If provided, the check runs only when this returns `true`. By default, it is skipped if prior parsing produced aborting issues. */
when?: ((payload: schemas.ParsePayload) => boolean) | undefined;
}
export interface $ZodCheckInternals<T> {
+1 -1
View File
@@ -7,7 +7,7 @@ export interface $ZodCheckDef {
error?: errors.$ZodErrorMap<never> | undefined;
/** If true, no later checks will be executed if this check fails. Default `false`. */
abort?: boolean | undefined;
/** If provided, this check will only be executed if the function returns `true`. Defaults to `payload => z.util.isAborted(payload)`. */
/** If provided, the check runs only when this returns `true`. By default, it is skipped if prior parsing produced aborting issues. */
when?: ((payload: schemas.ParsePayload) => boolean) | undefined;
}
export interface $ZodCheckInternals<T> {
+3 -1
View File
@@ -1,4 +1,5 @@
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.globalConfig = exports.$ZodEncodeError = exports.$ZodAsyncError = exports.$brand = exports.NEVER = void 0;
exports.$constructor = $constructor;
@@ -75,7 +76,8 @@ class $ZodEncodeError extends Error {
}
}
exports.$ZodEncodeError = $ZodEncodeError;
exports.globalConfig = {};
(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
exports.globalConfig = globalThis.__zod_globalConfig;
function config(newConfig) {
if (newConfig)
Object.assign(exports.globalConfig, newConfig);
+4 -2
View File
@@ -1,5 +1,6 @@
var _a;
/** A special constant with type `never` */
export const NEVER = Object.freeze({
export const NEVER = /*@__PURE__*/ Object.freeze({
status: "aborted",
});
export /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {
@@ -68,7 +69,8 @@ export class $ZodEncodeError extends Error {
this.name = "ZodEncodeError";
}
}
export const globalConfig = {};
(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
export const globalConfig = globalThis.__zod_globalConfig;
export function config(newConfig) {
if (newConfig)
Object.assign(globalConfig, newConfig);
+26 -23
View File
@@ -65,35 +65,38 @@ function flattenError(error, mapper = (issue) => issue.message) {
}
function formatError(error, mapper = (issue) => issue.message) {
const fieldErrors = { _errors: [] };
const processError = (error) => {
const processError = (error, path = []) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union" && issue.errors.length) {
issue.errors.map((issues) => processError({ issues }));
issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues });
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues });
}
else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
const fullpath = [...path, ...issue.path];
if (fullpath.length === 0) {
fieldErrors._errors.push(mapper(issue));
}
else {
let curr = fieldErrors;
let i = 0;
while (i < fullpath.length) {
const el = fullpath[i];
const terminal = i === fullpath.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
}
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
@@ -108,13 +111,13 @@ function treeifyError(error, mapper = (issue) => issue.message) {
for (const issue of error.issues) {
if (issue.code === "invalid_union" && issue.errors.length) {
// regular union error
issue.errors.map((issues) => processError({ issues }, issue.path));
issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues }, issue.path);
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues }, issue.path);
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else {
const fullpath = [...path, ...issue.path];
+1
View File
@@ -54,6 +54,7 @@ interface $ZodIssueInvalidUnionNoMatch extends $ZodIssueBase {
readonly errors: $ZodIssue[][];
readonly input?: unknown;
readonly discriminator?: string | undefined;
readonly options?: util.Primitive[];
readonly inclusive?: true;
}
interface $ZodIssueInvalidUnionMultipleMatch extends $ZodIssueBase {
+1
View File
@@ -54,6 +54,7 @@ interface $ZodIssueInvalidUnionNoMatch extends $ZodIssueBase {
readonly errors: $ZodIssue[][];
readonly input?: unknown;
readonly discriminator?: string | undefined;
readonly options?: util.Primitive[];
readonly inclusive?: true;
}
interface $ZodIssueInvalidUnionMultipleMatch extends $ZodIssueBase {
+26 -23
View File
@@ -34,35 +34,38 @@ export function flattenError(error, mapper = (issue) => issue.message) {
}
export function formatError(error, mapper = (issue) => issue.message) {
const fieldErrors = { _errors: [] };
const processError = (error) => {
const processError = (error, path = []) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union" && issue.errors.length) {
issue.errors.map((issues) => processError({ issues }));
issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues });
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues });
}
else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
const fullpath = [...path, ...issue.path];
if (fullpath.length === 0) {
fieldErrors._errors.push(mapper(issue));
}
else {
let curr = fieldErrors;
let i = 0;
while (i < fullpath.length) {
const el = fullpath[i];
const terminal = i === fullpath.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
}
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
@@ -77,13 +80,13 @@ export function treeifyError(error, mapper = (issue) => issue.message) {
for (const issue of error.issues) {
if (issue.code === "invalid_union" && issue.errors.length) {
// regular union error
issue.errors.map((issues) => processError({ issues }, issue.path));
issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues }, issue.path);
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues }, issue.path);
processError({ issues: issue.issues }, [...path, ...issue.path]);
}
else {
const fullpath = [...path, ...issue.path];
+16 -20
View File
@@ -58,8 +58,12 @@ const numberProcessor = (schema, ctx, _json, _params) => {
json.type = "integer";
else
json.type = "number";
if (typeof exclusiveMinimum === "number") {
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
// when both minimum and exclusiveMinimum exist, pick the more restrictive one
const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
if (exMin) {
if (legacy) {
json.minimum = exclusiveMinimum;
json.exclusiveMinimum = true;
}
@@ -67,17 +71,11 @@ const numberProcessor = (schema, ctx, _json, _params) => {
json.exclusiveMinimum = exclusiveMinimum;
}
}
if (typeof minimum === "number") {
else if (typeof minimum === "number") {
json.minimum = minimum;
if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") {
if (exclusiveMinimum >= minimum)
delete json.minimum;
else
delete json.exclusiveMinimum;
}
}
if (typeof exclusiveMaximum === "number") {
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
if (exMax) {
if (legacy) {
json.maximum = exclusiveMaximum;
json.exclusiveMaximum = true;
}
@@ -85,14 +83,8 @@ const numberProcessor = (schema, ctx, _json, _params) => {
json.exclusiveMaximum = exclusiveMaximum;
}
}
if (typeof maximum === "number") {
else if (typeof maximum === "number") {
json.maximum = maximum;
if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") {
if (exclusiveMaximum <= maximum)
delete json.maximum;
else
delete json.exclusiveMaximum;
}
}
if (typeof multipleOf === "number")
json.multipleOf = multipleOf;
@@ -302,7 +294,10 @@ const arrayProcessor = (schema, ctx, _json, params) => {
if (typeof maximum === "number")
json.maxItems = maximum;
json.type = "array";
json.items = (0, to_json_schema_js_1.process)(def.element, ctx, { ...params, path: [...params.path, "items"] });
json.items = (0, to_json_schema_js_1.process)(def.element, ctx, {
...params,
path: [...params.path, "items"],
});
};
exports.arrayProcessor = arrayProcessor;
const objectProcessor = (schema, ctx, _json, params) => {
@@ -530,7 +525,8 @@ const catchProcessor = (schema, ctx, json, params) => {
exports.catchProcessor = catchProcessor;
const pipeProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
const innerType = ctx.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out;
const inIsTransform = def.in._zod.traits.has("$ZodTransform");
const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out;
(0, to_json_schema_js_1.process)(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
+16 -20
View File
@@ -53,8 +53,12 @@ export const numberProcessor = (schema, ctx, _json, _params) => {
json.type = "integer";
else
json.type = "number";
if (typeof exclusiveMinimum === "number") {
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
// when both minimum and exclusiveMinimum exist, pick the more restrictive one
const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
if (exMin) {
if (legacy) {
json.minimum = exclusiveMinimum;
json.exclusiveMinimum = true;
}
@@ -62,17 +66,11 @@ export const numberProcessor = (schema, ctx, _json, _params) => {
json.exclusiveMinimum = exclusiveMinimum;
}
}
if (typeof minimum === "number") {
else if (typeof minimum === "number") {
json.minimum = minimum;
if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") {
if (exclusiveMinimum >= minimum)
delete json.minimum;
else
delete json.exclusiveMinimum;
}
}
if (typeof exclusiveMaximum === "number") {
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
if (exMax) {
if (legacy) {
json.maximum = exclusiveMaximum;
json.exclusiveMaximum = true;
}
@@ -80,14 +78,8 @@ export const numberProcessor = (schema, ctx, _json, _params) => {
json.exclusiveMaximum = exclusiveMaximum;
}
}
if (typeof maximum === "number") {
else if (typeof maximum === "number") {
json.maximum = maximum;
if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") {
if (exclusiveMaximum <= maximum)
delete json.maximum;
else
delete json.exclusiveMaximum;
}
}
if (typeof multipleOf === "number")
json.multipleOf = multipleOf;
@@ -275,7 +267,10 @@ export const arrayProcessor = (schema, ctx, _json, params) => {
if (typeof maximum === "number")
json.maxItems = maximum;
json.type = "array";
json.items = process(def.element, ctx, { ...params, path: [...params.path, "items"] });
json.items = process(def.element, ctx, {
...params,
path: [...params.path, "items"],
});
};
export const objectProcessor = (schema, ctx, _json, params) => {
const json = _json;
@@ -492,7 +487,8 @@ export const catchProcessor = (schema, ctx, json, params) => {
};
export const pipeProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
const innerType = ctx.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out;
const inIsTransform = def.in._zod.traits.has("$ZodTransform");
const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out;
process(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
+2 -1
View File
@@ -2,5 +2,6 @@
"type": "module",
"main": "./index.cjs",
"module": "./index.js",
"types": "./index.d.cts"
"types": "./index.d.cts",
"sideEffects": false
}
+7 -7
View File
@@ -28,7 +28,7 @@ const core = __importStar(require("./core.cjs"));
const errors = __importStar(require("./errors.cjs"));
const util = __importStar(require("./util.cjs"));
const _parse = (_Err) => (schema, value, _ctx, _params) => {
const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
@@ -43,7 +43,7 @@ const _parse = (_Err) => (schema, value, _ctx, _params) => {
exports._parse = _parse;
exports.parse = (0, exports._parse)(errors.$ZodRealError);
const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
@@ -72,7 +72,7 @@ const _safeParse = (_Err) => (schema, value, _ctx) => {
exports._safeParse = _safeParse;
exports.safeParse = (0, exports._safeParse)(errors.$ZodRealError);
const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
@@ -86,7 +86,7 @@ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
exports._safeParseAsync = _safeParseAsync;
exports.safeParseAsync = (0, exports._safeParseAsync)(errors.$ZodRealError);
const _encode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return (0, exports._parse)(_Err)(schema, value, ctx);
};
exports._encode = _encode;
@@ -97,7 +97,7 @@ const _decode = (_Err) => (schema, value, _ctx) => {
exports._decode = _decode;
exports.decode = (0, exports._decode)(errors.$ZodRealError);
const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return (0, exports._parseAsync)(_Err)(schema, value, ctx);
};
exports._encodeAsync = _encodeAsync;
@@ -108,7 +108,7 @@ const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
exports._decodeAsync = _decodeAsync;
exports.decodeAsync = (0, exports._decodeAsync)(errors.$ZodRealError);
const _safeEncode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return (0, exports._safeParse)(_Err)(schema, value, ctx);
};
exports._safeEncode = _safeEncode;
@@ -119,7 +119,7 @@ const _safeDecode = (_Err) => (schema, value, _ctx) => {
exports._safeDecode = _safeDecode;
exports.safeDecode = (0, exports._safeDecode)(errors.$ZodRealError);
const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return (0, exports._safeParseAsync)(_Err)(schema, value, ctx);
};
exports._safeEncodeAsync = _safeEncodeAsync;
+7 -7
View File
@@ -2,7 +2,7 @@ import * as core from "./core.js";
import * as errors from "./errors.js";
import * as util from "./util.js";
export const _parse = (_Err) => (schema, value, _ctx, _params) => {
const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
@@ -16,7 +16,7 @@ export const _parse = (_Err) => (schema, value, _ctx, _params) => {
};
export const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);
export const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
@@ -43,7 +43,7 @@ export const _safeParse = (_Err) => (schema, value, _ctx) => {
};
export const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);
export const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
@@ -56,7 +56,7 @@ export const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
};
export const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);
export const _encode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return _parse(_Err)(schema, value, ctx);
};
export const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);
@@ -65,7 +65,7 @@ export const _decode = (_Err) => (schema, value, _ctx) => {
};
export const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);
export const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return _parseAsync(_Err)(schema, value, ctx);
};
export const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);
@@ -74,7 +74,7 @@ export const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
};
export const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);
export const _safeEncode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return _safeParse(_Err)(schema, value, ctx);
};
export const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);
@@ -83,7 +83,7 @@ export const _safeDecode = (_Err) => (schema, value, _ctx) => {
};
export const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);
export const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
return _safeParseAsync(_Err)(schema, value, ctx);
};
export const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);
+9 -3
View File
@@ -23,13 +23,18 @@ var __importStar = (this && this.__importStar) || function (mod) {
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sha384_hex = exports.sha256_base64url = exports.sha256_base64 = exports.sha256_hex = exports.sha1_base64url = exports.sha1_base64 = exports.sha1_hex = exports.md5_base64url = exports.md5_base64 = exports.md5_hex = exports.hex = exports.uppercase = exports.lowercase = exports.undefined = exports.null = exports.boolean = exports.number = exports.integer = exports.bigint = exports.string = exports.date = exports.e164 = exports.domain = exports.hostname = exports.base64url = exports.base64 = exports.cidrv6 = exports.cidrv4 = exports.mac = exports.ipv6 = exports.ipv4 = exports.browserEmail = exports.idnEmail = exports.unicodeEmail = exports.rfc5322Email = exports.html5Email = exports.email = exports.uuid7 = exports.uuid6 = exports.uuid4 = exports.uuid = exports.guid = exports.extendedDuration = exports.duration = exports.nanoid = exports.ksuid = exports.xid = exports.ulid = exports.cuid2 = exports.cuid = void 0;
exports.sha512_base64url = exports.sha512_base64 = exports.sha512_hex = exports.sha384_base64url = exports.sha384_base64 = void 0;
exports.sha256_base64url = exports.sha256_base64 = exports.sha256_hex = exports.sha1_base64url = exports.sha1_base64 = exports.sha1_hex = exports.md5_base64url = exports.md5_base64 = exports.md5_hex = exports.hex = exports.uppercase = exports.lowercase = exports.undefined = exports.null = exports.boolean = exports.number = exports.integer = exports.bigint = exports.string = exports.date = exports.e164 = exports.httpProtocol = exports.domain = exports.hostname = exports.base64url = exports.base64 = exports.cidrv6 = exports.cidrv4 = exports.mac = exports.ipv6 = exports.ipv4 = exports.browserEmail = exports.idnEmail = exports.unicodeEmail = exports.rfc5322Email = exports.html5Email = exports.email = exports.uuid7 = exports.uuid6 = exports.uuid4 = exports.uuid = exports.guid = exports.extendedDuration = exports.duration = exports.nanoid = exports.ksuid = exports.xid = exports.ulid = exports.cuid2 = exports.cuid = void 0;
exports.sha512_base64url = exports.sha512_base64 = exports.sha512_hex = exports.sha384_base64url = exports.sha384_base64 = exports.sha384_hex = void 0;
exports.emoji = emoji;
exports.time = time;
exports.datetime = datetime;
const util = __importStar(require("./util.cjs"));
exports.cuid = /^[cC][^\s-]{8,}$/;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
exports.cuid = /^[cC][0-9a-z]{6,}$/;
exports.cuid2 = /^[0-9a-z]+$/;
exports.ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
exports.xid = /^[0-9a-vA-V]{20}$/;
@@ -84,6 +89,7 @@ exports.base64url = /^[A-Za-z0-9_-]*$/;
// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
exports.hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
exports.domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
exports.httpProtocol = /^https?$/;
// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15
exports.e164 = /^\+[1-9]\d{6,14}$/;
+6
View File
@@ -1,3 +1,8 @@
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const cuid: RegExp;
export declare const cuid2: RegExp;
export declare const ulid: RegExp;
@@ -37,6 +42,7 @@ export declare const base64: RegExp;
export declare const base64url: RegExp;
export declare const hostname: RegExp;
export declare const domain: RegExp;
export declare const httpProtocol: RegExp;
export declare const e164: RegExp;
export declare const date: RegExp;
export declare function time(args: {
+6
View File
@@ -1,3 +1,8 @@
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const cuid: RegExp;
export declare const cuid2: RegExp;
export declare const ulid: RegExp;
@@ -37,6 +42,7 @@ export declare const base64: RegExp;
export declare const base64url: RegExp;
export declare const hostname: RegExp;
export declare const domain: RegExp;
export declare const httpProtocol: RegExp;
export declare const e164: RegExp;
export declare const date: RegExp;
export declare function time(args: {
+7 -1
View File
@@ -1,5 +1,10 @@
import * as util from "./util.js";
export const cuid = /^[cC][^\s-]{8,}$/;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export const cuid = /^[cC][0-9a-z]{6,}$/;
export const cuid2 = /^[0-9a-z]+$/;
export const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
export const xid = /^[0-9a-vA-V]{20}$/;
@@ -52,6 +57,7 @@ export const base64url = /^[A-Za-z0-9_-]*$/;
// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
export const hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
export const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
export const httpProtocol = /^https?$/;
// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15
export const e164 = /^\+[1-9]\d{6,14}$/;
+211 -65
View File
@@ -24,7 +24,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.$ZodTuple = exports.$ZodIntersection = exports.$ZodDiscriminatedUnion = exports.$ZodXor = exports.$ZodUnion = exports.$ZodObjectJIT = exports.$ZodObject = exports.$ZodArray = exports.$ZodDate = exports.$ZodVoid = exports.$ZodNever = exports.$ZodUnknown = exports.$ZodAny = exports.$ZodNull = exports.$ZodUndefined = exports.$ZodSymbol = exports.$ZodBigIntFormat = exports.$ZodBigInt = exports.$ZodBoolean = exports.$ZodNumberFormat = exports.$ZodNumber = exports.$ZodCustomStringFormat = exports.$ZodJWT = exports.$ZodE164 = exports.$ZodBase64URL = exports.$ZodBase64 = exports.$ZodCIDRv6 = exports.$ZodCIDRv4 = exports.$ZodMAC = exports.$ZodIPv6 = exports.$ZodIPv4 = exports.$ZodISODuration = exports.$ZodISOTime = exports.$ZodISODate = exports.$ZodISODateTime = exports.$ZodKSUID = exports.$ZodXID = exports.$ZodULID = exports.$ZodCUID2 = exports.$ZodCUID = exports.$ZodNanoID = exports.$ZodEmoji = exports.$ZodURL = exports.$ZodEmail = exports.$ZodUUID = exports.$ZodGUID = exports.$ZodStringFormat = exports.$ZodString = exports.clone = exports.$ZodType = void 0;
exports.$ZodCustom = exports.$ZodLazy = exports.$ZodPromise = exports.$ZodFunction = exports.$ZodTemplateLiteral = exports.$ZodReadonly = exports.$ZodCodec = exports.$ZodPipe = exports.$ZodNaN = exports.$ZodCatch = exports.$ZodSuccess = exports.$ZodNonOptional = exports.$ZodPrefault = exports.$ZodDefault = exports.$ZodNullable = exports.$ZodExactOptional = exports.$ZodOptional = exports.$ZodTransform = exports.$ZodFile = exports.$ZodLiteral = exports.$ZodEnum = exports.$ZodSet = exports.$ZodMap = exports.$ZodRecord = void 0;
exports.$ZodCustom = exports.$ZodLazy = exports.$ZodPromise = exports.$ZodFunction = exports.$ZodTemplateLiteral = exports.$ZodReadonly = exports.$ZodPreprocess = exports.$ZodCodec = exports.$ZodPipe = exports.$ZodNaN = exports.$ZodCatch = exports.$ZodSuccess = exports.$ZodNonOptional = exports.$ZodPrefault = exports.$ZodDefault = exports.$ZodNullable = exports.$ZodExactOptional = exports.$ZodOptional = exports.$ZodTransform = exports.$ZodFile = exports.$ZodLiteral = exports.$ZodEnum = exports.$ZodSet = exports.$ZodMap = exports.$ZodRecord = void 0;
exports.isValidBase64 = isValidBase64;
exports.isValidBase64URL = isValidBase64URL;
exports.isValidJWT = isValidJWT;
@@ -65,6 +65,8 @@ exports.$ZodType = core.$constructor("$ZodType", (inst, def) => {
let asyncResult;
for (const ch of checks) {
if (ch._zod.def.when) {
if (util.explicitlyAborted(payload))
continue;
const shouldRun = ch._zod.def.when(payload);
if (!shouldRun)
continue;
@@ -219,6 +221,21 @@ exports.$ZodURL = core.$constructor("$ZodURL", (inst, def) => {
try {
// Trim whitespace from input
const trimmed = payload.value.trim();
// When normalize is off, require :// for http/https URLs
// This prevents strings like "http:example.com" or "https:/path" from being silently accepted
if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {
if (!/^https?:\/\//i.test(trimmed)) {
payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid URL format",
input: payload.value,
inst,
continue: !def.abort,
});
return;
}
}
// @ts-ignore
const url = new URL(trimmed);
if (def.hostname) {
@@ -279,6 +296,11 @@ exports.$ZodNanoID = core.$constructor("$ZodNanoID", (inst, def) => {
def.pattern ?? (def.pattern = regexes.nanoid);
exports.$ZodStringFormat.init(inst, def);
});
/**
* @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.
*/
exports.$ZodCUID = core.$constructor("$ZodCUID", (inst, def) => {
def.pattern ?? (def.pattern = regexes.cuid);
exports.$ZodStringFormat.init(inst, def);
@@ -384,6 +406,9 @@ exports.$ZodCIDRv6 = core.$constructor("$ZodCIDRv6", (inst, def) => {
function isValidBase64(data) {
if (data === "")
return true;
// atob ignores whitespace, so reject it up front.
if (/\s/.test(data))
return false;
if (data.length % 4 !== 0)
return false;
try {
@@ -588,8 +613,6 @@ exports.$ZodUndefined = core.$constructor("$ZodUndefined", (inst, def) => {
exports.$ZodType.init(inst, def);
inst._zod.pattern = regexes.undefined;
inst._zod.values = new Set([undefined]);
inst._zod.optin = "optional";
inst._zod.optout = "optional";
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (typeof input === "undefined")
@@ -719,16 +742,28 @@ exports.$ZodArray = core.$constructor("$ZodArray", (inst, def) => {
return payload; //handleArrayResultsAsync(parseResults, final);
};
});
function handlePropertyResult(result, final, key, input, isOptionalOut) {
function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
const isPresent = key in input;
if (result.issues.length) {
// For optional-out schemas, ignore errors on absent keys
if (isOptionalOut && !(key in input)) {
// For optional-in/out schemas, ignore errors on absent keys.
if (isOptionalIn && isOptionalOut && !isPresent) {
return;
}
final.issues.push(...util.prefixIssues(key, result.issues));
}
if (!isPresent && !isOptionalIn) {
if (!result.issues.length) {
final.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [key],
});
}
return;
}
if (result.value === undefined) {
if (key in input) {
if (isPresent) {
final.value[key] = undefined;
}
}
@@ -754,12 +789,16 @@ function normalizeDef(def) {
}
function handleCatchall(proms, input, payload, ctx, def, inst) {
const unrecognized = [];
// iterate over input keys
const keySet = def.keySet;
const _catchall = def.catchall._zod;
const t = _catchall.def.type;
const isOptionalIn = _catchall.optin === "optional";
const isOptionalOut = _catchall.optout === "optional";
for (const key in input) {
// skip __proto__ so it can't replace the result prototype via the
// assignment setter on the plain {} we build into
if (key === "__proto__")
continue;
if (keySet.has(key))
continue;
if (t === "never") {
@@ -768,10 +807,10 @@ function handleCatchall(proms, input, payload, ctx, def, inst) {
}
const r = _catchall.run({ value: input[key], issues: [] }, ctx);
if (r instanceof Promise) {
proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
}
else {
handlePropertyResult(r, payload, key, input, isOptionalOut);
handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
}
}
if (unrecognized.length) {
@@ -839,13 +878,14 @@ exports.$ZodObject = core.$constructor("$ZodObject", (inst, def) => {
const shape = value.shape;
for (const key of value.keys) {
const el = shape[key];
const isOptionalIn = el._zod.optin === "optional";
const isOptionalOut = el._zod.optout === "optional";
const r = el._zod.run({ value: input[key], issues: [] }, ctx);
if (r instanceof Promise) {
proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
}
else {
handlePropertyResult(r, payload, key, input, isOptionalOut);
handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
}
}
if (!catchall) {
@@ -878,10 +918,11 @@ exports.$ZodObjectJIT = core.$constructor("$ZodObjectJIT", (inst, def) => {
const id = ids[key];
const k = util.esc(key);
const schema = shape[key];
const isOptionalIn = schema?._zod?.optin === "optional";
const isOptionalOut = schema?._zod?.optout === "optional";
doc.write(`const ${id} = ${parseStr(key)};`);
if (isOptionalOut) {
// For optional-out schemas, ignore errors on absent keys
if (isOptionalIn && isOptionalOut) {
// For optional-in/out schemas, ignore errors on absent keys
doc.write(`
if (${id}.issues.length) {
if (${k} in input) {
@@ -900,6 +941,34 @@ exports.$ZodObjectJIT = core.$constructor("$ZodObjectJIT", (inst, def) => {
newResult[${k}] = ${id}.value;
}
`);
}
else if (!isOptionalIn) {
doc.write(`
const ${id}_present = ${k} in input;
if (${id}.issues.length) {
payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
...iss,
path: iss.path ? [${k}, ...iss.path] : [${k}]
})));
}
if (!${id}_present && !${id}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${k}]
});
}
if (${id}_present) {
if (${id}.value === undefined) {
newResult[${k}] = undefined;
} else {
newResult[${k}] = ${id}.value;
}
}
`);
}
else {
@@ -995,10 +1064,9 @@ exports.$ZodUnion = core.$constructor("$ZodUnion", (inst, def) => {
}
return undefined;
});
const single = def.options.length === 1;
const first = def.options[0]._zod.run;
const first = def.options.length === 1 ? def.options[0]._zod.run : null;
inst._zod.parse = (payload, ctx) => {
if (single) {
if (first) {
return first(payload, ctx);
}
let async = false;
@@ -1055,10 +1123,9 @@ function handleExclusiveUnionResults(results, final, inst, ctx) {
exports.$ZodXor = core.$constructor("$ZodXor", (inst, def) => {
exports.$ZodUnion.init(inst, def);
def.inclusive = false;
const single = def.options.length === 1;
const first = def.options[0]._zod.run;
const first = def.options.length === 1 ? def.options[0]._zod.run : null;
inst._zod.parse = (payload, ctx) => {
if (single) {
if (first) {
return first(payload, ctx);
}
let async = false;
@@ -1136,7 +1203,11 @@ core.$constructor("$ZodDiscriminatedUnion", (inst, def) => {
if (opt) {
return opt._zod.run(payload, ctx);
}
if (def.unionFallback) {
// Fall back to union matching when the fast discriminator path fails:
// - explicitly enabled via unionFallback, or
// - during backward direction (encode), since codec-based discriminators
// have different values in forward vs backward directions
if (def.unionFallback || ctx.direction === "backward") {
return _super(payload, ctx);
}
// no matching discriminator
@@ -1145,6 +1216,7 @@ core.$constructor("$ZodDiscriminatedUnion", (inst, def) => {
errors: [],
note: "No matching discriminator",
discriminator: def.discriminator,
options: Array.from(disc.value.keys()),
input,
path: [def.discriminator],
inst,
@@ -1272,67 +1344,112 @@ exports.$ZodTuple = core.$constructor("$ZodTuple", (inst, def) => {
}
payload.value = [];
const proms = [];
const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional");
const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;
const optinStart = getTupleOptStart(items, "optin");
const optoutStart = getTupleOptStart(items, "optout");
if (!def.rest) {
const tooBig = input.length > items.length;
const tooSmall = input.length < optStart - 1;
if (tooBig || tooSmall) {
if (input.length < optinStart) {
payload.issues.push({
...(tooBig
? { code: "too_big", maximum: items.length, inclusive: true }
: { code: "too_small", minimum: items.length }),
code: "too_small",
minimum: optinStart,
inclusive: true,
input,
inst,
origin: "array",
});
return payload;
}
if (input.length > items.length) {
payload.issues.push({
code: "too_big",
maximum: items.length,
inclusive: true,
input,
inst,
origin: "array",
});
}
}
let i = -1;
for (const item of items) {
i++;
if (i >= input.length)
if (i >= optStart)
continue;
const result = item._zod.run({
value: input[i],
issues: [],
}, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => handleTupleResult(result, payload, i)));
// Run every item in parallel, collecting results into an indexed
// array. The post-processing in `handleTupleResults` walks them in
// order so it can decide whether an absent optional-output error can
// truncate the tail or must be reported to preserve required output.
const itemResults = new Array(items.length);
for (let i = 0; i < items.length; i++) {
const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);
if (r instanceof Promise) {
proms.push(r.then((rr) => {
itemResults[i] = rr;
}));
}
else {
handleTupleResult(result, payload, i);
itemResults[i] = r;
}
}
if (def.rest) {
let i = items.length - 1;
const rest = input.slice(items.length);
for (const el of rest) {
i++;
const result = def.rest._zod.run({
value: el,
issues: [],
}, ctx);
const result = def.rest._zod.run({ value: el, issues: [] }, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => handleTupleResult(result, payload, i)));
proms.push(result.then((r) => handleTupleResult(r, payload, i)));
}
else {
handleTupleResult(result, payload, i);
}
}
}
if (proms.length)
return Promise.all(proms).then(() => payload);
return payload;
if (proms.length) {
return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));
}
return handleTupleResults(itemResults, payload, items, input, optoutStart);
};
});
function getTupleOptStart(items, key) {
for (let i = items.length - 1; i >= 0; i--) {
if (items[i]._zod[key] !== "optional")
return i + 1;
}
return 0;
}
function handleTupleResult(result, final, index) {
if (result.issues.length) {
final.issues.push(...util.prefixIssues(index, result.issues));
}
final.value[index] = result.value;
}
function handleTupleResults(itemResults, final, items, input, optoutStart) {
// Walk results in order. Mirror $ZodObject's swallow-on-absent-optional
// rule, but only after `optoutStart`: the first index where the output
// tuple tail can be absent.
for (let i = 0; i < items.length; i++) {
const r = itemResults[i];
const isPresent = i < input.length;
if (r.issues.length) {
if (!isPresent && i >= optoutStart) {
final.value.length = i;
break;
}
final.issues.push(...util.prefixIssues(i, r.issues));
}
final.value[i] = r.value;
}
// Drop trailing slots that produced `undefined` for absent input
// (the array analog of an absent optional key on an object). The
// `i >= input.length` floor is critical: an explicit `undefined`
// *inside* the input must be preserved even when the schema is
// optional-out (e.g. `z.string().or(z.undefined())` accepting an
// explicit undefined value).
for (let i = final.value.length - 1; i >= input.length; i--) {
if (items[i]._zod.optout === "optional" && final.value[i] === undefined) {
final.value.length = i;
}
else {
break;
}
}
return final;
}
exports.$ZodRecord = core.$constructor("$ZodRecord", (inst, def) => {
exports.$ZodType.init(inst, def);
inst._zod.parse = (payload, ctx) => {
@@ -1354,20 +1471,36 @@ exports.$ZodRecord = core.$constructor("$ZodRecord", (inst, def) => {
for (const key of values) {
if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
recordKeys.add(typeof key === "number" ? key.toString() : key);
const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
if (keyResult instanceof Promise) {
throw new Error("Async schemas not supported in object keys currently");
}
if (keyResult.issues.length) {
payload.issues.push({
code: "invalid_key",
origin: "record",
issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
input: key,
path: [key],
inst,
});
continue;
}
const outKey = keyResult.value;
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => {
if (result.issues.length) {
payload.issues.push(...util.prefixIssues(key, result.issues));
}
payload.value[key] = result.value;
payload.value[outKey] = result.value;
}));
}
else {
if (result.issues.length) {
payload.issues.push(...util.prefixIssues(key, result.issues));
}
payload.value[key] = result.value;
payload.value[outKey] = result.value;
}
}
}
@@ -1389,9 +1522,12 @@ exports.$ZodRecord = core.$constructor("$ZodRecord", (inst, def) => {
}
else {
payload.value = {};
// Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()
for (const key of Reflect.ownKeys(input)) {
if (key === "__proto__")
continue;
if (!Object.prototype.propertyIsEnumerable.call(input, key))
continue;
let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
if (keyResult instanceof Promise) {
throw new Error("Async schemas not supported in object keys currently");
@@ -1612,6 +1748,7 @@ exports.$ZodFile = core.$constructor("$ZodFile", (inst, def) => {
});
exports.$ZodTransform = core.$constructor("$ZodTransform", (inst, def) => {
exports.$ZodType.init(inst, def);
inst._zod.optin = "optional";
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
throw new core.$ZodEncodeError(inst.constructor.name);
@@ -1621,6 +1758,7 @@ exports.$ZodTransform = core.$constructor("$ZodTransform", (inst, def) => {
const output = _out instanceof Promise ? _out : Promise.resolve(_out);
return output.then((output) => {
payload.value = output;
payload.fallback = true;
return payload;
});
}
@@ -1628,11 +1766,12 @@ exports.$ZodTransform = core.$constructor("$ZodTransform", (inst, def) => {
throw new core.$ZodAsyncError();
}
payload.value = _out;
payload.fallback = true;
return payload;
};
});
function handleOptionalResult(result, input) {
if (result.issues.length && input === undefined) {
if (input === undefined && (result.issues.length || result.fallback)) {
return { issues: [], value: undefined };
}
return result;
@@ -1650,10 +1789,11 @@ exports.$ZodOptional = core.$constructor("$ZodOptional", (inst, def) => {
});
inst._zod.parse = (payload, ctx) => {
if (def.innerType._zod.optin === "optional") {
const input = payload.value;
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise)
return result.then((r) => handleOptionalResult(r, payload.value));
return handleOptionalResult(result, payload.value);
return result.then((r) => handleOptionalResult(r, input));
return handleOptionalResult(result, input);
}
if (payload.value === undefined) {
return payload;
@@ -1780,7 +1920,7 @@ exports.$ZodSuccess = core.$constructor("$ZodSuccess", (inst, def) => {
});
exports.$ZodCatch = core.$constructor("$ZodCatch", (inst, def) => {
exports.$ZodType.init(inst, def);
util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
inst._zod.optin = "optional";
util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
util.defineLazy(inst._zod, "values", () => def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
@@ -1801,6 +1941,7 @@ exports.$ZodCatch = core.$constructor("$ZodCatch", (inst, def) => {
input: payload.value,
});
payload.issues = [];
payload.fallback = true;
}
return payload;
});
@@ -1815,6 +1956,7 @@ exports.$ZodCatch = core.$constructor("$ZodCatch", (inst, def) => {
input: payload.value,
});
payload.issues = [];
payload.fallback = true;
}
return payload;
};
@@ -1861,7 +2003,7 @@ function handlePipeResult(left, next, ctx) {
left.aborted = true;
return left;
}
return next._zod.run({ value: left.value, issues: left.issues }, ctx);
return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);
}
exports.$ZodCodec = core.$constructor("$ZodCodec", (inst, def) => {
exports.$ZodType.init(inst, def);
@@ -1917,6 +2059,9 @@ function handleCodecTxResult(left, value, nextSchema, ctx) {
}
return nextSchema._zod.run({ value, issues: left.issues }, ctx);
}
exports.$ZodPreprocess = core.$constructor("$ZodPreprocess", (inst, def) => {
exports.$ZodPipe.init(inst, def);
});
exports.$ZodReadonly = core.$constructor("$ZodReadonly", (inst, def) => {
exports.$ZodType.init(inst, def);
util.defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
@@ -2074,14 +2219,15 @@ exports.$ZodPromise = core.$constructor("$ZodPromise", (inst, def) => {
});
exports.$ZodLazy = core.$constructor("$ZodLazy", (inst, def) => {
exports.$ZodType.init(inst, def);
// let _innerType!: any;
// util.defineLazy(def, "getter", () => {
// if (!_innerType) {
// _innerType = def.getter();
// }
// return () => _innerType;
// });
util.defineLazy(inst._zod, "innerType", () => def.getter());
// Cache the resolved inner type on the shared `def` so all clones of this
// lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,
// preserving identity for cycle detection on recursive schemas.
util.defineLazy(inst._zod, "innerType", () => {
const d = def;
if (!d._cachedInner)
d._cachedInner = def.getter();
return d._cachedInner;
});
util.defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern);
util.defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues);
util.defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? undefined);
+39 -1
View File
@@ -23,8 +23,13 @@ export interface ParseContextInternal<T extends errors.$ZodIssueBase = never> ex
export interface ParsePayload<T = unknown> {
value: T;
issues: errors.$ZodRawIssue[];
/** A may to mark a whole payload as aborted. Used in codecs/pipes. */
/** A way to mark a whole payload as aborted. Used in codecs/pipes. */
aborted?: boolean;
/** @internal Marks a value as a fallback that an outer wrapper (e.g.
* $ZodOptional) may override with its own interpretation when input was
* undefined. Set by $ZodCatch when catchValue substitutes and by every
* $ZodTransform invocation. */
fallback?: boolean | undefined;
}
export type CheckFn<T> = (input: ParsePayload<T>) => util.MaybeAsync<void>;
export interface $ZodTypeDef {
@@ -182,13 +187,33 @@ export interface $ZodNanoID extends $ZodType {
_zod: $ZodNanoIDInternals;
}
export declare const $ZodNanoID: core.$constructor<$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 $ZodCUIDDef extends $ZodStringFormatDef<"cuid"> {
}
/**
* @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 $ZodCUIDInternals extends $ZodStringFormatInternals<"cuid"> {
}
/**
* @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 $ZodType {
_zod: $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>;
export interface $ZodCUID2Def extends $ZodStringFormatDef<"cuid2"> {
}
@@ -1010,6 +1035,19 @@ export interface $ZodCodec<A extends SomeType = $ZodType, B extends SomeType = $
_zod: $ZodCodecInternals<A, B>;
}
export declare const $ZodCodec: core.$constructor<$ZodCodec>;
export interface $ZodPreprocessDef<B extends SomeType = $ZodType> extends $ZodPipeDef<$ZodTransform, B> {
in: $ZodTransform;
out: B;
}
export interface $ZodPreprocessInternals<B extends SomeType = $ZodType> extends $ZodPipeInternals<$ZodTransform, B> {
def: $ZodPreprocessDef<B>;
optin: B["_zod"]["optin"];
optout: B["_zod"]["optout"];
}
export interface $ZodPreprocess<B extends SomeType = $ZodType> extends $ZodPipe<$ZodTransform, B> {
_zod: $ZodPreprocessInternals<B>;
}
export declare const $ZodPreprocess: core.$constructor<$ZodPreprocess>;
export interface $ZodReadonlyDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
type: "readonly";
innerType: T;
+39 -1
View File
@@ -23,8 +23,13 @@ export interface ParseContextInternal<T extends errors.$ZodIssueBase = never> ex
export interface ParsePayload<T = unknown> {
value: T;
issues: errors.$ZodRawIssue[];
/** A may to mark a whole payload as aborted. Used in codecs/pipes. */
/** A way to mark a whole payload as aborted. Used in codecs/pipes. */
aborted?: boolean;
/** @internal Marks a value as a fallback that an outer wrapper (e.g.
* $ZodOptional) may override with its own interpretation when input was
* undefined. Set by $ZodCatch when catchValue substitutes and by every
* $ZodTransform invocation. */
fallback?: boolean | undefined;
}
export type CheckFn<T> = (input: ParsePayload<T>) => util.MaybeAsync<void>;
export interface $ZodTypeDef {
@@ -182,13 +187,33 @@ export interface $ZodNanoID extends $ZodType {
_zod: $ZodNanoIDInternals;
}
export declare const $ZodNanoID: core.$constructor<$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 $ZodCUIDDef extends $ZodStringFormatDef<"cuid"> {
}
/**
* @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 $ZodCUIDInternals extends $ZodStringFormatInternals<"cuid"> {
}
/**
* @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 $ZodType {
_zod: $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>;
export interface $ZodCUID2Def extends $ZodStringFormatDef<"cuid2"> {
}
@@ -1010,6 +1035,19 @@ export interface $ZodCodec<A extends SomeType = $ZodType, B extends SomeType = $
_zod: $ZodCodecInternals<A, B>;
}
export declare const $ZodCodec: core.$constructor<$ZodCodec>;
export interface $ZodPreprocessDef<B extends SomeType = $ZodType> extends $ZodPipeDef<$ZodTransform, B> {
in: $ZodTransform;
out: B;
}
export interface $ZodPreprocessInternals<B extends SomeType = $ZodType> extends $ZodPipeInternals<$ZodTransform, B> {
def: $ZodPreprocessDef<B>;
optin: B["_zod"]["optin"];
optout: B["_zod"]["optout"];
}
export interface $ZodPreprocess<B extends SomeType = $ZodType> extends $ZodPipe<$ZodTransform, B> {
_zod: $ZodPreprocessInternals<B>;
}
export declare const $ZodPreprocess: core.$constructor<$ZodPreprocess>;
export interface $ZodReadonlyDef<T extends SomeType = $ZodType> extends $ZodTypeDef {
type: "readonly";
innerType: T;
+210 -64
View File
@@ -35,6 +35,8 @@ export const $ZodType = /*@__PURE__*/ core.$constructor("$ZodType", (inst, def)
let asyncResult;
for (const ch of checks) {
if (ch._zod.def.when) {
if (util.explicitlyAborted(payload))
continue;
const shouldRun = ch._zod.def.when(payload);
if (!shouldRun)
continue;
@@ -188,6 +190,21 @@ export const $ZodURL = /*@__PURE__*/ core.$constructor("$ZodURL", (inst, def) =>
try {
// Trim whitespace from input
const trimmed = payload.value.trim();
// When normalize is off, require :// for http/https URLs
// This prevents strings like "http:example.com" or "https:/path" from being silently accepted
if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {
if (!/^https?:\/\//i.test(trimmed)) {
payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid URL format",
input: payload.value,
inst,
continue: !def.abort,
});
return;
}
}
// @ts-ignore
const url = new URL(trimmed);
if (def.hostname) {
@@ -248,6 +265,11 @@ export const $ZodNanoID = /*@__PURE__*/ core.$constructor("$ZodNanoID", (inst, d
def.pattern ?? (def.pattern = regexes.nanoid);
$ZodStringFormat.init(inst, def);
});
/**
* @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 const $ZodCUID = /*@__PURE__*/ core.$constructor("$ZodCUID", (inst, def) => {
def.pattern ?? (def.pattern = regexes.cuid);
$ZodStringFormat.init(inst, def);
@@ -353,6 +375,9 @@ export const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor("$ZodCIDRv6", (inst, d
export function isValidBase64(data) {
if (data === "")
return true;
// atob ignores whitespace, so reject it up front.
if (/\s/.test(data))
return false;
if (data.length % 4 !== 0)
return false;
try {
@@ -557,8 +582,6 @@ export const $ZodUndefined = /*@__PURE__*/ core.$constructor("$ZodUndefined", (i
$ZodType.init(inst, def);
inst._zod.pattern = regexes.undefined;
inst._zod.values = new Set([undefined]);
inst._zod.optin = "optional";
inst._zod.optout = "optional";
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (typeof input === "undefined")
@@ -688,16 +711,28 @@ export const $ZodArray = /*@__PURE__*/ core.$constructor("$ZodArray", (inst, def
return payload; //handleArrayResultsAsync(parseResults, final);
};
});
function handlePropertyResult(result, final, key, input, isOptionalOut) {
function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
const isPresent = key in input;
if (result.issues.length) {
// For optional-out schemas, ignore errors on absent keys
if (isOptionalOut && !(key in input)) {
// For optional-in/out schemas, ignore errors on absent keys.
if (isOptionalIn && isOptionalOut && !isPresent) {
return;
}
final.issues.push(...util.prefixIssues(key, result.issues));
}
if (!isPresent && !isOptionalIn) {
if (!result.issues.length) {
final.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [key],
});
}
return;
}
if (result.value === undefined) {
if (key in input) {
if (isPresent) {
final.value[key] = undefined;
}
}
@@ -723,12 +758,16 @@ function normalizeDef(def) {
}
function handleCatchall(proms, input, payload, ctx, def, inst) {
const unrecognized = [];
// iterate over input keys
const keySet = def.keySet;
const _catchall = def.catchall._zod;
const t = _catchall.def.type;
const isOptionalIn = _catchall.optin === "optional";
const isOptionalOut = _catchall.optout === "optional";
for (const key in input) {
// skip __proto__ so it can't replace the result prototype via the
// assignment setter on the plain {} we build into
if (key === "__proto__")
continue;
if (keySet.has(key))
continue;
if (t === "never") {
@@ -737,10 +776,10 @@ function handleCatchall(proms, input, payload, ctx, def, inst) {
}
const r = _catchall.run({ value: input[key], issues: [] }, ctx);
if (r instanceof Promise) {
proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
}
else {
handlePropertyResult(r, payload, key, input, isOptionalOut);
handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
}
}
if (unrecognized.length) {
@@ -808,13 +847,14 @@ export const $ZodObject = /*@__PURE__*/ core.$constructor("$ZodObject", (inst, d
const shape = value.shape;
for (const key of value.keys) {
const el = shape[key];
const isOptionalIn = el._zod.optin === "optional";
const isOptionalOut = el._zod.optout === "optional";
const r = el._zod.run({ value: input[key], issues: [] }, ctx);
if (r instanceof Promise) {
proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
}
else {
handlePropertyResult(r, payload, key, input, isOptionalOut);
handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
}
}
if (!catchall) {
@@ -847,10 +887,11 @@ export const $ZodObjectJIT = /*@__PURE__*/ core.$constructor("$ZodObjectJIT", (i
const id = ids[key];
const k = util.esc(key);
const schema = shape[key];
const isOptionalIn = schema?._zod?.optin === "optional";
const isOptionalOut = schema?._zod?.optout === "optional";
doc.write(`const ${id} = ${parseStr(key)};`);
if (isOptionalOut) {
// For optional-out schemas, ignore errors on absent keys
if (isOptionalIn && isOptionalOut) {
// For optional-in/out schemas, ignore errors on absent keys
doc.write(`
if (${id}.issues.length) {
if (${k} in input) {
@@ -869,6 +910,34 @@ export const $ZodObjectJIT = /*@__PURE__*/ core.$constructor("$ZodObjectJIT", (i
newResult[${k}] = ${id}.value;
}
`);
}
else if (!isOptionalIn) {
doc.write(`
const ${id}_present = ${k} in input;
if (${id}.issues.length) {
payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
...iss,
path: iss.path ? [${k}, ...iss.path] : [${k}]
})));
}
if (!${id}_present && !${id}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${k}]
});
}
if (${id}_present) {
if (${id}.value === undefined) {
newResult[${k}] = undefined;
} else {
newResult[${k}] = ${id}.value;
}
}
`);
}
else {
@@ -964,10 +1033,9 @@ export const $ZodUnion = /*@__PURE__*/ core.$constructor("$ZodUnion", (inst, def
}
return undefined;
});
const single = def.options.length === 1;
const first = def.options[0]._zod.run;
const first = def.options.length === 1 ? def.options[0]._zod.run : null;
inst._zod.parse = (payload, ctx) => {
if (single) {
if (first) {
return first(payload, ctx);
}
let async = false;
@@ -1024,10 +1092,9 @@ function handleExclusiveUnionResults(results, final, inst, ctx) {
export const $ZodXor = /*@__PURE__*/ core.$constructor("$ZodXor", (inst, def) => {
$ZodUnion.init(inst, def);
def.inclusive = false;
const single = def.options.length === 1;
const first = def.options[0]._zod.run;
const first = def.options.length === 1 ? def.options[0]._zod.run : null;
inst._zod.parse = (payload, ctx) => {
if (single) {
if (first) {
return first(payload, ctx);
}
let async = false;
@@ -1105,7 +1172,11 @@ core.$constructor("$ZodDiscriminatedUnion", (inst, def) => {
if (opt) {
return opt._zod.run(payload, ctx);
}
if (def.unionFallback) {
// Fall back to union matching when the fast discriminator path fails:
// - explicitly enabled via unionFallback, or
// - during backward direction (encode), since codec-based discriminators
// have different values in forward vs backward directions
if (def.unionFallback || ctx.direction === "backward") {
return _super(payload, ctx);
}
// no matching discriminator
@@ -1114,6 +1185,7 @@ core.$constructor("$ZodDiscriminatedUnion", (inst, def) => {
errors: [],
note: "No matching discriminator",
discriminator: def.discriminator,
options: Array.from(disc.value.keys()),
input,
path: [def.discriminator],
inst,
@@ -1241,67 +1313,112 @@ export const $ZodTuple = /*@__PURE__*/ core.$constructor("$ZodTuple", (inst, def
}
payload.value = [];
const proms = [];
const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional");
const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;
const optinStart = getTupleOptStart(items, "optin");
const optoutStart = getTupleOptStart(items, "optout");
if (!def.rest) {
const tooBig = input.length > items.length;
const tooSmall = input.length < optStart - 1;
if (tooBig || tooSmall) {
if (input.length < optinStart) {
payload.issues.push({
...(tooBig
? { code: "too_big", maximum: items.length, inclusive: true }
: { code: "too_small", minimum: items.length }),
code: "too_small",
minimum: optinStart,
inclusive: true,
input,
inst,
origin: "array",
});
return payload;
}
if (input.length > items.length) {
payload.issues.push({
code: "too_big",
maximum: items.length,
inclusive: true,
input,
inst,
origin: "array",
});
}
}
let i = -1;
for (const item of items) {
i++;
if (i >= input.length)
if (i >= optStart)
continue;
const result = item._zod.run({
value: input[i],
issues: [],
}, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => handleTupleResult(result, payload, i)));
// Run every item in parallel, collecting results into an indexed
// array. The post-processing in `handleTupleResults` walks them in
// order so it can decide whether an absent optional-output error can
// truncate the tail or must be reported to preserve required output.
const itemResults = new Array(items.length);
for (let i = 0; i < items.length; i++) {
const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);
if (r instanceof Promise) {
proms.push(r.then((rr) => {
itemResults[i] = rr;
}));
}
else {
handleTupleResult(result, payload, i);
itemResults[i] = r;
}
}
if (def.rest) {
let i = items.length - 1;
const rest = input.slice(items.length);
for (const el of rest) {
i++;
const result = def.rest._zod.run({
value: el,
issues: [],
}, ctx);
const result = def.rest._zod.run({ value: el, issues: [] }, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => handleTupleResult(result, payload, i)));
proms.push(result.then((r) => handleTupleResult(r, payload, i)));
}
else {
handleTupleResult(result, payload, i);
}
}
}
if (proms.length)
return Promise.all(proms).then(() => payload);
return payload;
if (proms.length) {
return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));
}
return handleTupleResults(itemResults, payload, items, input, optoutStart);
};
});
function getTupleOptStart(items, key) {
for (let i = items.length - 1; i >= 0; i--) {
if (items[i]._zod[key] !== "optional")
return i + 1;
}
return 0;
}
function handleTupleResult(result, final, index) {
if (result.issues.length) {
final.issues.push(...util.prefixIssues(index, result.issues));
}
final.value[index] = result.value;
}
function handleTupleResults(itemResults, final, items, input, optoutStart) {
// Walk results in order. Mirror $ZodObject's swallow-on-absent-optional
// rule, but only after `optoutStart`: the first index where the output
// tuple tail can be absent.
for (let i = 0; i < items.length; i++) {
const r = itemResults[i];
const isPresent = i < input.length;
if (r.issues.length) {
if (!isPresent && i >= optoutStart) {
final.value.length = i;
break;
}
final.issues.push(...util.prefixIssues(i, r.issues));
}
final.value[i] = r.value;
}
// Drop trailing slots that produced `undefined` for absent input
// (the array analog of an absent optional key on an object). The
// `i >= input.length` floor is critical: an explicit `undefined`
// *inside* the input must be preserved even when the schema is
// optional-out (e.g. `z.string().or(z.undefined())` accepting an
// explicit undefined value).
for (let i = final.value.length - 1; i >= input.length; i--) {
if (items[i]._zod.optout === "optional" && final.value[i] === undefined) {
final.value.length = i;
}
else {
break;
}
}
return final;
}
export const $ZodRecord = /*@__PURE__*/ core.$constructor("$ZodRecord", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, ctx) => {
@@ -1323,20 +1440,36 @@ export const $ZodRecord = /*@__PURE__*/ core.$constructor("$ZodRecord", (inst, d
for (const key of values) {
if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
recordKeys.add(typeof key === "number" ? key.toString() : key);
const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
if (keyResult instanceof Promise) {
throw new Error("Async schemas not supported in object keys currently");
}
if (keyResult.issues.length) {
payload.issues.push({
code: "invalid_key",
origin: "record",
issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),
input: key,
path: [key],
inst,
});
continue;
}
const outKey = keyResult.value;
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
if (result instanceof Promise) {
proms.push(result.then((result) => {
if (result.issues.length) {
payload.issues.push(...util.prefixIssues(key, result.issues));
}
payload.value[key] = result.value;
payload.value[outKey] = result.value;
}));
}
else {
if (result.issues.length) {
payload.issues.push(...util.prefixIssues(key, result.issues));
}
payload.value[key] = result.value;
payload.value[outKey] = result.value;
}
}
}
@@ -1358,9 +1491,12 @@ export const $ZodRecord = /*@__PURE__*/ core.$constructor("$ZodRecord", (inst, d
}
else {
payload.value = {};
// Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()
for (const key of Reflect.ownKeys(input)) {
if (key === "__proto__")
continue;
if (!Object.prototype.propertyIsEnumerable.call(input, key))
continue;
let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
if (keyResult instanceof Promise) {
throw new Error("Async schemas not supported in object keys currently");
@@ -1581,6 +1717,7 @@ export const $ZodFile = /*@__PURE__*/ core.$constructor("$ZodFile", (inst, def)
});
export const $ZodTransform = /*@__PURE__*/ core.$constructor("$ZodTransform", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
throw new core.$ZodEncodeError(inst.constructor.name);
@@ -1590,6 +1727,7 @@ export const $ZodTransform = /*@__PURE__*/ core.$constructor("$ZodTransform", (i
const output = _out instanceof Promise ? _out : Promise.resolve(_out);
return output.then((output) => {
payload.value = output;
payload.fallback = true;
return payload;
});
}
@@ -1597,11 +1735,12 @@ export const $ZodTransform = /*@__PURE__*/ core.$constructor("$ZodTransform", (i
throw new core.$ZodAsyncError();
}
payload.value = _out;
payload.fallback = true;
return payload;
};
});
function handleOptionalResult(result, input) {
if (result.issues.length && input === undefined) {
if (input === undefined && (result.issues.length || result.fallback)) {
return { issues: [], value: undefined };
}
return result;
@@ -1619,10 +1758,11 @@ export const $ZodOptional = /*@__PURE__*/ core.$constructor("$ZodOptional", (ins
});
inst._zod.parse = (payload, ctx) => {
if (def.innerType._zod.optin === "optional") {
const input = payload.value;
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise)
return result.then((r) => handleOptionalResult(r, payload.value));
return handleOptionalResult(result, payload.value);
return result.then((r) => handleOptionalResult(r, input));
return handleOptionalResult(result, input);
}
if (payload.value === undefined) {
return payload;
@@ -1749,7 +1889,7 @@ export const $ZodSuccess = /*@__PURE__*/ core.$constructor("$ZodSuccess", (inst,
});
export const $ZodCatch = /*@__PURE__*/ core.$constructor("$ZodCatch", (inst, def) => {
$ZodType.init(inst, def);
util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
inst._zod.optin = "optional";
util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
util.defineLazy(inst._zod, "values", () => def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
@@ -1770,6 +1910,7 @@ export const $ZodCatch = /*@__PURE__*/ core.$constructor("$ZodCatch", (inst, def
input: payload.value,
});
payload.issues = [];
payload.fallback = true;
}
return payload;
});
@@ -1784,6 +1925,7 @@ export const $ZodCatch = /*@__PURE__*/ core.$constructor("$ZodCatch", (inst, def
input: payload.value,
});
payload.issues = [];
payload.fallback = true;
}
return payload;
};
@@ -1830,7 +1972,7 @@ function handlePipeResult(left, next, ctx) {
left.aborted = true;
return left;
}
return next._zod.run({ value: left.value, issues: left.issues }, ctx);
return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);
}
export const $ZodCodec = /*@__PURE__*/ core.$constructor("$ZodCodec", (inst, def) => {
$ZodType.init(inst, def);
@@ -1886,6 +2028,9 @@ function handleCodecTxResult(left, value, nextSchema, ctx) {
}
return nextSchema._zod.run({ value, issues: left.issues }, ctx);
}
export const $ZodPreprocess = /*@__PURE__*/ core.$constructor("$ZodPreprocess", (inst, def) => {
$ZodPipe.init(inst, def);
});
export const $ZodReadonly = /*@__PURE__*/ core.$constructor("$ZodReadonly", (inst, def) => {
$ZodType.init(inst, def);
util.defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
@@ -2043,14 +2188,15 @@ export const $ZodPromise = /*@__PURE__*/ core.$constructor("$ZodPromise", (inst,
});
export const $ZodLazy = /*@__PURE__*/ core.$constructor("$ZodLazy", (inst, def) => {
$ZodType.init(inst, def);
// let _innerType!: any;
// util.defineLazy(def, "getter", () => {
// if (!_innerType) {
// _innerType = def.getter();
// }
// return () => _innerType;
// });
util.defineLazy(inst._zod, "innerType", () => def.getter());
// Cache the resolved inner type on the shared `def` so all clones of this
// lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,
// preserving identity for cycle detection on recursive schemas.
util.defineLazy(inst._zod, "innerType", () => {
const d = def;
if (!d._cachedInner)
d._cachedInner = def.getter();
return d._cachedInner;
});
util.defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern);
util.defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues);
util.defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? undefined);
+12 -1
View File
@@ -93,7 +93,7 @@ function process(schema, ctx, _params = { path: [], schemaPath: [] }) {
delete result.schema.default;
}
// set prefault as default
if (ctx.io === "input" && result.schema._prefault)
if (ctx.io === "input" && "_prefault" in result.schema)
(_a = result.schema).default ?? (_a.default = result.schema._prefault);
delete result.schema._prefault;
// pulling fresh from ctx.seen in case it was overwritten
@@ -325,11 +325,20 @@ function finalize(ctx, schema) {
result.$id = ctx.external.uri(id);
}
Object.assign(result, root.def ?? root.schema);
// The `id` in `.meta()` is a Zod-specific registration tag used to extract
// schemas into $defs — it is not user-facing JSON Schema metadata. Strip it
// from the output body where it would otherwise leak. The id is preserved
// implicitly via the $defs key (and via $ref paths).
const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
if (rootMetaId !== undefined && result.id === rootMetaId)
delete result.id;
// build defs object
const defs = ctx.external?.defs ?? {};
for (const entry of ctx.seen.entries()) {
const seen = entry[1];
if (seen.def && seen.defId) {
if (seen.def.id === seen.defId)
delete seen.def.id;
defs[seen.defId] = seen.def;
}
}
@@ -398,6 +407,8 @@ function isTransforming(_schema, _ctx) {
return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
}
if (def.type === "pipe") {
if (_schema._zod.traits.has("$ZodCodec"))
return true;
return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
}
if (def.type === "object") {
+12 -1
View File
@@ -86,7 +86,7 @@ export function process(schema, ctx, _params = { path: [], schemaPath: [] }) {
delete result.schema.default;
}
// set prefault as default
if (ctx.io === "input" && result.schema._prefault)
if (ctx.io === "input" && "_prefault" in result.schema)
(_a = result.schema).default ?? (_a.default = result.schema._prefault);
delete result.schema._prefault;
// pulling fresh from ctx.seen in case it was overwritten
@@ -318,11 +318,20 @@ export function finalize(ctx, schema) {
result.$id = ctx.external.uri(id);
}
Object.assign(result, root.def ?? root.schema);
// The `id` in `.meta()` is a Zod-specific registration tag used to extract
// schemas into $defs — it is not user-facing JSON Schema metadata. Strip it
// from the output body where it would otherwise leak. The id is preserved
// implicitly via the $defs key (and via $ref paths).
const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
if (rootMetaId !== undefined && result.id === rootMetaId)
delete result.id;
// build defs object
const defs = ctx.external?.defs ?? {};
for (const entry of ctx.seen.entries()) {
const seen = entry[1];
if (seen.def && seen.defId) {
if (seen.def.id === seen.defId)
delete seen.def.id;
defs[seen.defId] = seen.def;
}
}
@@ -391,6 +400,8 @@ function isTransforming(_schema, _ctx) {
return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
}
if (def.type === "pipe") {
if (_schema._zod.traits.has("$ZodCodec"))
return true;
return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
}
if (def.type === "object") {
+53 -29
View File
@@ -41,6 +41,7 @@ exports.merge = merge;
exports.partial = partial;
exports.required = required;
exports.aborted = aborted;
exports.explicitlyAborted = explicitlyAborted;
exports.prefixIssues = prefixIssues;
exports.unwrapMessage = unwrapMessage;
exports.finalizeIssue = finalizeIssue;
@@ -55,6 +56,7 @@ exports.base64urlToUint8Array = base64urlToUint8Array;
exports.uint8ArrayToBase64url = uint8ArrayToBase64url;
exports.hexToUint8Array = hexToUint8Array;
exports.uint8ArrayToHex = uint8ArrayToHex;
const core_js_1 = require("./core.cjs");
// functions
function assertEqual(val) {
return val;
@@ -104,21 +106,15 @@ function cleanRegex(source) {
return source.slice(start, end);
}
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepString = step.toString();
let stepDecCount = (stepString.split(".")[1] || "").length;
if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
const match = stepString.match(/\d?e-(\d?)/);
if (match?.[1]) {
stepDecCount = Number.parseInt(match[1]);
}
}
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return (valInt % stepInt) / 10 ** decCount;
const ratio = val / step;
const roundedRatio = Math.round(ratio);
// Use a relative epsilon scaled to the magnitude of the result
const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
if (Math.abs(ratio - roundedRatio) < tolerance)
return 0;
return ratio - roundedRatio;
}
const EVALUATING = Symbol("evaluating");
const EVALUATING = /* @__PURE__*/ Symbol("evaluating");
function defineLazy(object, key, getter) {
let value = undefined;
Object.defineProperty(object, key, {
@@ -205,6 +201,11 @@ function isObject(data) {
return typeof data === "object" && data !== null && !Array.isArray(data);
}
exports.allowsEval = cached(() => {
// Skip the probe under `jitless`: strict CSPs report the caught `new Function`
// as a `securitypolicyviolation` even though the throw is swallowed.
if (core_js_1.globalConfig.jitless) {
return false;
}
// @ts-ignore
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
return false;
@@ -242,6 +243,10 @@ function shallowClone(o) {
return { ...o };
if (Array.isArray(o))
return [...o];
if (o instanceof Map)
return new Map(o);
if (o instanceof Set)
return new Set(o);
return o;
}
function numKeys(data) {
@@ -300,7 +305,14 @@ const getParsedType = (data) => {
};
exports.getParsedType = getParsedType;
exports.propertyKeyTypes = new Set(["string", "number", "symbol"]);
exports.primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
exports.primitiveTypes = new Set([
"string",
"number",
"bigint",
"boolean",
"symbol",
"undefined",
]);
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
@@ -472,6 +484,9 @@ function safeExtend(schema, shape) {
return clone(schema, def);
}
function merge(a, b) {
if (a._zod.def.checks?.length) {
throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
}
const def = mergeDefs(a._zod.def, {
get shape() {
const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
@@ -481,7 +496,7 @@ function merge(a, b) {
get catchall() {
return b._zod.def.catchall;
},
checks: [], // delete existing checks
checks: b._zod.def.checks ?? [],
});
return clone(a, def);
}
@@ -575,6 +590,18 @@ function aborted(x, startIndex = 0) {
}
return false;
}
// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).
// Used to respect `abort: true` in .refine() even for checks that have a `when` function.
function explicitlyAborted(x, startIndex = 0) {
if (x.aborted === true)
return true;
for (let i = startIndex; i < x.issues.length; i++) {
if (x.issues[i]?.continue === false) {
return true;
}
}
return false;
}
function prefixIssues(path, issues) {
return issues.map((iss) => {
var _a;
@@ -587,23 +614,20 @@ function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config) {
const full = { ...iss, path: iss.path ?? [] };
// for backwards compatibility
if (!iss.message) {
const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
const message = iss.message
? iss.message
: (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
unwrapMessage(ctx?.error?.(iss)) ??
unwrapMessage(config.customError?.(iss)) ??
unwrapMessage(config.localeError?.(iss)) ??
"Invalid input";
full.message = message;
"Invalid input");
const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
rest.path ?? (rest.path = []);
rest.message = message;
if (ctx?.reportInput) {
rest.input = _input;
}
// delete (full as any).def;
delete full.inst;
delete full.continue;
if (!ctx?.reportInput) {
delete full.input;
}
return full;
return rest;
}
function getSizableOrigin(input) {
if (input instanceof Set)
+1
View File
@@ -177,6 +177,7 @@ export declare function partial(Class: SchemaClass<schemas.$ZodOptional> | null,
export declare function required(Class: SchemaClass<schemas.$ZodNonOptional>, schema: schemas.$ZodObject, mask: object | undefined): any;
export type Constructor<T, Def extends any[] = any[]> = new (...args: Def) => T;
export declare function aborted(x: schemas.ParsePayload, startIndex?: number): boolean;
export declare function explicitlyAborted(x: schemas.ParsePayload, startIndex?: number): boolean;
export declare function prefixIssues(path: PropertyKey, issues: errors.$ZodRawIssue[]): errors.$ZodRawIssue[];
export declare function unwrapMessage(message: string | {
message: string;
+1
View File
@@ -177,6 +177,7 @@ export declare function partial(Class: SchemaClass<schemas.$ZodOptional> | null,
export declare function required(Class: SchemaClass<schemas.$ZodNonOptional>, schema: schemas.$ZodObject, mask: object | undefined): any;
export type Constructor<T, Def extends any[] = any[]> = new (...args: Def) => T;
export declare function aborted(x: schemas.ParsePayload, startIndex?: number): boolean;
export declare function explicitlyAborted(x: schemas.ParsePayload, startIndex?: number): boolean;
export declare function prefixIssues(path: PropertyKey, issues: errors.$ZodRawIssue[]): errors.$ZodRawIssue[];
export declare function unwrapMessage(message: string | {
message: string;
+54 -31
View File
@@ -1,3 +1,4 @@
import { globalConfig } from "./core.js";
// functions
export function assertEqual(val) {
return val;
@@ -47,21 +48,15 @@ export function cleanRegex(source) {
return source.slice(start, end);
}
export function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepString = step.toString();
let stepDecCount = (stepString.split(".")[1] || "").length;
if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
const match = stepString.match(/\d?e-(\d?)/);
if (match?.[1]) {
stepDecCount = Number.parseInt(match[1]);
}
}
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return (valInt % stepInt) / 10 ** decCount;
const ratio = val / step;
const roundedRatio = Math.round(ratio);
// Use a relative epsilon scaled to the magnitude of the result
const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
if (Math.abs(ratio - roundedRatio) < tolerance)
return 0;
return ratio - roundedRatio;
}
const EVALUATING = Symbol("evaluating");
const EVALUATING = /* @__PURE__*/ Symbol("evaluating");
export function defineLazy(object, key, getter) {
let value = undefined;
Object.defineProperty(object, key, {
@@ -147,7 +142,12 @@ export const captureStackTrace = ("captureStackTrace" in Error ? Error.captureSt
export function isObject(data) {
return typeof data === "object" && data !== null && !Array.isArray(data);
}
export const allowsEval = cached(() => {
export const allowsEval = /* @__PURE__*/ cached(() => {
// Skip the probe under `jitless`: strict CSPs report the caught `new Function`
// as a `securitypolicyviolation` even though the throw is swallowed.
if (globalConfig.jitless) {
return false;
}
// @ts-ignore
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
return false;
@@ -185,6 +185,10 @@ export function shallowClone(o) {
return { ...o };
if (Array.isArray(o))
return [...o];
if (o instanceof Map)
return new Map(o);
if (o instanceof Set)
return new Set(o);
return o;
}
export function numKeys(data) {
@@ -241,8 +245,15 @@ export const getParsedType = (data) => {
throw new Error(`Unknown data type: ${t}`);
}
};
export const propertyKeyTypes = new Set(["string", "number", "symbol"]);
export const primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
export const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]);
export const primitiveTypes = /* @__PURE__*/ new Set([
"string",
"number",
"bigint",
"boolean",
"symbol",
"undefined",
]);
export function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
@@ -414,6 +425,9 @@ export function safeExtend(schema, shape) {
return clone(schema, def);
}
export function merge(a, b) {
if (a._zod.def.checks?.length) {
throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
}
const def = mergeDefs(a._zod.def, {
get shape() {
const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
@@ -423,7 +437,7 @@ export function merge(a, b) {
get catchall() {
return b._zod.def.catchall;
},
checks: [], // delete existing checks
checks: b._zod.def.checks ?? [],
});
return clone(a, def);
}
@@ -517,6 +531,18 @@ export function aborted(x, startIndex = 0) {
}
return false;
}
// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).
// Used to respect `abort: true` in .refine() even for checks that have a `when` function.
export function explicitlyAborted(x, startIndex = 0) {
if (x.aborted === true)
return true;
for (let i = startIndex; i < x.issues.length; i++) {
if (x.issues[i]?.continue === false) {
return true;
}
}
return false;
}
export function prefixIssues(path, issues) {
return issues.map((iss) => {
var _a;
@@ -529,23 +555,20 @@ export function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
export function finalizeIssue(iss, ctx, config) {
const full = { ...iss, path: iss.path ?? [] };
// for backwards compatibility
if (!iss.message) {
const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
const message = iss.message
? iss.message
: (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
unwrapMessage(ctx?.error?.(iss)) ??
unwrapMessage(config.customError?.(iss)) ??
unwrapMessage(config.localeError?.(iss)) ??
"Invalid input";
full.message = message;
"Invalid input");
const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
rest.path ?? (rest.path = []);
rest.message = message;
if (ctx?.reportInput) {
rest.input = _input;
}
// delete (full as any).def;
delete full.inst;
delete full.continue;
if (!ctx?.reportInput) {
delete full.input;
}
return full;
return rest;
}
export function getSizableOrigin(input) {
if (input instanceof Set)
+2 -2
View File
@@ -3,6 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
exports.version = void 0;
exports.version = {
major: 4,
minor: 3,
patch: 6,
minor: 4,
patch: 3,
};
+1 -1
View File
@@ -1,5 +1,5 @@
export declare const version: {
readonly major: 4;
readonly minor: 3;
readonly minor: 4;
readonly patch: number;
};
+1 -1
View File
@@ -1,5 +1,5 @@
export declare const version: {
readonly major: 4;
readonly minor: 3;
readonly minor: 4;
readonly patch: number;
};
+2 -2
View File
@@ -1,5 +1,5 @@
export const version = {
major: 4,
minor: 3,
patch: 6,
minor: 4,
patch: 3,
};