gitea push
This commit is contained in:
+2
-2
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -2,5 +2,6 @@
|
||||
"type": "module",
|
||||
"main": "./index.cjs",
|
||||
"module": "./index.js",
|
||||
"types": "./index.d.cts"
|
||||
"types": "./index.d.cts",
|
||||
"sideEffects": false
|
||||
}
|
||||
|
||||
+358
-119
@@ -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
@@ -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
@@ -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
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user