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
+2 -2
View File
@@ -40,8 +40,8 @@ const initializer = (inst, issues) => {
// },
// });
};
export const ZodError = core.$constructor("ZodError", initializer);
export const ZodRealError = core.$constructor("ZodError", initializer, {
export const ZodError = /*@__PURE__*/ core.$constructor("ZodError", initializer);
export const ZodRealError = /*@__PURE__*/ core.$constructor("ZodError", initializer, {
Parent: Error,
});
// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
+1
View File
@@ -5,6 +5,7 @@ export * from "./errors.cjs";
export * from "./parse.cjs";
export * from "./compat.cjs";
export type { infer, output, input } from "../core/index.cjs";
export type { JSONType } from "../core/util.cjs";
export { globalRegistry, type GlobalMeta, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from "../core/index.cjs";
export { toJSONSchema } from "../core/json-schema-processors.cjs";
export { fromJSONSchema } from "./from-json-schema.cjs";
+1
View File
@@ -5,6 +5,7 @@ export * from "./errors.js";
export * from "./parse.js";
export * from "./compat.js";
export type { infer, output, input } from "../core/index.js";
export type { JSONType } from "../core/util.js";
export { globalRegistry, type GlobalMeta, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from "../core/index.js";
export { toJSONSchema } from "../core/json-schema-processors.js";
export { fromJSONSchema } from "./from-json-schema.js";
+31 -16
View File
@@ -35,7 +35,7 @@ const z = {
iso: _iso,
};
// Keys that are recognized and handled by the conversion logic
const RECOGNIZED_KEYS = new Set([
const RECOGNIZED_KEYS = /*@__PURE__*/ new Set([
// Schema identification
"$schema",
"$ref",
@@ -511,13 +511,6 @@ function convertBaseSchema(schema, ctx) {
default:
throw new Error(`Unsupported type: ${type}`);
}
// Apply metadata
if (schema.description) {
zodSchema = zodSchema.describe(schema.description);
}
if (schema.default !== undefined) {
zodSchema = zodSchema.default(schema.default);
}
return zodSchema;
}
function convertSchema(schema, ctx) {
@@ -562,23 +555,28 @@ function convertSchema(schema, ctx) {
if (schema.readOnly === true) {
baseSchema = z.readonly(baseSchema);
}
// Collect metadata: core schema keywords and unrecognized keys
// Apply `default` so it wraps the fully-composed schema. This ensures
// `parse(undefined) -> default` works regardless of which branch of
// `convertBaseSchema` produced the inner schema (enum/const/not/typed/etc.).
if (schema.default !== undefined) {
baseSchema = baseSchema.default(schema.default);
}
// Collect non-description annotation metadata into the user-supplied
// registry. Description is handled separately below via `.describe()` to
// preserve the contract that `schema.description` reads from globalRegistry.
const extraMeta = {};
// Core schema keywords that should be captured as metadata
const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
for (const key of coreMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
// Content keywords - store as metadata
const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
for (const key of contentMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
// Unrecognized keys (custom metadata)
for (const key of Object.keys(schema)) {
if (!RECOGNIZED_KEYS.has(key)) {
extraMeta[key] = schema[key];
@@ -587,6 +585,12 @@ function convertSchema(schema, ctx) {
if (Object.keys(extraMeta).length > 0) {
ctx.registry.add(baseSchema, extraMeta);
}
// Apply description last. `.describe()` clones the schema and sets
// `_zod.parent` on the clone, so registry lookups on the returned reference
// still resolve `extraMeta` via parent inheritance.
if (schema.description) {
baseSchema = baseSchema.describe(schema.description);
}
return baseSchema;
}
/**
@@ -596,15 +600,26 @@ function fromJSONSchema(schema, params) {
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
const version = detectVersion(schema, params?.defaultTarget);
const defs = (schema.$defs || schema.definitions || {});
// Normalize input via a JSON round-trip. This guarantees the converter
// walks a plain, finite, JSON-valid object graph: cyclic inputs fail here,
// getter/Proxy-based properties are materialized into static values, and
// class instances collapse to plain objects.
let normalized;
try {
normalized = JSON.parse(JSON.stringify(schema));
}
catch {
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
}
const version = detectVersion(normalized, params?.defaultTarget);
const defs = (normalized.$defs || normalized.definitions || {});
const ctx = {
version,
defs,
refs: new Map(),
processing: new Set(),
rootSchema: schema,
rootSchema: normalized,
registry: params?.registry ?? registries_js_1.globalRegistry,
};
return convertSchema(schema, ctx);
return convertSchema(normalized, ctx);
}
+31 -16
View File
@@ -9,7 +9,7 @@ const z = {
iso: _iso,
};
// Keys that are recognized and handled by the conversion logic
const RECOGNIZED_KEYS = new Set([
const RECOGNIZED_KEYS = /*@__PURE__*/ new Set([
// Schema identification
"$schema",
"$ref",
@@ -485,13 +485,6 @@ function convertBaseSchema(schema, ctx) {
default:
throw new Error(`Unsupported type: ${type}`);
}
// Apply metadata
if (schema.description) {
zodSchema = zodSchema.describe(schema.description);
}
if (schema.default !== undefined) {
zodSchema = zodSchema.default(schema.default);
}
return zodSchema;
}
function convertSchema(schema, ctx) {
@@ -536,23 +529,28 @@ function convertSchema(schema, ctx) {
if (schema.readOnly === true) {
baseSchema = z.readonly(baseSchema);
}
// Collect metadata: core schema keywords and unrecognized keys
// Apply `default` so it wraps the fully-composed schema. This ensures
// `parse(undefined) -> default` works regardless of which branch of
// `convertBaseSchema` produced the inner schema (enum/const/not/typed/etc.).
if (schema.default !== undefined) {
baseSchema = baseSchema.default(schema.default);
}
// Collect non-description annotation metadata into the user-supplied
// registry. Description is handled separately below via `.describe()` to
// preserve the contract that `schema.description` reads from globalRegistry.
const extraMeta = {};
// Core schema keywords that should be captured as metadata
const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
for (const key of coreMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
// Content keywords - store as metadata
const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
for (const key of contentMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
// Unrecognized keys (custom metadata)
for (const key of Object.keys(schema)) {
if (!RECOGNIZED_KEYS.has(key)) {
extraMeta[key] = schema[key];
@@ -561,6 +559,12 @@ function convertSchema(schema, ctx) {
if (Object.keys(extraMeta).length > 0) {
ctx.registry.add(baseSchema, extraMeta);
}
// Apply description last. `.describe()` clones the schema and sets
// `_zod.parent` on the clone, so registry lookups on the returned reference
// still resolve `extraMeta` via parent inheritance.
if (schema.description) {
baseSchema = baseSchema.describe(schema.description);
}
return baseSchema;
}
/**
@@ -570,15 +574,26 @@ export function fromJSONSchema(schema, params) {
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
const version = detectVersion(schema, params?.defaultTarget);
const defs = (schema.$defs || schema.definitions || {});
// Normalize input via a JSON round-trip. This guarantees the converter
// walks a plain, finite, JSON-valid object graph: cyclic inputs fail here,
// getter/Proxy-based properties are materialized into static values, and
// class instances collapse to plain objects.
let normalized;
try {
normalized = JSON.parse(JSON.stringify(schema));
}
catch {
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
}
const version = detectVersion(normalized, params?.defaultTarget);
const defs = (normalized.$defs || normalized.definitions || {});
const ctx = {
version,
defs,
refs: new Map(),
processing: new Set(),
rootSchema: schema,
rootSchema: normalized,
registry: params?.registry ?? globalRegistry,
};
return convertSchema(schema, ctx);
return convertSchema(normalized, ctx);
}
+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
}
+358 -119
View File
@@ -24,7 +24,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodLiteral = exports.ZodEnum = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodXor = exports.ZodUnion = 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.ZodIPv6 = exports.ZodMAC = exports.ZodIPv4 = exports.ZodKSUID = exports.ZodXID = exports.ZodULID = exports.ZodCUID2 = exports.ZodCUID = exports.ZodNanoID = exports.ZodEmoji = exports.ZodURL = exports.ZodUUID = exports.ZodGUID = exports.ZodEmail = exports.ZodStringFormat = exports.ZodString = exports._ZodString = exports.ZodType = void 0;
exports.stringbool = exports.meta = exports.describe = exports.ZodCustom = exports.ZodFunction = exports.ZodPromise = exports.ZodLazy = 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 = void 0;
exports.stringbool = exports.meta = exports.describe = exports.ZodCustom = exports.ZodFunction = exports.ZodPromise = exports.ZodLazy = 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 = void 0;
exports.string = string;
exports.email = email;
exports.guid = guid;
@@ -104,6 +104,7 @@ exports.catch = _catch;
exports.nan = nan;
exports.pipe = pipe;
exports.codec = codec;
exports.invertCodec = invertCodec;
exports.readonly = readonly;
exports.templateLiteral = templateLiteral;
exports.lazy = lazy;
@@ -126,6 +127,54 @@ const to_json_schema_js_1 = require("../core/to-json-schema.cjs");
const checks = __importStar(require("./checks.cjs"));
const iso = __importStar(require("./iso.cjs"));
const parse = __importStar(require("./parse.cjs"));
// Lazy-bind builder methods.
//
// Builder methods (`.optional`, `.array`, `.refine`, ...) live as
// non-enumerable getters on each concrete schema constructor's
// prototype. On first access from an instance the getter allocates
// `fn.bind(this)` and caches it as an own property on that instance,
// so detached usage (`const m = schema.optional; m()`) still works
// and the per-instance allocation only happens for methods actually
// touched.
//
// One install per (prototype, group), memoized by `_installedGroups`.
const _installedGroups = /* @__PURE__ */ new WeakMap();
function _installLazyMethods(inst, group, methods) {
const proto = Object.getPrototypeOf(inst);
let installed = _installedGroups.get(proto);
if (!installed) {
installed = new Set();
_installedGroups.set(proto, installed);
}
if (installed.has(group))
return;
installed.add(group);
for (const key in methods) {
const fn = methods[key];
Object.defineProperty(proto, key, {
configurable: true,
enumerable: false,
get() {
const bound = fn.bind(this);
Object.defineProperty(this, key, {
configurable: true,
writable: true,
enumerable: true,
value: bound,
});
return bound;
},
set(v) {
Object.defineProperty(this, key, {
configurable: true,
writable: true,
enumerable: true,
value: v,
});
},
});
}
}
exports.ZodType = core.$constructor("ZodType", (inst, def) => {
core.$ZodType.init(inst, def);
Object.assign(inst["~standard"], {
@@ -138,31 +187,16 @@ exports.ZodType = core.$constructor("ZodType", (inst, def) => {
inst.def = def;
inst.type = def.type;
Object.defineProperty(inst, "_def", { value: def });
// base methods
inst.check = (...checks) => {
return inst.clone(index_js_1.util.mergeDefs(def, {
checks: [
...(def.checks ?? []),
...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
],
}), {
parent: true,
});
};
inst.with = inst.check;
inst.clone = (def, params) => core.clone(inst, def, params);
inst.brand = () => inst;
inst.register = ((reg, meta) => {
reg.add(inst, meta);
return inst;
});
// parsing
// Parse-family is intentionally kept as per-instance closures: these are
// the hot path AND the most-detached methods (`arr.map(schema.parse)`,
// `const { parse } = schema`, etc.). Eager closures here mean callers pay
// ~12 closure allocations per schema but get monomorphic call sites and
// detached usage that "just works".
inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });
inst.safeParse = (data, params) => parse.safeParse(inst, data, params);
inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });
inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);
inst.spa = inst.safeParseAsync;
// encoding/decoding
inst.encode = (data, params) => parse.encode(inst, data, params);
inst.decode = (data, params) => parse.decode(inst, data, params);
inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);
@@ -171,50 +205,118 @@ exports.ZodType = core.$constructor("ZodType", (inst, def) => {
inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);
inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);
inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);
// refinements
inst.refine = (check, params) => inst.check(refine(check, params));
inst.superRefine = (refinement) => inst.check(superRefine(refinement));
inst.overwrite = (fn) => inst.check(checks.overwrite(fn));
// wrappers
inst.optional = () => optional(inst);
inst.exactOptional = () => exactOptional(inst);
inst.nullable = () => nullable(inst);
inst.nullish = () => optional(nullable(inst));
inst.nonoptional = (params) => nonoptional(inst, params);
inst.array = () => array(inst);
inst.or = (arg) => union([inst, arg]);
inst.and = (arg) => intersection(inst, arg);
inst.transform = (tx) => pipe(inst, transform(tx));
inst.default = (def) => _default(inst, def);
inst.prefault = (def) => prefault(inst, def);
// inst.coalesce = (def, params) => coalesce(inst, def, params);
inst.catch = (params) => _catch(inst, params);
inst.pipe = (target) => pipe(inst, target);
inst.readonly = () => readonly(inst);
// meta
inst.describe = (description) => {
const cl = inst.clone();
core.globalRegistry.add(cl, { description });
return cl;
};
// All builder methods are placed on the internal prototype as lazy-bind
// getters. On first access per-instance, a bound thunk is allocated and
// cached as an own property; subsequent accesses skip the getter. This
// means: no per-instance allocation for unused methods, full
// detachability preserved (`const m = schema.optional; m()` works), and
// shared underlying function references across all instances.
_installLazyMethods(inst, "ZodType", {
check(...chks) {
const def = this.def;
return this.clone(index_js_1.util.mergeDefs(def, {
checks: [
...(def.checks ?? []),
...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
],
}), { parent: true });
},
with(...chks) {
return this.check(...chks);
},
clone(def, params) {
return core.clone(this, def, params);
},
brand() {
return this;
},
register(reg, meta) {
reg.add(this, meta);
return this;
},
refine(check, params) {
return this.check(refine(check, params));
},
superRefine(refinement, params) {
return this.check(superRefine(refinement, params));
},
overwrite(fn) {
return this.check(checks.overwrite(fn));
},
optional() {
return optional(this);
},
exactOptional() {
return exactOptional(this);
},
nullable() {
return nullable(this);
},
nullish() {
return optional(nullable(this));
},
nonoptional(params) {
return nonoptional(this, params);
},
array() {
return array(this);
},
or(arg) {
return union([this, arg]);
},
and(arg) {
return intersection(this, arg);
},
transform(tx) {
return pipe(this, transform(tx));
},
default(d) {
return _default(this, d);
},
prefault(d) {
return prefault(this, d);
},
catch(params) {
return _catch(this, params);
},
pipe(target) {
return pipe(this, target);
},
readonly() {
return readonly(this);
},
describe(description) {
const cl = this.clone();
core.globalRegistry.add(cl, { description });
return cl;
},
meta(...args) {
// overloaded: meta() returns the registered metadata, meta(data)
// returns a clone with `data` registered. The mapped type picks
// up the second overload, so we accept variadic any-args and
// return `any` to satisfy both at runtime.
if (args.length === 0)
return core.globalRegistry.get(this);
const cl = this.clone();
core.globalRegistry.add(cl, args[0]);
return cl;
},
isOptional() {
return this.safeParse(undefined).success;
},
isNullable() {
return this.safeParse(null).success;
},
apply(fn) {
return fn(this);
},
});
Object.defineProperty(inst, "description", {
get() {
return core.globalRegistry.get(inst)?.description;
},
configurable: true,
});
inst.meta = (...args) => {
if (args.length === 0) {
return core.globalRegistry.get(inst);
}
const cl = inst.clone();
core.globalRegistry.add(cl, args[0]);
return cl;
};
// helpers
inst.isOptional = () => inst.safeParse(undefined).success;
inst.isNullable = () => inst.safeParse(null).success;
inst.apply = (fn) => fn(inst);
return inst;
});
/** @internal */
@@ -226,23 +328,53 @@ exports._ZodString = core.$constructor("_ZodString", (inst, def) => {
inst.format = bag.format ?? null;
inst.minLength = bag.minimum ?? null;
inst.maxLength = bag.maximum ?? null;
// validations
inst.regex = (...args) => inst.check(checks.regex(...args));
inst.includes = (...args) => inst.check(checks.includes(...args));
inst.startsWith = (...args) => inst.check(checks.startsWith(...args));
inst.endsWith = (...args) => inst.check(checks.endsWith(...args));
inst.min = (...args) => inst.check(checks.minLength(...args));
inst.max = (...args) => inst.check(checks.maxLength(...args));
inst.length = (...args) => inst.check(checks.length(...args));
inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));
inst.lowercase = (params) => inst.check(checks.lowercase(params));
inst.uppercase = (params) => inst.check(checks.uppercase(params));
// transforms
inst.trim = () => inst.check(checks.trim());
inst.normalize = (...args) => inst.check(checks.normalize(...args));
inst.toLowerCase = () => inst.check(checks.toLowerCase());
inst.toUpperCase = () => inst.check(checks.toUpperCase());
inst.slugify = () => inst.check(checks.slugify());
_installLazyMethods(inst, "_ZodString", {
regex(...args) {
return this.check(checks.regex(...args));
},
includes(...args) {
return this.check(checks.includes(...args));
},
startsWith(...args) {
return this.check(checks.startsWith(...args));
},
endsWith(...args) {
return this.check(checks.endsWith(...args));
},
min(...args) {
return this.check(checks.minLength(...args));
},
max(...args) {
return this.check(checks.maxLength(...args));
},
length(...args) {
return this.check(checks.length(...args));
},
nonempty(...args) {
return this.check(checks.minLength(1, ...args));
},
lowercase(params) {
return this.check(checks.lowercase(params));
},
uppercase(params) {
return this.check(checks.uppercase(params));
},
trim() {
return this.check(checks.trim());
},
normalize(...args) {
return this.check(checks.normalize(...args));
},
toLowerCase() {
return this.check(checks.toLowerCase());
},
toUpperCase() {
return this.check(checks.toUpperCase());
},
slugify() {
return this.check(checks.slugify());
},
});
});
exports.ZodString = core.$constructor("ZodString", (inst, def) => {
core.$ZodString.init(inst, def);
@@ -328,7 +460,7 @@ function url(params) {
}
function httpUrl(params) {
return core._url(exports.ZodURL, {
protocol: /^https?$/,
protocol: core.regexes.httpProtocol,
hostname: core.regexes.domain,
...index_js_1.util.normalizeParams(params),
});
@@ -349,11 +481,23 @@ exports.ZodNanoID = core.$constructor("ZodNanoID", (inst, def) => {
function nanoid(params) {
return core._nanoid(exports.ZodNanoID, params);
}
/**
* @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) => {
// ZodStringFormat.init(inst, def);
core.$ZodCUID.init(inst, def);
exports.ZodStringFormat.init(inst, def);
});
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
function cuid(params) {
return core._cuid(exports.ZodCUID, params);
}
@@ -485,22 +629,53 @@ exports.ZodNumber = core.$constructor("ZodNumber", (inst, def) => {
core.$ZodNumber.init(inst, def);
exports.ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);
inst.gt = (value, params) => inst.check(checks.gt(value, params));
inst.gte = (value, params) => inst.check(checks.gte(value, params));
inst.min = (value, params) => inst.check(checks.gte(value, params));
inst.lt = (value, params) => inst.check(checks.lt(value, params));
inst.lte = (value, params) => inst.check(checks.lte(value, params));
inst.max = (value, params) => inst.check(checks.lte(value, params));
inst.int = (params) => inst.check(int(params));
inst.safe = (params) => inst.check(int(params));
inst.positive = (params) => inst.check(checks.gt(0, params));
inst.nonnegative = (params) => inst.check(checks.gte(0, params));
inst.negative = (params) => inst.check(checks.lt(0, params));
inst.nonpositive = (params) => inst.check(checks.lte(0, params));
inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));
inst.step = (value, params) => inst.check(checks.multipleOf(value, params));
// inst.finite = (params) => inst.check(core.finite(params));
inst.finite = () => inst;
_installLazyMethods(inst, "ZodNumber", {
gt(value, params) {
return this.check(checks.gt(value, params));
},
gte(value, params) {
return this.check(checks.gte(value, params));
},
min(value, params) {
return this.check(checks.gte(value, params));
},
lt(value, params) {
return this.check(checks.lt(value, params));
},
lte(value, params) {
return this.check(checks.lte(value, params));
},
max(value, params) {
return this.check(checks.lte(value, params));
},
int(params) {
return this.check(int(params));
},
safe(params) {
return this.check(int(params));
},
positive(params) {
return this.check(checks.gt(0, params));
},
nonnegative(params) {
return this.check(checks.gte(0, params));
},
negative(params) {
return this.check(checks.lt(0, params));
},
nonpositive(params) {
return this.check(checks.lte(0, params));
},
multipleOf(value, params) {
return this.check(checks.multipleOf(value, params));
},
step(value, params) {
return this.check(checks.multipleOf(value, params));
},
finite() {
return this;
},
});
const bag = inst._zod.bag;
inst.minValue =
Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
@@ -651,11 +826,23 @@ exports.ZodArray = core.$constructor("ZodArray", (inst, def) => {
exports.ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);
inst.element = def.element;
inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));
inst.nonempty = (params) => inst.check(checks.minLength(1, params));
inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));
inst.length = (len, params) => inst.check(checks.length(len, params));
inst.unwrap = () => inst.element;
_installLazyMethods(inst, "ZodArray", {
min(n, params) {
return this.check(checks.minLength(n, params));
},
nonempty(params) {
return this.check(checks.minLength(1, params));
},
max(n, params) {
return this.check(checks.maxLength(n, params));
},
length(n, params) {
return this.check(checks.length(n, params));
},
unwrap() {
return this.element;
},
});
});
function array(element, params) {
return core._array(exports.ZodArray, element, params);
@@ -672,23 +859,47 @@ exports.ZodObject = core.$constructor("ZodObject", (inst, def) => {
index_js_1.util.defineLazy(inst, "shape", () => {
return def.shape;
});
inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });
inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });
inst.extend = (incoming) => {
return index_js_1.util.extend(inst, incoming);
};
inst.safeExtend = (incoming) => {
return index_js_1.util.safeExtend(inst, incoming);
};
inst.merge = (other) => index_js_1.util.merge(inst, other);
inst.pick = (mask) => index_js_1.util.pick(inst, mask);
inst.omit = (mask) => index_js_1.util.omit(inst, mask);
inst.partial = (...args) => index_js_1.util.partial(exports.ZodOptional, inst, args[0]);
inst.required = (...args) => index_js_1.util.required(exports.ZodNonOptional, inst, args[0]);
_installLazyMethods(inst, "ZodObject", {
keyof() {
return _enum(Object.keys(this._zod.def.shape));
},
catchall(catchall) {
return this.clone({ ...this._zod.def, catchall: catchall });
},
passthrough() {
return this.clone({ ...this._zod.def, catchall: unknown() });
},
loose() {
return this.clone({ ...this._zod.def, catchall: unknown() });
},
strict() {
return this.clone({ ...this._zod.def, catchall: never() });
},
strip() {
return this.clone({ ...this._zod.def, catchall: undefined });
},
extend(incoming) {
return index_js_1.util.extend(this, incoming);
},
safeExtend(incoming) {
return index_js_1.util.safeExtend(this, incoming);
},
merge(other) {
return index_js_1.util.merge(this, other);
},
pick(mask) {
return index_js_1.util.pick(this, mask);
},
omit(mask) {
return index_js_1.util.omit(this, mask);
},
partial(...args) {
return index_js_1.util.partial(exports.ZodOptional, this, args[0]);
},
required(...args) {
return index_js_1.util.required(exports.ZodNonOptional, this, args[0]);
},
});
});
function object(shape, params) {
const def = {
@@ -799,6 +1010,15 @@ exports.ZodRecord = core.$constructor("ZodRecord", (inst, def) => {
inst.valueType = def.valueType;
});
function record(keyType, valueType, params) {
// v3-compat: z.record(valueType, params?) — defaults keyType to z.string()
if (!valueType || !valueType._zod) {
return new exports.ZodRecord({
type: "record",
keyType: string(),
valueType: keyType,
...index_js_1.util.normalizeParams(valueType),
});
}
return new exports.ZodRecord({
type: "record",
keyType,
@@ -983,10 +1203,12 @@ exports.ZodTransform = core.$constructor("ZodTransform", (inst, def) => {
if (output instanceof Promise) {
return output.then((output) => {
payload.value = output;
payload.fallback = true;
return payload;
});
}
payload.value = output;
payload.fallback = true;
return payload;
};
});
@@ -1142,6 +1364,20 @@ function codec(in_, out, params) {
reverseTransform: params.encode,
});
}
function invertCodec(codec) {
const def = codec._zod.def;
return new exports.ZodCodec({
type: "pipe",
in: def.out,
out: def.in,
transform: def.reverseTransform,
reverseTransform: def.transform,
});
}
exports.ZodPreprocess = core.$constructor("ZodPreprocess", (inst, def) => {
exports.ZodPipe.init(inst, def);
core.$ZodPreprocess.init(inst, def);
});
exports.ZodReadonly = core.$constructor("ZodReadonly", (inst, def) => {
core.$ZodReadonly.init(inst, def);
exports.ZodType.init(inst, def);
@@ -1223,8 +1459,8 @@ function refine(fn, _params = {}) {
return core._refine(exports.ZodCustom, fn, _params);
}
// superRefine
function superRefine(fn) {
return core._superRefine(fn);
function superRefine(fn, params) {
return core._superRefine(fn, params);
}
// Re-export describe and meta from core
exports.describe = core.describe;
@@ -1266,7 +1502,10 @@ function json(params) {
return jsonSchema;
}
// preprocess
// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */
function preprocess(fn, schema) {
return pipe(transform(fn), schema);
return new exports.ZodPreprocess({
type: "pipe",
in: transform(fn),
out: schema,
});
}
+42 -14
View File
@@ -36,7 +36,7 @@ export interface ZodType<out Output = unknown, out Input = unknown, out Internal
safeEncodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.input<this>>>;
safeDecodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
refine<Ch extends (arg: core.output<this>) => unknown | Promise<unknown>>(check: Ch, params?: string | core.$ZodCustomParams): Ch extends (arg: any) => arg is infer R ? this & ZodType<R, core.input<this>> : this;
superRefine(refinement: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => void | Promise<void>): this;
superRefine(refinement: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): this;
overwrite(fn: (x: core.output<this>) => core.output<this>): this;
optional(): ZodOptional<this>;
exactOptional(): ZodExactOptional<this>;
@@ -129,7 +129,11 @@ export interface ZodString extends _ZodString<core.$ZodStringInternals<string>>
nanoid(params?: string | core.$ZodCheckNanoIDParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/** @deprecated Use `z.cuid()` instead. */
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use `z.cuid2()` instead.
* See https://github.com/paralleldrive/cuid.
*/
cuid(params?: string | core.$ZodCheckCUIDParams): this;
/** @deprecated Use `z.cuid2()` instead. */
cuid2(params?: string | core.$ZodCheckCUID2Params): this;
@@ -202,10 +206,27 @@ export interface ZodNanoID extends ZodStringFormat<"nanoid"> {
}
export declare const ZodNanoID: core.$constructor<ZodNanoID>;
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export interface ZodCUID extends ZodStringFormat<"cuid"> {
_zod: core.$ZodCUIDInternals;
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const ZodCUID: core.$constructor<ZodCUID>;
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodCUID;
export interface ZodCUID2 extends ZodStringFormat<"cuid2"> {
_zod: core.$ZodCUID2Internals;
@@ -444,8 +465,8 @@ out Shape extends core.$ZodShape = core.$ZodLooseShape, out Config extends core.
strict(): ZodObject<Shape, core.$strict>;
/** This is the default behavior. This method call is likely unnecessary. */
strip(): ZodObject<Shape, core.$strip>;
extend<U extends core.$ZodLooseShape>(shape: U): ZodObject<util.Extend<Shape, U>, Config>;
safeExtend<U extends core.$ZodLooseShape>(shape: SafeExtendShape<Shape, U> & Partial<Record<keyof Shape, core.SomeType>>): ZodObject<util.Extend<Shape, U>, Config>;
extend<U extends core.$ZodLooseShape>(shape: U): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
safeExtend<U extends core.$ZodLooseShape>(shape: SafeExtendShape<Shape, U> & Partial<Record<keyof Shape, core.SomeType>>): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
/**
* @deprecated Use [`A.extend(B.shape)`](https://zod.dev/api?id=extend) instead.
*/
@@ -453,22 +474,22 @@ out Shape extends core.$ZodShape = core.$ZodLooseShape, out Config extends core.
pick<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Pick<Shape, Extract<keyof Shape, keyof M>>>, Config>;
omit<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Omit<Shape, Extract<keyof Shape, keyof M>>>, Config>;
partial(): ZodObject<{
[k in keyof Shape]: ZodOptional<Shape[k]>;
-readonly [k in keyof Shape]: ZodOptional<Shape[k]>;
}, Config>;
partial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
[k in keyof Shape]: k extends keyof M ? ZodOptional<Shape[k]> : Shape[k];
-readonly [k in keyof Shape]: k extends keyof M ? ZodOptional<Shape[k]> : Shape[k];
}, Config>;
required(): ZodObject<{
[k in keyof Shape]: ZodNonOptional<Shape[k]>;
-readonly [k in keyof Shape]: ZodNonOptional<Shape[k]>;
}, Config>;
required<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
[k in keyof Shape]: k extends keyof M ? ZodNonOptional<Shape[k]> : Shape[k];
-readonly [k in keyof Shape]: k extends keyof M ? ZodNonOptional<Shape[k]> : Shape[k];
}, Config>;
}
export declare const ZodObject: core.$constructor<ZodObject>;
export declare function object<T extends core.$ZodLooseShape = Partial<Record<never, core.SomeType>>>(shape?: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<T, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<T, core.$loose>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$loose>;
export interface ZodUnion<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodUnionInternals<T>>, core.$ZodUnion<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
@@ -490,7 +511,7 @@ export interface ZodDiscriminatedUnion<Options extends readonly core.SomeType[]
def: core.$ZodDiscriminatedUnionDef<Options, Disc>;
}
export declare const ZodDiscriminatedUnion: core.$constructor<ZodDiscriminatedUnion>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable, ...core.$ZodTypeDiscriminable[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodDiscriminatedUnion<Types, Disc>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable<Disc>, ...core.$ZodTypeDiscriminable<Disc>[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodDiscriminatedUnion<Types, Disc>;
export interface ZodIntersection<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodIntersectionInternals<A, B>>, core.$ZodIntersection<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
@@ -575,7 +596,7 @@ export interface ZodTransform<O = unknown, I = unknown> extends _ZodType<core.$Z
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTransform: core.$constructor<ZodTransform>;
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.ParsePayload) => O): ZodTransform<Awaited<O>, I>;
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.$RefinementCtx) => O): ZodTransform<Awaited<O>, I>;
export interface ZodOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodOptionalInternals<T>>, core.$ZodOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
@@ -652,6 +673,13 @@ export declare function codec<const A extends core.SomeType, B extends core.Some
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
}): ZodCodec<A, B>;
export declare function invertCodec<A extends core.SomeType, B extends core.SomeType>(codec: ZodCodec<A, B>): ZodCodec<B, A>;
export interface ZodPreprocess<B extends core.SomeType = core.$ZodType> extends ZodPipe<core.$ZodTransform, B>, core.$ZodPreprocess<B> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodPreprocessInternals<B>;
def: core.$ZodPreprocessDef<B>;
}
export declare const ZodPreprocess: core.$constructor<ZodPreprocess>;
export interface ZodReadonly<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodReadonlyInternals<T>>, core.$ZodReadonly<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
@@ -712,7 +740,7 @@ export declare const ZodCustom: core.$constructor<ZodCustom>;
export declare function check<O = unknown>(fn: core.CheckFn<O>): core.$ZodCheck<O>;
export declare function custom<O>(fn?: (data: unknown) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodCustom<O, O>;
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
export declare const describe: typeof core.describe;
export declare const meta: typeof core.meta;
type ZodInstanceOfParams = core.Params<ZodCustom, core.$ZodIssueCustom, "type" | "check" | "checks" | "fn" | "abort" | "error" | "params" | "path">;
@@ -736,4 +764,4 @@ export interface ZodJSONSchema extends _ZodJSONSchema {
_zod: ZodJSONSchemaInternals;
}
export declare function json(params?: string | core.$ZodCustomParams): ZodJSONSchema;
export declare function preprocess<A, U extends core.SomeType, B = unknown>(fn: (arg: B, ctx: core.$RefinementCtx) => A, schema: U): ZodPipe<ZodTransform<A, B>, U>;
export declare function preprocess<A, U extends core.SomeType, B = unknown>(fn: (arg: B, ctx: core.$RefinementCtx) => A, schema: U): ZodPreprocess<U>;
+42 -14
View File
@@ -36,7 +36,7 @@ export interface ZodType<out Output = unknown, out Input = unknown, out Internal
safeEncodeAsync(data: core.output<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.input<this>>>;
safeDecodeAsync(data: core.input<this>, params?: core.ParseContext<core.$ZodIssue>): Promise<parse.ZodSafeParseResult<core.output<this>>>;
refine<Ch extends (arg: core.output<this>) => unknown | Promise<unknown>>(check: Ch, params?: string | core.$ZodCustomParams): Ch extends (arg: any) => arg is infer R ? this & ZodType<R, core.input<this>> : this;
superRefine(refinement: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => void | Promise<void>): this;
superRefine(refinement: (arg: core.output<this>, ctx: core.$RefinementCtx<core.output<this>>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): this;
overwrite(fn: (x: core.output<this>) => core.output<this>): this;
optional(): ZodOptional<this>;
exactOptional(): ZodExactOptional<this>;
@@ -129,7 +129,11 @@ export interface ZodString extends _ZodString<core.$ZodStringInternals<string>>
nanoid(params?: string | core.$ZodCheckNanoIDParams): this;
/** @deprecated Use `z.guid()` instead. */
guid(params?: string | core.$ZodCheckGUIDParams): this;
/** @deprecated Use `z.cuid()` instead. */
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use `z.cuid2()` instead.
* See https://github.com/paralleldrive/cuid.
*/
cuid(params?: string | core.$ZodCheckCUIDParams): this;
/** @deprecated Use `z.cuid2()` instead. */
cuid2(params?: string | core.$ZodCheckCUID2Params): this;
@@ -202,10 +206,27 @@ export interface ZodNanoID extends ZodStringFormat<"nanoid"> {
}
export declare const ZodNanoID: core.$constructor<ZodNanoID>;
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodNanoID;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export interface ZodCUID extends ZodStringFormat<"cuid"> {
_zod: core.$ZodCUIDInternals;
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const ZodCUID: core.$constructor<ZodCUID>;
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodCUID;
export interface ZodCUID2 extends ZodStringFormat<"cuid2"> {
_zod: core.$ZodCUID2Internals;
@@ -444,8 +465,8 @@ out Shape extends core.$ZodShape = core.$ZodLooseShape, out Config extends core.
strict(): ZodObject<Shape, core.$strict>;
/** This is the default behavior. This method call is likely unnecessary. */
strip(): ZodObject<Shape, core.$strip>;
extend<U extends core.$ZodLooseShape>(shape: U): ZodObject<util.Extend<Shape, U>, Config>;
safeExtend<U extends core.$ZodLooseShape>(shape: SafeExtendShape<Shape, U> & Partial<Record<keyof Shape, core.SomeType>>): ZodObject<util.Extend<Shape, U>, Config>;
extend<U extends core.$ZodLooseShape>(shape: U): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
safeExtend<U extends core.$ZodLooseShape>(shape: SafeExtendShape<Shape, U> & Partial<Record<keyof Shape, core.SomeType>>): ZodObject<util.Extend<Shape, util.Writeable<U>>, Config>;
/**
* @deprecated Use [`A.extend(B.shape)`](https://zod.dev/api?id=extend) instead.
*/
@@ -453,22 +474,22 @@ out Shape extends core.$ZodShape = core.$ZodLooseShape, out Config extends core.
pick<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Pick<Shape, Extract<keyof Shape, keyof M>>>, Config>;
omit<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<util.Flatten<Omit<Shape, Extract<keyof Shape, keyof M>>>, Config>;
partial(): ZodObject<{
[k in keyof Shape]: ZodOptional<Shape[k]>;
-readonly [k in keyof Shape]: ZodOptional<Shape[k]>;
}, Config>;
partial<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
[k in keyof Shape]: k extends keyof M ? ZodOptional<Shape[k]> : Shape[k];
-readonly [k in keyof Shape]: k extends keyof M ? ZodOptional<Shape[k]> : Shape[k];
}, Config>;
required(): ZodObject<{
[k in keyof Shape]: ZodNonOptional<Shape[k]>;
-readonly [k in keyof Shape]: ZodNonOptional<Shape[k]>;
}, Config>;
required<M extends util.Mask<keyof Shape>>(mask: M & Record<Exclude<keyof M, keyof Shape>, never>): ZodObject<{
[k in keyof Shape]: k extends keyof M ? ZodNonOptional<Shape[k]> : Shape[k];
-readonly [k in keyof Shape]: k extends keyof M ? ZodNonOptional<Shape[k]> : Shape[k];
}, Config>;
}
export declare const ZodObject: core.$constructor<ZodObject>;
export declare function object<T extends core.$ZodLooseShape = Partial<Record<never, core.SomeType>>>(shape?: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<T, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<T, core.$loose>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodObject<util.Writeable<T>, core.$loose>;
export interface ZodUnion<T extends readonly core.SomeType[] = readonly core.$ZodType[]> extends _ZodType<core.$ZodUnionInternals<T>>, core.$ZodUnion<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
options: T;
@@ -490,7 +511,7 @@ export interface ZodDiscriminatedUnion<Options extends readonly core.SomeType[]
def: core.$ZodDiscriminatedUnionDef<Options, Disc>;
}
export declare const ZodDiscriminatedUnion: core.$constructor<ZodDiscriminatedUnion>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable, ...core.$ZodTypeDiscriminable[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodDiscriminatedUnion<Types, Disc>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable<Disc>, ...core.$ZodTypeDiscriminable<Disc>[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodDiscriminatedUnion<Types, Disc>;
export interface ZodIntersection<A extends core.SomeType = core.$ZodType, B extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodIntersectionInternals<A, B>>, core.$ZodIntersection<A, B> {
"~standard": ZodStandardSchemaWithJSON<this>;
}
@@ -575,7 +596,7 @@ export interface ZodTransform<O = unknown, I = unknown> extends _ZodType<core.$Z
"~standard": ZodStandardSchemaWithJSON<this>;
}
export declare const ZodTransform: core.$constructor<ZodTransform>;
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.ParsePayload) => O): ZodTransform<Awaited<O>, I>;
export declare function transform<I = unknown, O = I>(fn: (input: I, ctx: core.$RefinementCtx) => O): ZodTransform<Awaited<O>, I>;
export interface ZodOptional<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodOptionalInternals<T>>, core.$ZodOptional<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
@@ -652,6 +673,13 @@ export declare function codec<const A extends core.SomeType, B extends core.Some
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
}): ZodCodec<A, B>;
export declare function invertCodec<A extends core.SomeType, B extends core.SomeType>(codec: ZodCodec<A, B>): ZodCodec<B, A>;
export interface ZodPreprocess<B extends core.SomeType = core.$ZodType> extends ZodPipe<core.$ZodTransform, B>, core.$ZodPreprocess<B> {
"~standard": ZodStandardSchemaWithJSON<this>;
_zod: core.$ZodPreprocessInternals<B>;
def: core.$ZodPreprocessDef<B>;
}
export declare const ZodPreprocess: core.$constructor<ZodPreprocess>;
export interface ZodReadonly<T extends core.SomeType = core.$ZodType> extends _ZodType<core.$ZodReadonlyInternals<T>>, core.$ZodReadonly<T> {
"~standard": ZodStandardSchemaWithJSON<this>;
unwrap(): T;
@@ -712,7 +740,7 @@ export declare const ZodCustom: core.$constructor<ZodCustom>;
export declare function check<O = unknown>(fn: core.CheckFn<O>): core.$ZodCheck<O>;
export declare function custom<O>(fn?: (data: unknown) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodCustom<O, O>;
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
export declare const describe: typeof core.describe;
export declare const meta: typeof core.meta;
type ZodInstanceOfParams = core.Params<ZodCustom, core.$ZodIssueCustom, "type" | "check" | "checks" | "fn" | "abort" | "error" | "params" | "path">;
@@ -736,4 +764,4 @@ export interface ZodJSONSchema extends _ZodJSONSchema {
_zod: ZodJSONSchemaInternals;
}
export declare function json(params?: string | core.$ZodCustomParams): ZodJSONSchema;
export declare function preprocess<A, U extends core.SomeType, B = unknown>(fn: (arg: B, ctx: core.$RefinementCtx) => A, schema: U): ZodPipe<ZodTransform<A, B>, U>;
export declare function preprocess<A, U extends core.SomeType, B = unknown>(fn: (arg: B, ctx: core.$RefinementCtx) => A, schema: U): ZodPreprocess<U>;
+356 -118
View File
@@ -5,6 +5,54 @@ import { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from "../cor
import * as checks from "./checks.js";
import * as iso from "./iso.js";
import * as parse from "./parse.js";
// Lazy-bind builder methods.
//
// Builder methods (`.optional`, `.array`, `.refine`, ...) live as
// non-enumerable getters on each concrete schema constructor's
// prototype. On first access from an instance the getter allocates
// `fn.bind(this)` and caches it as an own property on that instance,
// so detached usage (`const m = schema.optional; m()`) still works
// and the per-instance allocation only happens for methods actually
// touched.
//
// One install per (prototype, group), memoized by `_installedGroups`.
const _installedGroups = /* @__PURE__ */ new WeakMap();
function _installLazyMethods(inst, group, methods) {
const proto = Object.getPrototypeOf(inst);
let installed = _installedGroups.get(proto);
if (!installed) {
installed = new Set();
_installedGroups.set(proto, installed);
}
if (installed.has(group))
return;
installed.add(group);
for (const key in methods) {
const fn = methods[key];
Object.defineProperty(proto, key, {
configurable: true,
enumerable: false,
get() {
const bound = fn.bind(this);
Object.defineProperty(this, key, {
configurable: true,
writable: true,
enumerable: true,
value: bound,
});
return bound;
},
set(v) {
Object.defineProperty(this, key, {
configurable: true,
writable: true,
enumerable: true,
value: v,
});
},
});
}
}
export const ZodType = /*@__PURE__*/ core.$constructor("ZodType", (inst, def) => {
core.$ZodType.init(inst, def);
Object.assign(inst["~standard"], {
@@ -17,31 +65,16 @@ export const ZodType = /*@__PURE__*/ core.$constructor("ZodType", (inst, def) =>
inst.def = def;
inst.type = def.type;
Object.defineProperty(inst, "_def", { value: def });
// base methods
inst.check = (...checks) => {
return inst.clone(util.mergeDefs(def, {
checks: [
...(def.checks ?? []),
...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
],
}), {
parent: true,
});
};
inst.with = inst.check;
inst.clone = (def, params) => core.clone(inst, def, params);
inst.brand = () => inst;
inst.register = ((reg, meta) => {
reg.add(inst, meta);
return inst;
});
// parsing
// Parse-family is intentionally kept as per-instance closures: these are
// the hot path AND the most-detached methods (`arr.map(schema.parse)`,
// `const { parse } = schema`, etc.). Eager closures here mean callers pay
// ~12 closure allocations per schema but get monomorphic call sites and
// detached usage that "just works".
inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });
inst.safeParse = (data, params) => parse.safeParse(inst, data, params);
inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });
inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);
inst.spa = inst.safeParseAsync;
// encoding/decoding
inst.encode = (data, params) => parse.encode(inst, data, params);
inst.decode = (data, params) => parse.decode(inst, data, params);
inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);
@@ -50,50 +83,118 @@ export const ZodType = /*@__PURE__*/ core.$constructor("ZodType", (inst, def) =>
inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);
inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);
inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);
// refinements
inst.refine = (check, params) => inst.check(refine(check, params));
inst.superRefine = (refinement) => inst.check(superRefine(refinement));
inst.overwrite = (fn) => inst.check(checks.overwrite(fn));
// wrappers
inst.optional = () => optional(inst);
inst.exactOptional = () => exactOptional(inst);
inst.nullable = () => nullable(inst);
inst.nullish = () => optional(nullable(inst));
inst.nonoptional = (params) => nonoptional(inst, params);
inst.array = () => array(inst);
inst.or = (arg) => union([inst, arg]);
inst.and = (arg) => intersection(inst, arg);
inst.transform = (tx) => pipe(inst, transform(tx));
inst.default = (def) => _default(inst, def);
inst.prefault = (def) => prefault(inst, def);
// inst.coalesce = (def, params) => coalesce(inst, def, params);
inst.catch = (params) => _catch(inst, params);
inst.pipe = (target) => pipe(inst, target);
inst.readonly = () => readonly(inst);
// meta
inst.describe = (description) => {
const cl = inst.clone();
core.globalRegistry.add(cl, { description });
return cl;
};
// All builder methods are placed on the internal prototype as lazy-bind
// getters. On first access per-instance, a bound thunk is allocated and
// cached as an own property; subsequent accesses skip the getter. This
// means: no per-instance allocation for unused methods, full
// detachability preserved (`const m = schema.optional; m()` works), and
// shared underlying function references across all instances.
_installLazyMethods(inst, "ZodType", {
check(...chks) {
const def = this.def;
return this.clone(util.mergeDefs(def, {
checks: [
...(def.checks ?? []),
...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
],
}), { parent: true });
},
with(...chks) {
return this.check(...chks);
},
clone(def, params) {
return core.clone(this, def, params);
},
brand() {
return this;
},
register(reg, meta) {
reg.add(this, meta);
return this;
},
refine(check, params) {
return this.check(refine(check, params));
},
superRefine(refinement, params) {
return this.check(superRefine(refinement, params));
},
overwrite(fn) {
return this.check(checks.overwrite(fn));
},
optional() {
return optional(this);
},
exactOptional() {
return exactOptional(this);
},
nullable() {
return nullable(this);
},
nullish() {
return optional(nullable(this));
},
nonoptional(params) {
return nonoptional(this, params);
},
array() {
return array(this);
},
or(arg) {
return union([this, arg]);
},
and(arg) {
return intersection(this, arg);
},
transform(tx) {
return pipe(this, transform(tx));
},
default(d) {
return _default(this, d);
},
prefault(d) {
return prefault(this, d);
},
catch(params) {
return _catch(this, params);
},
pipe(target) {
return pipe(this, target);
},
readonly() {
return readonly(this);
},
describe(description) {
const cl = this.clone();
core.globalRegistry.add(cl, { description });
return cl;
},
meta(...args) {
// overloaded: meta() returns the registered metadata, meta(data)
// returns a clone with `data` registered. The mapped type picks
// up the second overload, so we accept variadic any-args and
// return `any` to satisfy both at runtime.
if (args.length === 0)
return core.globalRegistry.get(this);
const cl = this.clone();
core.globalRegistry.add(cl, args[0]);
return cl;
},
isOptional() {
return this.safeParse(undefined).success;
},
isNullable() {
return this.safeParse(null).success;
},
apply(fn) {
return fn(this);
},
});
Object.defineProperty(inst, "description", {
get() {
return core.globalRegistry.get(inst)?.description;
},
configurable: true,
});
inst.meta = (...args) => {
if (args.length === 0) {
return core.globalRegistry.get(inst);
}
const cl = inst.clone();
core.globalRegistry.add(cl, args[0]);
return cl;
};
// helpers
inst.isOptional = () => inst.safeParse(undefined).success;
inst.isNullable = () => inst.safeParse(null).success;
inst.apply = (fn) => fn(inst);
return inst;
});
/** @internal */
@@ -105,23 +206,53 @@ export const _ZodString = /*@__PURE__*/ core.$constructor("_ZodString", (inst, d
inst.format = bag.format ?? null;
inst.minLength = bag.minimum ?? null;
inst.maxLength = bag.maximum ?? null;
// validations
inst.regex = (...args) => inst.check(checks.regex(...args));
inst.includes = (...args) => inst.check(checks.includes(...args));
inst.startsWith = (...args) => inst.check(checks.startsWith(...args));
inst.endsWith = (...args) => inst.check(checks.endsWith(...args));
inst.min = (...args) => inst.check(checks.minLength(...args));
inst.max = (...args) => inst.check(checks.maxLength(...args));
inst.length = (...args) => inst.check(checks.length(...args));
inst.nonempty = (...args) => inst.check(checks.minLength(1, ...args));
inst.lowercase = (params) => inst.check(checks.lowercase(params));
inst.uppercase = (params) => inst.check(checks.uppercase(params));
// transforms
inst.trim = () => inst.check(checks.trim());
inst.normalize = (...args) => inst.check(checks.normalize(...args));
inst.toLowerCase = () => inst.check(checks.toLowerCase());
inst.toUpperCase = () => inst.check(checks.toUpperCase());
inst.slugify = () => inst.check(checks.slugify());
_installLazyMethods(inst, "_ZodString", {
regex(...args) {
return this.check(checks.regex(...args));
},
includes(...args) {
return this.check(checks.includes(...args));
},
startsWith(...args) {
return this.check(checks.startsWith(...args));
},
endsWith(...args) {
return this.check(checks.endsWith(...args));
},
min(...args) {
return this.check(checks.minLength(...args));
},
max(...args) {
return this.check(checks.maxLength(...args));
},
length(...args) {
return this.check(checks.length(...args));
},
nonempty(...args) {
return this.check(checks.minLength(1, ...args));
},
lowercase(params) {
return this.check(checks.lowercase(params));
},
uppercase(params) {
return this.check(checks.uppercase(params));
},
trim() {
return this.check(checks.trim());
},
normalize(...args) {
return this.check(checks.normalize(...args));
},
toLowerCase() {
return this.check(checks.toLowerCase());
},
toUpperCase() {
return this.check(checks.toUpperCase());
},
slugify() {
return this.check(checks.slugify());
},
});
});
export const ZodString = /*@__PURE__*/ core.$constructor("ZodString", (inst, def) => {
core.$ZodString.init(inst, def);
@@ -207,7 +338,7 @@ export function url(params) {
}
export function httpUrl(params) {
return core._url(ZodURL, {
protocol: /^https?$/,
protocol: core.regexes.httpProtocol,
hostname: core.regexes.domain,
...util.normalizeParams(params),
});
@@ -228,11 +359,23 @@ export const ZodNanoID = /*@__PURE__*/ core.$constructor("ZodNanoID", (inst, def
export function nanoid(params) {
return core._nanoid(ZodNanoID, params);
}
/**
* @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) => {
// ZodStringFormat.init(inst, def);
core.$ZodCUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
export function cuid(params) {
return core._cuid(ZodCUID, params);
}
@@ -364,22 +507,53 @@ export const ZodNumber = /*@__PURE__*/ core.$constructor("ZodNumber", (inst, def
core.$ZodNumber.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);
inst.gt = (value, params) => inst.check(checks.gt(value, params));
inst.gte = (value, params) => inst.check(checks.gte(value, params));
inst.min = (value, params) => inst.check(checks.gte(value, params));
inst.lt = (value, params) => inst.check(checks.lt(value, params));
inst.lte = (value, params) => inst.check(checks.lte(value, params));
inst.max = (value, params) => inst.check(checks.lte(value, params));
inst.int = (params) => inst.check(int(params));
inst.safe = (params) => inst.check(int(params));
inst.positive = (params) => inst.check(checks.gt(0, params));
inst.nonnegative = (params) => inst.check(checks.gte(0, params));
inst.negative = (params) => inst.check(checks.lt(0, params));
inst.nonpositive = (params) => inst.check(checks.lte(0, params));
inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));
inst.step = (value, params) => inst.check(checks.multipleOf(value, params));
// inst.finite = (params) => inst.check(core.finite(params));
inst.finite = () => inst;
_installLazyMethods(inst, "ZodNumber", {
gt(value, params) {
return this.check(checks.gt(value, params));
},
gte(value, params) {
return this.check(checks.gte(value, params));
},
min(value, params) {
return this.check(checks.gte(value, params));
},
lt(value, params) {
return this.check(checks.lt(value, params));
},
lte(value, params) {
return this.check(checks.lte(value, params));
},
max(value, params) {
return this.check(checks.lte(value, params));
},
int(params) {
return this.check(int(params));
},
safe(params) {
return this.check(int(params));
},
positive(params) {
return this.check(checks.gt(0, params));
},
nonnegative(params) {
return this.check(checks.gte(0, params));
},
negative(params) {
return this.check(checks.lt(0, params));
},
nonpositive(params) {
return this.check(checks.lte(0, params));
},
multipleOf(value, params) {
return this.check(checks.multipleOf(value, params));
},
step(value, params) {
return this.check(checks.multipleOf(value, params));
},
finite() {
return this;
},
});
const bag = inst._zod.bag;
inst.minValue =
Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
@@ -533,11 +707,23 @@ export const ZodArray = /*@__PURE__*/ core.$constructor("ZodArray", (inst, def)
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);
inst.element = def.element;
inst.min = (minLength, params) => inst.check(checks.minLength(minLength, params));
inst.nonempty = (params) => inst.check(checks.minLength(1, params));
inst.max = (maxLength, params) => inst.check(checks.maxLength(maxLength, params));
inst.length = (len, params) => inst.check(checks.length(len, params));
inst.unwrap = () => inst.element;
_installLazyMethods(inst, "ZodArray", {
min(n, params) {
return this.check(checks.minLength(n, params));
},
nonempty(params) {
return this.check(checks.minLength(1, params));
},
max(n, params) {
return this.check(checks.maxLength(n, params));
},
length(n, params) {
return this.check(checks.length(n, params));
},
unwrap() {
return this.element;
},
});
});
export function array(element, params) {
return core._array(ZodArray, element, params);
@@ -554,23 +740,47 @@ export const ZodObject = /*@__PURE__*/ core.$constructor("ZodObject", (inst, def
util.defineLazy(inst, "shape", () => {
return def.shape;
});
inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });
inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });
inst.extend = (incoming) => {
return util.extend(inst, incoming);
};
inst.safeExtend = (incoming) => {
return util.safeExtend(inst, incoming);
};
inst.merge = (other) => util.merge(inst, other);
inst.pick = (mask) => util.pick(inst, mask);
inst.omit = (mask) => util.omit(inst, mask);
inst.partial = (...args) => util.partial(ZodOptional, inst, args[0]);
inst.required = (...args) => util.required(ZodNonOptional, inst, args[0]);
_installLazyMethods(inst, "ZodObject", {
keyof() {
return _enum(Object.keys(this._zod.def.shape));
},
catchall(catchall) {
return this.clone({ ...this._zod.def, catchall: catchall });
},
passthrough() {
return this.clone({ ...this._zod.def, catchall: unknown() });
},
loose() {
return this.clone({ ...this._zod.def, catchall: unknown() });
},
strict() {
return this.clone({ ...this._zod.def, catchall: never() });
},
strip() {
return this.clone({ ...this._zod.def, catchall: undefined });
},
extend(incoming) {
return util.extend(this, incoming);
},
safeExtend(incoming) {
return util.safeExtend(this, incoming);
},
merge(other) {
return util.merge(this, other);
},
pick(mask) {
return util.pick(this, mask);
},
omit(mask) {
return util.omit(this, mask);
},
partial(...args) {
return util.partial(ZodOptional, this, args[0]);
},
required(...args) {
return util.required(ZodNonOptional, this, args[0]);
},
});
});
export function object(shape, params) {
const def = {
@@ -681,6 +891,15 @@ export const ZodRecord = /*@__PURE__*/ core.$constructor("ZodRecord", (inst, def
inst.valueType = def.valueType;
});
export function record(keyType, valueType, params) {
// v3-compat: z.record(valueType, params?) — defaults keyType to z.string()
if (!valueType || !valueType._zod) {
return new ZodRecord({
type: "record",
keyType: string(),
valueType: keyType,
...util.normalizeParams(valueType),
});
}
return new ZodRecord({
type: "record",
keyType,
@@ -866,10 +1085,12 @@ export const ZodTransform = /*@__PURE__*/ core.$constructor("ZodTransform", (ins
if (output instanceof Promise) {
return output.then((output) => {
payload.value = output;
payload.fallback = true;
return payload;
});
}
payload.value = output;
payload.fallback = true;
return payload;
};
});
@@ -1026,6 +1247,20 @@ export function codec(in_, out, params) {
reverseTransform: params.encode,
});
}
export function invertCodec(codec) {
const def = codec._zod.def;
return new ZodCodec({
type: "pipe",
in: def.out,
out: def.in,
transform: def.reverseTransform,
reverseTransform: def.transform,
});
}
export const ZodPreprocess = /*@__PURE__*/ core.$constructor("ZodPreprocess", (inst, def) => {
ZodPipe.init(inst, def);
core.$ZodPreprocess.init(inst, def);
});
export const ZodReadonly = /*@__PURE__*/ core.$constructor("ZodReadonly", (inst, def) => {
core.$ZodReadonly.init(inst, def);
ZodType.init(inst, def);
@@ -1108,8 +1343,8 @@ export function refine(fn, _params = {}) {
return core._refine(ZodCustom, fn, _params);
}
// superRefine
export function superRefine(fn) {
return core._superRefine(fn);
export function superRefine(fn, params) {
return core._superRefine(fn, params);
}
// Re-export describe and meta from core
export const describe = core.describe;
@@ -1151,7 +1386,10 @@ export function json(params) {
return jsonSchema;
}
// preprocess
// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */
export function preprocess(fn, schema) {
return pipe(transform(fn), schema);
return new ZodPreprocess({
type: "pipe",
in: transform(fn),
out: schema,
});
}
+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,
};
+4
View File
@@ -120,6 +120,10 @@ const error = () => {
case "invalid_key":
return `Invalid key in ${issue.origin}`;
case "invalid_union":
if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {
const opts = issue.options.map((o) => `'${o}'`).join(" | ");
return `Invalid discriminator value. Expected ${opts}`;
}
return "Invalid input";
case "invalid_element":
return `Invalid value in ${issue.origin}`;
+4
View File
@@ -94,6 +94,10 @@ const error = () => {
case "invalid_key":
return `Invalid key in ${issue.origin}`;
case "invalid_union":
if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {
const opts = issue.options.map((o) => `'${o}'`).join(" | ");
return `Invalid discriminator value. Expected ${opts}`;
}
return "Invalid input";
case "invalid_element":
return `Invalid value in ${issue.origin}`;
+24 -7
View File
@@ -66,9 +66,27 @@ const error = () => {
template_literal: "entrée",
};
const TypeDictionary = {
nan: "NaN",
string: "chaîne",
number: "nombre",
int: "entier",
boolean: "booléen",
bigint: "grand entier",
symbol: "symbole",
undefined: "indéfini",
null: "null",
never: "jamais",
void: "vide",
date: "date",
array: "tableau",
object: "objet",
tuple: "tuple",
record: "enregistrement",
map: "carte",
set: "ensemble",
file: "fichier",
nonoptional: "non-optionnel",
nan: "NaN",
function: "fonction",
};
return (issue) => {
switch (issue.code) {
@@ -89,16 +107,15 @@ const error = () => {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Trop grand : ${issue.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "élément(s)"}`;
return `Trop grand : ${issue.origin ?? "valeur"} doit être ${adj}${issue.maximum.toString()}`;
return `Trop grand : ${TypeDictionary[issue.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "élément(s)"}`;
return `Trop grand : ${TypeDictionary[issue.origin] ?? "valeur"} doit être ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Trop petit : ${issue.origin} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Trop petit : ${issue.origin} doit être ${adj}${issue.minimum.toString()}`;
if (sizing)
return `Trop petit : ${TypeDictionary[issue.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;
return `Trop petit : ${TypeDictionary[issue.origin] ?? "valeur"} doit être ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
+24 -7
View File
@@ -40,9 +40,27 @@ const error = () => {
template_literal: "entrée",
};
const TypeDictionary = {
nan: "NaN",
string: "chaîne",
number: "nombre",
int: "entier",
boolean: "booléen",
bigint: "grand entier",
symbol: "symbole",
undefined: "indéfini",
null: "null",
never: "jamais",
void: "vide",
date: "date",
array: "tableau",
object: "objet",
tuple: "tuple",
record: "enregistrement",
map: "carte",
set: "ensemble",
file: "fichier",
nonoptional: "non-optionnel",
nan: "NaN",
function: "fonction",
};
return (issue) => {
switch (issue.code) {
@@ -63,16 +81,15 @@ const error = () => {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Trop grand : ${issue.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "élément(s)"}`;
return `Trop grand : ${issue.origin ?? "valeur"} doit être ${adj}${issue.maximum.toString()}`;
return `Trop grand : ${TypeDictionary[issue.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "élément(s)"}`;
return `Trop grand : ${TypeDictionary[issue.origin] ?? "valeur"} doit être ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Trop petit : ${issue.origin} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Trop petit : ${issue.origin} doit être ${adj}${issue.minimum.toString()}`;
if (sizing)
return `Trop petit : ${TypeDictionary[issue.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`;
return `Trop petit : ${TypeDictionary[issue.origin] ?? "valeur"} doit être ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
+8 -1
View File
@@ -3,7 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.yo = exports.zhTW = exports.zhCN = exports.vi = exports.uz = exports.ur = exports.uk = exports.ua = exports.tr = exports.th = exports.ta = exports.sv = exports.sl = exports.ru = exports.pt = exports.pl = exports.ps = exports.ota = exports.no = exports.nl = exports.ms = exports.mk = exports.lt = exports.ko = exports.km = exports.kh = exports.ka = exports.ja = exports.it = exports.is = exports.id = exports.hy = exports.hu = exports.he = exports.frCA = exports.fr = exports.fi = exports.fa = exports.es = exports.eo = exports.en = exports.de = exports.da = exports.cs = exports.ca = exports.bg = exports.be = exports.az = exports.ar = void 0;
exports.zhCN = exports.vi = exports.uz = exports.ur = exports.uk = exports.ua = exports.tr = exports.th = exports.ta = exports.sv = exports.sl = exports.ru = exports.ro = exports.pt = exports.pl = exports.ps = exports.ota = exports.no = exports.nl = exports.ms = exports.mk = exports.lt = exports.ko = exports.km = exports.kh = exports.ka = exports.ja = exports.it = exports.is = exports.id = exports.hy = exports.hu = exports.hr = exports.he = exports.frCA = exports.fr = exports.fi = exports.fa = exports.es = exports.eo = exports.en = exports.el = exports.de = exports.da = exports.cs = exports.ca = exports.bg = exports.be = exports.az = exports.ar = void 0;
exports.yo = exports.zhTW = void 0;
var ar_js_1 = require("./ar.cjs");
Object.defineProperty(exports, "ar", { enumerable: true, get: function () { return __importDefault(ar_js_1).default; } });
var az_js_1 = require("./az.cjs");
@@ -20,6 +21,8 @@ var da_js_1 = require("./da.cjs");
Object.defineProperty(exports, "da", { enumerable: true, get: function () { return __importDefault(da_js_1).default; } });
var de_js_1 = require("./de.cjs");
Object.defineProperty(exports, "de", { enumerable: true, get: function () { return __importDefault(de_js_1).default; } });
var el_js_1 = require("./el.cjs");
Object.defineProperty(exports, "el", { enumerable: true, get: function () { return __importDefault(el_js_1).default; } });
var en_js_1 = require("./en.cjs");
Object.defineProperty(exports, "en", { enumerable: true, get: function () { return __importDefault(en_js_1).default; } });
var eo_js_1 = require("./eo.cjs");
@@ -36,6 +39,8 @@ var fr_CA_js_1 = require("./fr-CA.cjs");
Object.defineProperty(exports, "frCA", { enumerable: true, get: function () { return __importDefault(fr_CA_js_1).default; } });
var he_js_1 = require("./he.cjs");
Object.defineProperty(exports, "he", { enumerable: true, get: function () { return __importDefault(he_js_1).default; } });
var hr_js_1 = require("./hr.cjs");
Object.defineProperty(exports, "hr", { enumerable: true, get: function () { return __importDefault(hr_js_1).default; } });
var hu_js_1 = require("./hu.cjs");
Object.defineProperty(exports, "hu", { enumerable: true, get: function () { return __importDefault(hu_js_1).default; } });
var hy_js_1 = require("./hy.cjs");
@@ -74,6 +79,8 @@ var pl_js_1 = require("./pl.cjs");
Object.defineProperty(exports, "pl", { enumerable: true, get: function () { return __importDefault(pl_js_1).default; } });
var pt_js_1 = require("./pt.cjs");
Object.defineProperty(exports, "pt", { enumerable: true, get: function () { return __importDefault(pt_js_1).default; } });
var ro_js_1 = require("./ro.cjs");
Object.defineProperty(exports, "ro", { enumerable: true, get: function () { return __importDefault(ro_js_1).default; } });
var ru_js_1 = require("./ru.cjs");
Object.defineProperty(exports, "ru", { enumerable: true, get: function () { return __importDefault(ru_js_1).default; } });
var sl_js_1 = require("./sl.cjs");
+3
View File
@@ -6,6 +6,7 @@ export { default as ca } from "./ca.cjs";
export { default as cs } from "./cs.cjs";
export { default as da } from "./da.cjs";
export { default as de } from "./de.cjs";
export { default as el } from "./el.cjs";
export { default as en } from "./en.cjs";
export { default as eo } from "./eo.cjs";
export { default as es } from "./es.cjs";
@@ -14,6 +15,7 @@ export { default as fi } from "./fi.cjs";
export { default as fr } from "./fr.cjs";
export { default as frCA } from "./fr-CA.cjs";
export { default as he } from "./he.cjs";
export { default as hr } from "./hr.cjs";
export { default as hu } from "./hu.cjs";
export { default as hy } from "./hy.cjs";
export { default as id } from "./id.cjs";
@@ -33,6 +35,7 @@ export { default as ota } from "./ota.cjs";
export { default as ps } from "./ps.cjs";
export { default as pl } from "./pl.cjs";
export { default as pt } from "./pt.cjs";
export { default as ro } from "./ro.cjs";
export { default as ru } from "./ru.cjs";
export { default as sl } from "./sl.cjs";
export { default as sv } from "./sv.cjs";
+3
View File
@@ -6,6 +6,7 @@ export { default as ca } from "./ca.js";
export { default as cs } from "./cs.js";
export { default as da } from "./da.js";
export { default as de } from "./de.js";
export { default as el } from "./el.js";
export { default as en } from "./en.js";
export { default as eo } from "./eo.js";
export { default as es } from "./es.js";
@@ -14,6 +15,7 @@ export { default as fi } from "./fi.js";
export { default as fr } from "./fr.js";
export { default as frCA } from "./fr-CA.js";
export { default as he } from "./he.js";
export { default as hr } from "./hr.js";
export { default as hu } from "./hu.js";
export { default as hy } from "./hy.js";
export { default as id } from "./id.js";
@@ -33,6 +35,7 @@ export { default as ota } from "./ota.js";
export { default as ps } from "./ps.js";
export { default as pl } from "./pl.js";
export { default as pt } from "./pt.js";
export { default as ro } from "./ro.js";
export { default as ru } from "./ru.js";
export { default as sl } from "./sl.js";
export { default as sv } from "./sv.js";
+3
View File
@@ -6,6 +6,7 @@ export { default as ca } from "./ca.js";
export { default as cs } from "./cs.js";
export { default as da } from "./da.js";
export { default as de } from "./de.js";
export { default as el } from "./el.js";
export { default as en } from "./en.js";
export { default as eo } from "./eo.js";
export { default as es } from "./es.js";
@@ -14,6 +15,7 @@ export { default as fi } from "./fi.js";
export { default as fr } from "./fr.js";
export { default as frCA } from "./fr-CA.js";
export { default as he } from "./he.js";
export { default as hr } from "./hr.js";
export { default as hu } from "./hu.js";
export { default as hy } from "./hy.js";
export { default as id } from "./id.js";
@@ -33,6 +35,7 @@ export { default as ota } from "./ota.js";
export { default as ps } from "./ps.js";
export { default as pl } from "./pl.js";
export { default as pt } from "./pt.js";
export { default as ro } from "./ro.js";
export { default as ru } from "./ru.js";
export { default as sl } from "./sl.js";
export { default as sv } from "./sv.js";
+1 -1
View File
@@ -110,7 +110,7 @@ const error = () => {
return `Stringa non valida: deve includere "${_issue.includes}"`;
if (_issue.format === "regex")
return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;
return `Input non valido: ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Numero non valido: deve essere un multiplo di ${issue.divisor}`;
+1 -1
View File
@@ -84,7 +84,7 @@ const error = () => {
return `Stringa non valida: deve includere "${_issue.includes}"`;
if (_issue.format === "regex")
return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;
return `Input non valido: ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Numero non valido: deve essere un multiplo di ${issue.divisor}`;
+8 -8
View File
@@ -58,9 +58,9 @@ const error = () => {
ipv6: "IPv6 მისამართი",
cidrv4: "IPv4 დიაპაზონი",
cidrv6: "IPv6 დიაპაზონი",
base64: "base64-კოდირებული სტრინგი",
base64url: "base64url-კოდირებული სტრინგი",
json_string: "JSON სტრინგი",
base64: "base64-კოდირებული ველი",
base64url: "base64url-კოდირებული ველი",
json_string: "JSON ველი",
e164: "E.164 ნომერი",
jwt: "JWT",
template_literal: "შეყვანა",
@@ -68,7 +68,7 @@ const error = () => {
const TypeDictionary = {
nan: "NaN",
number: "რიცხვი",
string: "სტრინგი",
string: "ველი",
boolean: "ბულეანი",
function: "ფუნქცია",
array: "მასივი",
@@ -106,14 +106,14 @@ const error = () => {
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`;
return `არასწორი ველი: უნდა იწყებოდეს "${_issue.prefix}"-ით`;
}
if (_issue.format === "ends_with")
return `არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`;
return `არასწორი ველი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`;
if (_issue.format === "includes")
return `არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`;
return `არასწორი ველი: უნდა შეიცავდეს "${_issue.includes}"-ს`;
if (_issue.format === "regex")
return `არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;
return `არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;
return `არასწორი ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
+8 -8
View File
@@ -32,9 +32,9 @@ const error = () => {
ipv6: "IPv6 მისამართი",
cidrv4: "IPv4 დიაპაზონი",
cidrv6: "IPv6 დიაპაზონი",
base64: "base64-კოდირებული სტრინგი",
base64url: "base64url-კოდირებული სტრინგი",
json_string: "JSON სტრინგი",
base64: "base64-კოდირებული ველი",
base64url: "base64url-კოდირებული ველი",
json_string: "JSON ველი",
e164: "E.164 ნომერი",
jwt: "JWT",
template_literal: "შეყვანა",
@@ -42,7 +42,7 @@ const error = () => {
const TypeDictionary = {
nan: "NaN",
number: "რიცხვი",
string: "სტრინგი",
string: "ველი",
boolean: "ბულეანი",
function: "ფუნქცია",
array: "მასივი",
@@ -80,14 +80,14 @@ const error = () => {
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`;
return `არასწორი ველი: უნდა იწყებოდეს "${_issue.prefix}"-ით`;
}
if (_issue.format === "ends_with")
return `არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`;
return `არასწორი ველი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`;
if (_issue.format === "includes")
return `არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`;
return `არასწორი ველი: უნდა შეიცავდეს "${_issue.includes}"-ს`;
if (_issue.format === "regex")
return `არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;
return `არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;
return `არასწორი ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
+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
}
+1
View File
@@ -31,6 +31,7 @@ const error = () => {
file: { unit: "bayt", verb: "bolishi kerak" },
array: { unit: "element", verb: "bolishi kerak" },
set: { unit: "element", verb: "bolishi kerak" },
map: { unit: "yozuv", verb: "bolishi kerak" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
+1
View File
@@ -5,6 +5,7 @@ const error = () => {
file: { unit: "bayt", verb: "bolishi kerak" },
array: { unit: "element", verb: "bolishi kerak" },
set: { unit: "element", verb: "bolishi kerak" },
map: { unit: "yozuv", verb: "bolishi kerak" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
+1
View File
@@ -3,6 +3,7 @@ export * from "./parse.cjs";
export * from "./schemas.cjs";
export * from "./checks.cjs";
export type { infer, output, input } from "../core/index.cjs";
export type { JSONType } from "../core/util.cjs";
export { globalRegistry, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from "../core/index.cjs";
export { toJSONSchema } from "../core/json-schema-processors.cjs";
export * as locales from "../locales/index.cjs";
+1
View File
@@ -3,6 +3,7 @@ export * from "./parse.js";
export * from "./schemas.js";
export * from "./checks.js";
export type { infer, output, input } from "../core/index.js";
export type { JSONType } from "../core/util.js";
export { globalRegistry, registry, config, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, TimePrecision, util, NEVER, } from "../core/index.js";
export { toJSONSchema } from "../core/json-schema-processors.js";
export * as locales from "../locales/index.js";
+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
}
+41 -4
View File
@@ -112,6 +112,7 @@ exports.catch = _catch;
exports.nan = nan;
exports.pipe = pipe;
exports.codec = codec;
exports.invertCodec = invertCodec;
exports.readonly = readonly;
exports.templateLiteral = templateLiteral;
exports.lazy = _lazy;
@@ -144,7 +145,11 @@ exports.ZodMiniType = core.$constructor("ZodMiniType", (inst, def) => {
...def,
checks: [
...(def.checks ?? []),
...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
...checks.map((ch) => typeof ch === "function"
? {
_zod: { check: ch, def: { check: "custom" }, onattach: [] },
}
: ch),
],
}, { parent: true });
};
@@ -218,7 +223,7 @@ function url(params) {
// @__NO_SIDE_EFFECTS__
function httpUrl(params) {
return core._url(exports.ZodMiniURL, {
protocol: /^https?$/,
protocol: core.regexes.httpProtocol,
hostname: core.regexes.domain,
...util.normalizeParams(params),
});
@@ -239,10 +244,22 @@ exports.ZodMiniNanoID = core.$constructor("ZodMiniNanoID", (inst, def) => {
function nanoid(params) {
return core._nanoid(exports.ZodMiniNanoID, params);
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
exports.ZodMiniCUID = core.$constructor("ZodMiniCUID", (inst, def) => {
core.$ZodCUID.init(inst, def);
exports.ZodMiniStringFormat.init(inst, def);
});
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
// @__NO_SIDE_EFFECTS__
function cuid(params) {
return core._cuid(exports.ZodMiniCUID, params);
@@ -668,6 +685,15 @@ exports.ZodMiniRecord = core.$constructor("ZodMiniRecord", (inst, def) => {
});
// @__NO_SIDE_EFFECTS__
function record(keyType, valueType, params) {
// v3-compat: z.record(valueType, params?) — defaults keyType to z.string()
if (!valueType || !valueType._zod) {
return new exports.ZodMiniRecord({
type: "record",
keyType: string(),
valueType: keyType,
...util.normalizeParams(valueType),
});
}
return new exports.ZodMiniRecord({
type: "record",
keyType,
@@ -915,6 +941,17 @@ function codec(in_, out, params) {
reverseTransform: params.encode,
});
}
// @__NO_SIDE_EFFECTS__
function invertCodec(codec) {
const def = codec._zod.def;
return new exports.ZodMiniCodec({
type: "pipe",
in: def.out,
out: def.in,
transform: def.reverseTransform,
reverseTransform: def.transform,
});
}
exports.ZodMiniReadonly = core.$constructor("ZodMiniReadonly", (inst, def) => {
core.$ZodReadonly.init(inst, def);
exports.ZodMiniType.init(inst, def);
@@ -990,8 +1027,8 @@ function refine(fn, _params = {}) {
}
// superRefine
// @__NO_SIDE_EFFECTS__
function superRefine(fn) {
return core._superRefine(fn);
function superRefine(fn, params) {
return core._superRefine(fn, params);
}
// Re-export describe and meta from core
exports.describe = core.describe;
+28 -10
View File
@@ -58,9 +58,26 @@ export interface ZodMiniNanoID extends _ZodMiniString<core.$ZodNanoIDInternals>
}
export declare const ZodMiniNanoID: core.$constructor<ZodMiniNanoID>;
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodMiniNanoID;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export interface ZodMiniCUID extends _ZodMiniString<core.$ZodCUIDInternals> {
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const ZodMiniCUID: core.$constructor<ZodMiniCUID>;
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodMiniCUID;
export interface ZodMiniCUID2 extends _ZodMiniString<core.$ZodCUID2Internals> {
}
@@ -198,23 +215,23 @@ out Shape extends core.$ZodShape = core.$ZodShape, out Config extends core.$ZodO
shape: Shape;
}
export declare const ZodMiniObject: core.$constructor<ZodMiniObject>;
export declare function object<T extends core.$ZodLooseShape = Record<never, SomeType>>(shape?: T, params?: string | core.$ZodObjectParams): ZodMiniObject<T, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodMiniObject<T, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodMiniObject<T, core.$loose>;
export declare function extend<T extends ZodMiniObject, U extends core.$ZodLooseShape>(schema: T, shape: U): ZodMiniObject<util.Extend<T["shape"], U>, T["_zod"]["config"]>;
export declare function object<T extends core.$ZodLooseShape = Record<never, SomeType>>(shape?: T, params?: string | core.$ZodObjectParams): ZodMiniObject<util.Writeable<T>, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodMiniObject<util.Writeable<T>, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodMiniObject<util.Writeable<T>, core.$loose>;
export declare function extend<T extends ZodMiniObject, U extends core.$ZodLooseShape>(schema: T, shape: U): ZodMiniObject<util.Extend<T["shape"], util.Writeable<U>>, T["_zod"]["config"]>;
export type SafeExtendShape<Base extends core.$ZodShape, Ext extends core.$ZodLooseShape> = {
[K in keyof Ext]: K extends keyof Base ? core.output<Ext[K]> extends core.output<Base[K]> ? core.input<Ext[K]> extends core.input<Base[K]> ? Ext[K] : never : never : Ext[K];
};
export declare function safeExtend<T extends ZodMiniObject, U extends core.$ZodLooseShape>(schema: T, shape: SafeExtendShape<T["shape"], U>): ZodMiniObject<util.Extend<T["shape"], U>, T["_zod"]["config"]>;
export declare function safeExtend<T extends ZodMiniObject, U extends core.$ZodLooseShape>(schema: T, shape: SafeExtendShape<T["shape"], U>): ZodMiniObject<util.Extend<T["shape"], util.Writeable<U>>, T["_zod"]["config"]>;
/** @deprecated Identical to `z.extend(A, B)` */
export declare function merge<T extends ZodMiniObject, U extends ZodMiniObject>(a: T, b: U): ZodMiniObject<util.Extend<T["shape"], U["shape"]>, T["_zod"]["config"]>;
export declare function pick<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<util.Flatten<Pick<T["shape"], keyof T["shape"] & keyof M>>, T["_zod"]["config"]>;
export declare function omit<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<util.Flatten<Omit<T["shape"], keyof M>>, T["_zod"]["config"]>;
export declare function partial<T extends ZodMiniObject>(schema: T): ZodMiniObject<{
[k in keyof T["shape"]]: ZodMiniOptional<T["shape"][k]>;
-readonly [k in keyof T["shape"]]: ZodMiniOptional<T["shape"][k]>;
}, T["_zod"]["config"]>;
export declare function partial<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<{
[k in keyof T["shape"]]: k extends keyof M ? ZodMiniOptional<T["shape"][k]> : T["shape"][k];
-readonly [k in keyof T["shape"]]: k extends keyof M ? ZodMiniOptional<T["shape"][k]> : T["shape"][k];
}, T["_zod"]["config"]>;
export type RequiredInterfaceShape<Shape extends core.$ZodLooseShape, Keys extends PropertyKey = keyof Shape> = util.Identity<{
[k in keyof Shape as k extends Keys ? k : never]: ZodMiniNonOptional<Shape[k]>;
@@ -222,7 +239,7 @@ export type RequiredInterfaceShape<Shape extends core.$ZodLooseShape, Keys exten
[k in keyof Shape as k extends Keys ? never : k]: Shape[k];
}>;
export declare function required<T extends ZodMiniObject>(schema: T): ZodMiniObject<{
[k in keyof T["shape"]]: ZodMiniNonOptional<T["shape"][k]>;
-readonly [k in keyof T["shape"]]: ZodMiniNonOptional<T["shape"][k]>;
}, T["_zod"]["config"]>;
export declare function required<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<util.Extend<T["shape"], {
[k in keyof M & keyof T["shape"]]: ZodMiniNonOptional<T["shape"][k]>;
@@ -243,7 +260,7 @@ export interface ZodMiniDiscriminatedUnion<Options extends readonly SomeType[] =
_zod: core.$ZodDiscriminatedUnionInternals<Options, Disc>;
}
export declare const ZodMiniDiscriminatedUnion: core.$constructor<ZodMiniDiscriminatedUnion>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable, ...core.$ZodTypeDiscriminable[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodMiniDiscriminatedUnion<Types, Disc>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable<Disc>, ...core.$ZodTypeDiscriminable<Disc>[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodMiniDiscriminatedUnion<Types, Disc>;
export interface ZodMiniIntersection<A extends SomeType = core.$ZodType, B extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodIntersectionInternals<A, B>> {
}
export declare const ZodMiniIntersection: core.$constructor<ZodMiniIntersection>;
@@ -347,6 +364,7 @@ export declare function codec<const A extends SomeType, B extends core.SomeType
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
}): ZodMiniCodec<A, B>;
export declare function invertCodec<A extends SomeType, B extends SomeType>(codec: ZodMiniCodec<A, B>): ZodMiniCodec<B, A>;
export interface ZodMiniReadonly<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodReadonlyInternals<T>> {
}
export declare const ZodMiniReadonly: core.$constructor<ZodMiniReadonly>;
@@ -370,7 +388,7 @@ export declare const ZodMiniCustom: core.$constructor<ZodMiniCustom>;
export declare function check<O = unknown>(fn: core.CheckFn<O>, params?: string | core.$ZodCustomParams): core.$ZodCheck<O>;
export declare function custom<O = unknown, I = O>(fn?: (data: O) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodMiniCustom<O, I>;
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
export declare const describe: typeof core.describe;
export declare const meta: typeof core.meta;
declare abstract class Class {
+28 -10
View File
@@ -58,9 +58,26 @@ export interface ZodMiniNanoID extends _ZodMiniString<core.$ZodNanoIDInternals>
}
export declare const ZodMiniNanoID: core.$constructor<ZodMiniNanoID>;
export declare function nanoid(params?: string | core.$ZodNanoIDParams): ZodMiniNanoID;
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export interface ZodMiniCUID extends _ZodMiniString<core.$ZodCUIDInternals> {
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare const ZodMiniCUID: core.$constructor<ZodMiniCUID>;
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
export declare function cuid(params?: string | core.$ZodCUIDParams): ZodMiniCUID;
export interface ZodMiniCUID2 extends _ZodMiniString<core.$ZodCUID2Internals> {
}
@@ -198,23 +215,23 @@ out Shape extends core.$ZodShape = core.$ZodShape, out Config extends core.$ZodO
shape: Shape;
}
export declare const ZodMiniObject: core.$constructor<ZodMiniObject>;
export declare function object<T extends core.$ZodLooseShape = Record<never, SomeType>>(shape?: T, params?: string | core.$ZodObjectParams): ZodMiniObject<T, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodMiniObject<T, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodMiniObject<T, core.$loose>;
export declare function extend<T extends ZodMiniObject, U extends core.$ZodLooseShape>(schema: T, shape: U): ZodMiniObject<util.Extend<T["shape"], U>, T["_zod"]["config"]>;
export declare function object<T extends core.$ZodLooseShape = Record<never, SomeType>>(shape?: T, params?: string | core.$ZodObjectParams): ZodMiniObject<util.Writeable<T>, core.$strip>;
export declare function strictObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodMiniObject<util.Writeable<T>, core.$strict>;
export declare function looseObject<T extends core.$ZodLooseShape>(shape: T, params?: string | core.$ZodObjectParams): ZodMiniObject<util.Writeable<T>, core.$loose>;
export declare function extend<T extends ZodMiniObject, U extends core.$ZodLooseShape>(schema: T, shape: U): ZodMiniObject<util.Extend<T["shape"], util.Writeable<U>>, T["_zod"]["config"]>;
export type SafeExtendShape<Base extends core.$ZodShape, Ext extends core.$ZodLooseShape> = {
[K in keyof Ext]: K extends keyof Base ? core.output<Ext[K]> extends core.output<Base[K]> ? core.input<Ext[K]> extends core.input<Base[K]> ? Ext[K] : never : never : Ext[K];
};
export declare function safeExtend<T extends ZodMiniObject, U extends core.$ZodLooseShape>(schema: T, shape: SafeExtendShape<T["shape"], U>): ZodMiniObject<util.Extend<T["shape"], U>, T["_zod"]["config"]>;
export declare function safeExtend<T extends ZodMiniObject, U extends core.$ZodLooseShape>(schema: T, shape: SafeExtendShape<T["shape"], U>): ZodMiniObject<util.Extend<T["shape"], util.Writeable<U>>, T["_zod"]["config"]>;
/** @deprecated Identical to `z.extend(A, B)` */
export declare function merge<T extends ZodMiniObject, U extends ZodMiniObject>(a: T, b: U): ZodMiniObject<util.Extend<T["shape"], U["shape"]>, T["_zod"]["config"]>;
export declare function pick<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<util.Flatten<Pick<T["shape"], keyof T["shape"] & keyof M>>, T["_zod"]["config"]>;
export declare function omit<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<util.Flatten<Omit<T["shape"], keyof M>>, T["_zod"]["config"]>;
export declare function partial<T extends ZodMiniObject>(schema: T): ZodMiniObject<{
[k in keyof T["shape"]]: ZodMiniOptional<T["shape"][k]>;
-readonly [k in keyof T["shape"]]: ZodMiniOptional<T["shape"][k]>;
}, T["_zod"]["config"]>;
export declare function partial<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<{
[k in keyof T["shape"]]: k extends keyof M ? ZodMiniOptional<T["shape"][k]> : T["shape"][k];
-readonly [k in keyof T["shape"]]: k extends keyof M ? ZodMiniOptional<T["shape"][k]> : T["shape"][k];
}, T["_zod"]["config"]>;
export type RequiredInterfaceShape<Shape extends core.$ZodLooseShape, Keys extends PropertyKey = keyof Shape> = util.Identity<{
[k in keyof Shape as k extends Keys ? k : never]: ZodMiniNonOptional<Shape[k]>;
@@ -222,7 +239,7 @@ export type RequiredInterfaceShape<Shape extends core.$ZodLooseShape, Keys exten
[k in keyof Shape as k extends Keys ? never : k]: Shape[k];
}>;
export declare function required<T extends ZodMiniObject>(schema: T): ZodMiniObject<{
[k in keyof T["shape"]]: ZodMiniNonOptional<T["shape"][k]>;
-readonly [k in keyof T["shape"]]: ZodMiniNonOptional<T["shape"][k]>;
}, T["_zod"]["config"]>;
export declare function required<T extends ZodMiniObject, M extends util.Mask<keyof T["shape"]>>(schema: T, mask: M & Record<Exclude<keyof M, keyof T["shape"]>, never>): ZodMiniObject<util.Extend<T["shape"], {
[k in keyof M & keyof T["shape"]]: ZodMiniNonOptional<T["shape"][k]>;
@@ -243,7 +260,7 @@ export interface ZodMiniDiscriminatedUnion<Options extends readonly SomeType[] =
_zod: core.$ZodDiscriminatedUnionInternals<Options, Disc>;
}
export declare const ZodMiniDiscriminatedUnion: core.$constructor<ZodMiniDiscriminatedUnion>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable, ...core.$ZodTypeDiscriminable[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodMiniDiscriminatedUnion<Types, Disc>;
export declare function discriminatedUnion<Types extends readonly [core.$ZodTypeDiscriminable<Disc>, ...core.$ZodTypeDiscriminable<Disc>[]], Disc extends string>(discriminator: Disc, options: Types, params?: string | core.$ZodDiscriminatedUnionParams): ZodMiniDiscriminatedUnion<Types, Disc>;
export interface ZodMiniIntersection<A extends SomeType = core.$ZodType, B extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodIntersectionInternals<A, B>> {
}
export declare const ZodMiniIntersection: core.$constructor<ZodMiniIntersection>;
@@ -347,6 +364,7 @@ export declare function codec<const A extends SomeType, B extends core.SomeType
decode: (value: core.output<A>, payload: core.ParsePayload<core.output<A>>) => core.util.MaybeAsync<core.input<B>>;
encode: (value: core.input<B>, payload: core.ParsePayload<core.input<B>>) => core.util.MaybeAsync<core.output<A>>;
}): ZodMiniCodec<A, B>;
export declare function invertCodec<A extends SomeType, B extends SomeType>(codec: ZodMiniCodec<A, B>): ZodMiniCodec<B, A>;
export interface ZodMiniReadonly<T extends SomeType = core.$ZodType> extends _ZodMiniType<core.$ZodReadonlyInternals<T>> {
}
export declare const ZodMiniReadonly: core.$constructor<ZodMiniReadonly>;
@@ -370,7 +388,7 @@ export declare const ZodMiniCustom: core.$constructor<ZodMiniCustom>;
export declare function check<O = unknown>(fn: core.CheckFn<O>, params?: string | core.$ZodCustomParams): core.$ZodCheck<O>;
export declare function custom<O = unknown, I = O>(fn?: (data: O) => unknown, _params?: string | core.$ZodCustomParams | undefined): ZodMiniCustom<O, I>;
export declare function refine<T>(fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>, _params?: string | core.$ZodCustomParams): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>): core.$ZodCheck<T>;
export declare function superRefine<T>(fn: (arg: T, payload: core.$RefinementCtx<T>) => void | Promise<void>, params?: core.$ZodSuperRefineParams): core.$ZodCheck<T>;
export declare const describe: typeof core.describe;
export declare const meta: typeof core.meta;
declare abstract class Class {
+40 -4
View File
@@ -16,7 +16,11 @@ export const ZodMiniType = /*@__PURE__*/ core.$constructor("ZodMiniType", (inst,
...def,
checks: [
...(def.checks ?? []),
...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
...checks.map((ch) => typeof ch === "function"
? {
_zod: { check: ch, def: { check: "custom" }, onattach: [] },
}
: ch),
],
}, { parent: true });
};
@@ -90,7 +94,7 @@ export function url(params) {
// @__NO_SIDE_EFFECTS__
export function httpUrl(params) {
return core._url(ZodMiniURL, {
protocol: /^https?$/,
protocol: core.regexes.httpProtocol,
hostname: core.regexes.domain,
...util.normalizeParams(params),
});
@@ -111,10 +115,22 @@ export const ZodMiniNanoID = /*@__PURE__*/ core.$constructor("ZodMiniNanoID", (i
export function nanoid(params) {
return core._nanoid(ZodMiniNanoID, params);
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link ZodMiniCUID2} instead.
* See https://github.com/paralleldrive/cuid.
*/
export const ZodMiniCUID = /*@__PURE__*/ core.$constructor("ZodMiniCUID", (inst, def) => {
core.$ZodCUID.init(inst, def);
ZodMiniStringFormat.init(inst, def);
});
/**
* Validates a CUID v1 string.
*
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.
* See https://github.com/paralleldrive/cuid.
*/
// @__NO_SIDE_EFFECTS__
export function cuid(params) {
return core._cuid(ZodMiniCUID, params);
@@ -543,6 +559,15 @@ export const ZodMiniRecord = /*@__PURE__*/ core.$constructor("ZodMiniRecord", (i
});
// @__NO_SIDE_EFFECTS__
export function record(keyType, valueType, params) {
// v3-compat: z.record(valueType, params?) — defaults keyType to z.string()
if (!valueType || !valueType._zod) {
return new ZodMiniRecord({
type: "record",
keyType: string(),
valueType: keyType,
...util.normalizeParams(valueType),
});
}
return new ZodMiniRecord({
type: "record",
keyType,
@@ -792,6 +817,17 @@ export function codec(in_, out, params) {
reverseTransform: params.encode,
});
}
// @__NO_SIDE_EFFECTS__
export function invertCodec(codec) {
const def = codec._zod.def;
return new ZodMiniCodec({
type: "pipe",
in: def.out,
out: def.in,
transform: def.reverseTransform,
reverseTransform: def.transform,
});
}
export const ZodMiniReadonly = /*@__PURE__*/ core.$constructor("ZodMiniReadonly", (inst, def) => {
core.$ZodReadonly.init(inst, def);
ZodMiniType.init(inst, def);
@@ -868,8 +904,8 @@ export function refine(fn, _params = {}) {
}
// superRefine
// @__NO_SIDE_EFFECTS__
export function superRefine(fn) {
return core._superRefine(fn);
export function superRefine(fn, params) {
return core._superRefine(fn, params);
}
// Re-export describe and meta from core
export const describe = core.describe;
+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
}