Add extracted source directory and README navigation

This commit is contained in:
Shawn Bot
2026-03-31 14:56:06 +00:00
parent 6252bb6eb5
commit 91e01d755b
4757 changed files with 984951 additions and 0 deletions

906
extracted-source/node_modules/zod/v4/core/api.js generated vendored Normal file
View File

@@ -0,0 +1,906 @@
import * as checks from "./checks.js";
import * as schemas from "./schemas.js";
import * as util from "./util.js";
export function _string(Class, params) {
return new Class({
type: "string",
...util.normalizeParams(params),
});
}
export function _coercedString(Class, params) {
return new Class({
type: "string",
coerce: true,
...util.normalizeParams(params),
});
}
export function _email(Class, params) {
return new Class({
type: "string",
format: "email",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _guid(Class, params) {
return new Class({
type: "string",
format: "guid",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _uuid(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _uuidv4(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v4",
...util.normalizeParams(params),
});
}
export function _uuidv6(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v6",
...util.normalizeParams(params),
});
}
export function _uuidv7(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v7",
...util.normalizeParams(params),
});
}
export function _url(Class, params) {
return new Class({
type: "string",
format: "url",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _emoji(Class, params) {
return new Class({
type: "string",
format: "emoji",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _nanoid(Class, params) {
return new Class({
type: "string",
format: "nanoid",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _cuid(Class, params) {
return new Class({
type: "string",
format: "cuid",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _cuid2(Class, params) {
return new Class({
type: "string",
format: "cuid2",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _ulid(Class, params) {
return new Class({
type: "string",
format: "ulid",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _xid(Class, params) {
return new Class({
type: "string",
format: "xid",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _ksuid(Class, params) {
return new Class({
type: "string",
format: "ksuid",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _ipv4(Class, params) {
return new Class({
type: "string",
format: "ipv4",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _ipv6(Class, params) {
return new Class({
type: "string",
format: "ipv6",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _cidrv4(Class, params) {
return new Class({
type: "string",
format: "cidrv4",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _cidrv6(Class, params) {
return new Class({
type: "string",
format: "cidrv6",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _base64(Class, params) {
return new Class({
type: "string",
format: "base64",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _base64url(Class, params) {
return new Class({
type: "string",
format: "base64url",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _e164(Class, params) {
return new Class({
type: "string",
format: "e164",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export function _jwt(Class, params) {
return new Class({
type: "string",
format: "jwt",
check: "string_format",
abort: false,
...util.normalizeParams(params),
});
}
export const TimePrecision = {
Any: null,
Minute: -1,
Second: 0,
Millisecond: 3,
Microsecond: 6,
};
export function _isoDateTime(Class, params) {
return new Class({
type: "string",
format: "datetime",
check: "string_format",
offset: false,
local: false,
precision: null,
...util.normalizeParams(params),
});
}
export function _isoDate(Class, params) {
return new Class({
type: "string",
format: "date",
check: "string_format",
...util.normalizeParams(params),
});
}
export function _isoTime(Class, params) {
return new Class({
type: "string",
format: "time",
check: "string_format",
precision: null,
...util.normalizeParams(params),
});
}
export function _isoDuration(Class, params) {
return new Class({
type: "string",
format: "duration",
check: "string_format",
...util.normalizeParams(params),
});
}
export function _number(Class, params) {
return new Class({
type: "number",
checks: [],
...util.normalizeParams(params),
});
}
export function _coercedNumber(Class, params) {
return new Class({
type: "number",
coerce: true,
checks: [],
...util.normalizeParams(params),
});
}
export function _int(Class, params) {
return new Class({
type: "number",
check: "number_format",
abort: false,
format: "safeint",
...util.normalizeParams(params),
});
}
export function _float32(Class, params) {
return new Class({
type: "number",
check: "number_format",
abort: false,
format: "float32",
...util.normalizeParams(params),
});
}
export function _float64(Class, params) {
return new Class({
type: "number",
check: "number_format",
abort: false,
format: "float64",
...util.normalizeParams(params),
});
}
export function _int32(Class, params) {
return new Class({
type: "number",
check: "number_format",
abort: false,
format: "int32",
...util.normalizeParams(params),
});
}
export function _uint32(Class, params) {
return new Class({
type: "number",
check: "number_format",
abort: false,
format: "uint32",
...util.normalizeParams(params),
});
}
export function _boolean(Class, params) {
return new Class({
type: "boolean",
...util.normalizeParams(params),
});
}
export function _coercedBoolean(Class, params) {
return new Class({
type: "boolean",
coerce: true,
...util.normalizeParams(params),
});
}
export function _bigint(Class, params) {
return new Class({
type: "bigint",
...util.normalizeParams(params),
});
}
export function _coercedBigint(Class, params) {
return new Class({
type: "bigint",
coerce: true,
...util.normalizeParams(params),
});
}
export function _int64(Class, params) {
return new Class({
type: "bigint",
check: "bigint_format",
abort: false,
format: "int64",
...util.normalizeParams(params),
});
}
export function _uint64(Class, params) {
return new Class({
type: "bigint",
check: "bigint_format",
abort: false,
format: "uint64",
...util.normalizeParams(params),
});
}
export function _symbol(Class, params) {
return new Class({
type: "symbol",
...util.normalizeParams(params),
});
}
export function _undefined(Class, params) {
return new Class({
type: "undefined",
...util.normalizeParams(params),
});
}
export function _null(Class, params) {
return new Class({
type: "null",
...util.normalizeParams(params),
});
}
export function _any(Class) {
return new Class({
type: "any",
});
}
export function _unknown(Class) {
return new Class({
type: "unknown",
});
}
export function _never(Class, params) {
return new Class({
type: "never",
...util.normalizeParams(params),
});
}
export function _void(Class, params) {
return new Class({
type: "void",
...util.normalizeParams(params),
});
}
export function _date(Class, params) {
return new Class({
type: "date",
...util.normalizeParams(params),
});
}
export function _coercedDate(Class, params) {
return new Class({
type: "date",
coerce: true,
...util.normalizeParams(params),
});
}
export function _nan(Class, params) {
return new Class({
type: "nan",
...util.normalizeParams(params),
});
}
export function _lt(value, params) {
return new checks.$ZodCheckLessThan({
check: "less_than",
...util.normalizeParams(params),
value,
inclusive: false,
});
}
export function _lte(value, params) {
return new checks.$ZodCheckLessThan({
check: "less_than",
...util.normalizeParams(params),
value,
inclusive: true,
});
}
export {
/** @deprecated Use `z.lte()` instead. */
_lte as _max, };
export function _gt(value, params) {
return new checks.$ZodCheckGreaterThan({
check: "greater_than",
...util.normalizeParams(params),
value,
inclusive: false,
});
}
export function _gte(value, params) {
return new checks.$ZodCheckGreaterThan({
check: "greater_than",
...util.normalizeParams(params),
value,
inclusive: true,
});
}
export {
/** @deprecated Use `z.gte()` instead. */
_gte as _min, };
export function _positive(params) {
return _gt(0, params);
}
// negative
export function _negative(params) {
return _lt(0, params);
}
// nonpositive
export function _nonpositive(params) {
return _lte(0, params);
}
// nonnegative
export function _nonnegative(params) {
return _gte(0, params);
}
export function _multipleOf(value, params) {
return new checks.$ZodCheckMultipleOf({
check: "multiple_of",
...util.normalizeParams(params),
value,
});
}
export function _maxSize(maximum, params) {
return new checks.$ZodCheckMaxSize({
check: "max_size",
...util.normalizeParams(params),
maximum,
});
}
export function _minSize(minimum, params) {
return new checks.$ZodCheckMinSize({
check: "min_size",
...util.normalizeParams(params),
minimum,
});
}
export function _size(size, params) {
return new checks.$ZodCheckSizeEquals({
check: "size_equals",
...util.normalizeParams(params),
size,
});
}
export function _maxLength(maximum, params) {
const ch = new checks.$ZodCheckMaxLength({
check: "max_length",
...util.normalizeParams(params),
maximum,
});
return ch;
}
export function _minLength(minimum, params) {
return new checks.$ZodCheckMinLength({
check: "min_length",
...util.normalizeParams(params),
minimum,
});
}
export function _length(length, params) {
return new checks.$ZodCheckLengthEquals({
check: "length_equals",
...util.normalizeParams(params),
length,
});
}
export function _regex(pattern, params) {
return new checks.$ZodCheckRegex({
check: "string_format",
format: "regex",
...util.normalizeParams(params),
pattern,
});
}
export function _lowercase(params) {
return new checks.$ZodCheckLowerCase({
check: "string_format",
format: "lowercase",
...util.normalizeParams(params),
});
}
export function _uppercase(params) {
return new checks.$ZodCheckUpperCase({
check: "string_format",
format: "uppercase",
...util.normalizeParams(params),
});
}
export function _includes(includes, params) {
return new checks.$ZodCheckIncludes({
check: "string_format",
format: "includes",
...util.normalizeParams(params),
includes,
});
}
export function _startsWith(prefix, params) {
return new checks.$ZodCheckStartsWith({
check: "string_format",
format: "starts_with",
...util.normalizeParams(params),
prefix,
});
}
export function _endsWith(suffix, params) {
return new checks.$ZodCheckEndsWith({
check: "string_format",
format: "ends_with",
...util.normalizeParams(params),
suffix,
});
}
export function _property(property, schema, params) {
return new checks.$ZodCheckProperty({
check: "property",
property,
schema,
...util.normalizeParams(params),
});
}
export function _mime(types, params) {
return new checks.$ZodCheckMimeType({
check: "mime_type",
mime: types,
...util.normalizeParams(params),
});
}
export function _overwrite(tx) {
return new checks.$ZodCheckOverwrite({
check: "overwrite",
tx,
});
}
// normalize
export function _normalize(form) {
return _overwrite((input) => input.normalize(form));
}
// trim
export function _trim() {
return _overwrite((input) => input.trim());
}
// toLowerCase
export function _toLowerCase() {
return _overwrite((input) => input.toLowerCase());
}
// toUpperCase
export function _toUpperCase() {
return _overwrite((input) => input.toUpperCase());
}
export function _array(Class, element, params) {
return new Class({
type: "array",
element,
// get element() {
// return element;
// },
...util.normalizeParams(params),
});
}
export function _union(Class, options, params) {
return new Class({
type: "union",
options,
...util.normalizeParams(params),
});
}
export function _discriminatedUnion(Class, discriminator, options, params) {
return new Class({
type: "union",
options,
discriminator,
...util.normalizeParams(params),
});
}
export function _intersection(Class, left, right) {
return new Class({
type: "intersection",
left,
right,
});
}
// export function _tuple(
// Class: util.SchemaClass<schemas.$ZodTuple>,
// items: [],
// params?: string | $ZodTupleParams
// ): schemas.$ZodTuple<[], null>;
export function _tuple(Class, items, _paramsOrRest, _params) {
const hasRest = _paramsOrRest instanceof schemas.$ZodType;
const params = hasRest ? _params : _paramsOrRest;
const rest = hasRest ? _paramsOrRest : null;
return new Class({
type: "tuple",
items,
rest,
...util.normalizeParams(params),
});
}
export function _record(Class, keyType, valueType, params) {
return new Class({
type: "record",
keyType,
valueType,
...util.normalizeParams(params),
});
}
export function _map(Class, keyType, valueType, params) {
return new Class({
type: "map",
keyType,
valueType,
...util.normalizeParams(params),
});
}
export function _set(Class, valueType, params) {
return new Class({
type: "set",
valueType,
...util.normalizeParams(params),
});
}
export function _enum(Class, values, params) {
const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
// if (Array.isArray(values)) {
// for (const value of values) {
// entries[value] = value;
// }
// } else {
// Object.assign(entries, values);
// }
// const entries: util.EnumLike = {};
// for (const val of values) {
// entries[val] = val;
// }
return new Class({
type: "enum",
entries,
...util.normalizeParams(params),
});
}
/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.
*
* ```ts
* enum Colors { red, green, blue }
* z.enum(Colors);
* ```
*/
export function _nativeEnum(Class, entries, params) {
return new Class({
type: "enum",
entries,
...util.normalizeParams(params),
});
}
export function _literal(Class, value, params) {
return new Class({
type: "literal",
values: Array.isArray(value) ? value : [value],
...util.normalizeParams(params),
});
}
export function _file(Class, params) {
return new Class({
type: "file",
...util.normalizeParams(params),
});
}
export function _transform(Class, fn) {
return new Class({
type: "transform",
transform: fn,
});
}
export function _optional(Class, innerType) {
return new Class({
type: "optional",
innerType,
});
}
export function _nullable(Class, innerType) {
return new Class({
type: "nullable",
innerType,
});
}
export function _default(Class, innerType, defaultValue) {
return new Class({
type: "default",
innerType,
get defaultValue() {
return typeof defaultValue === "function" ? defaultValue() : defaultValue;
},
});
}
export function _nonoptional(Class, innerType, params) {
return new Class({
type: "nonoptional",
innerType,
...util.normalizeParams(params),
});
}
export function _success(Class, innerType) {
return new Class({
type: "success",
innerType,
});
}
export function _catch(Class, innerType, catchValue) {
return new Class({
type: "catch",
innerType,
catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue),
});
}
export function _pipe(Class, in_, out) {
return new Class({
type: "pipe",
in: in_,
out,
});
}
export function _readonly(Class, innerType) {
return new Class({
type: "readonly",
innerType,
});
}
export function _templateLiteral(Class, parts, params) {
return new Class({
type: "template_literal",
parts,
...util.normalizeParams(params),
});
}
export function _lazy(Class, getter) {
return new Class({
type: "lazy",
getter,
});
}
export function _promise(Class, innerType) {
return new Class({
type: "promise",
innerType,
});
}
export function _custom(Class, fn, _params) {
const norm = util.normalizeParams(_params);
norm.abort ?? (norm.abort = true); // default to abort:false
const schema = new Class({
type: "custom",
check: "custom",
fn: fn,
...norm,
});
return schema;
}
// export function _refine<T>(
// Class: util.SchemaClass<schemas.$ZodCustom>,
// fn: (arg: NoInfer<T>) => util.MaybeAsync<unknown>,
// _params: string | $ZodCustomParams = {}
// ): checks.$ZodCheck<T> {
// return _custom(Class, fn, _params);
// }
// same as _custom but defaults to abort:false
export function _refine(Class, fn, _params) {
const schema = new Class({
type: "custom",
check: "custom",
fn: fn,
...util.normalizeParams(_params),
});
return schema;
}
export function _stringbool(Classes, _params) {
const params = util.normalizeParams(_params);
let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"];
let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"];
if (params.case !== "sensitive") {
truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v));
falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v));
}
const truthySet = new Set(truthyArray);
const falsySet = new Set(falsyArray);
const _Pipe = Classes.Pipe ?? schemas.$ZodPipe;
const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;
const _String = Classes.String ?? schemas.$ZodString;
const _Transform = Classes.Transform ?? schemas.$ZodTransform;
const tx = new _Transform({
type: "transform",
transform: (input, payload) => {
let data = input;
if (params.case !== "sensitive")
data = data.toLowerCase();
if (truthySet.has(data)) {
return true;
}
else if (falsySet.has(data)) {
return false;
}
else {
payload.issues.push({
code: "invalid_value",
expected: "stringbool",
values: [...truthySet, ...falsySet],
input: payload.value,
inst: tx,
});
return {};
}
},
error: params.error,
});
// params.error;
const innerPipe = new _Pipe({
type: "pipe",
in: new _String({ type: "string", error: params.error }),
out: tx,
error: params.error,
});
const outerPipe = new _Pipe({
type: "pipe",
in: innerPipe,
out: new _Boolean({
type: "boolean",
error: params.error,
}),
error: params.error,
});
return outerPipe;
}
export function _stringFormat(Class, format, fnOrRegex, _params = {}) {
const params = util.normalizeParams(_params);
const def = {
...util.normalizeParams(_params),
check: "string_format",
type: "string",
format,
fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
...params,
};
if (fnOrRegex instanceof RegExp) {
def.pattern = fnOrRegex;
}
const inst = new Class(def);
return inst;
}

559
extracted-source/node_modules/zod/v4/core/checks.js generated vendored Normal file
View File

@@ -0,0 +1,559 @@
// import { $ZodType } from "./schemas.js";
import * as core from "./core.js";
import * as regexes from "./regexes.js";
import * as util from "./util.js";
export const $ZodCheck = /*@__PURE__*/ core.$constructor("$ZodCheck", (inst, def) => {
var _a;
inst._zod ?? (inst._zod = {});
inst._zod.def = def;
(_a = inst._zod).onattach ?? (_a.onattach = []);
});
const numericOriginMap = {
number: "number",
bigint: "bigint",
object: "date",
};
export const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor("$ZodCheckLessThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
if (def.value < curr) {
if (def.inclusive)
bag.maximum = def.value;
else
bag.exclusiveMaximum = def.value;
}
});
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
return;
}
payload.issues.push({
origin,
code: "too_big",
maximum: def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor("$ZodCheckGreaterThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
if (def.value > curr) {
if (def.inclusive)
bag.minimum = def.value;
else
bag.exclusiveMinimum = def.value;
}
});
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
return;
}
payload.issues.push({
origin,
code: "too_small",
minimum: def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckMultipleOf =
/*@__PURE__*/ core.$constructor("$ZodCheckMultipleOf", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.onattach.push((inst) => {
var _a;
(_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
});
inst._zod.check = (payload) => {
if (typeof payload.value !== typeof def.value)
throw new Error("Cannot mix number and bigint in multiple_of check.");
const isMultiple = typeof payload.value === "bigint"
? payload.value % def.value === BigInt(0)
: util.floatSafeRemainder(payload.value, def.value) === 0;
if (isMultiple)
return;
payload.issues.push({
origin: typeof payload.value,
code: "not_multiple_of",
divisor: def.value,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor("$ZodCheckNumberFormat", (inst, def) => {
$ZodCheck.init(inst, def); // no format checks
def.format = def.format || "float64";
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.format = def.format;
bag.minimum = minimum;
bag.maximum = maximum;
if (isInt)
bag.pattern = regexes.integer;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
if (!Number.isInteger(input)) {
// invalid_format issue
// payload.issues.push({
// expected: def.format,
// format: def.format,
// code: "invalid_format",
// input,
// inst,
// });
// invalid_type issue
payload.issues.push({
expected: origin,
format: def.format,
code: "invalid_type",
input,
inst,
});
return;
// not_multiple_of issue
// payload.issues.push({
// code: "not_multiple_of",
// origin: "number",
// input,
// inst,
// divisor: 1,
// });
}
if (!Number.isSafeInteger(input)) {
if (input > 0) {
// too_big
payload.issues.push({
input,
code: "too_big",
maximum: Number.MAX_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
continue: !def.abort,
});
}
else {
// too_small
payload.issues.push({
input,
code: "too_small",
minimum: Number.MIN_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
continue: !def.abort,
});
}
return;
}
}
if (input < minimum) {
payload.issues.push({
origin: "number",
input,
code: "too_small",
minimum,
inclusive: true,
inst,
continue: !def.abort,
});
}
if (input > maximum) {
payload.issues.push({
origin: "number",
input,
code: "too_big",
maximum,
inst,
});
}
};
});
export const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor("$ZodCheckBigIntFormat", (inst, def) => {
$ZodCheck.init(inst, def); // no format checks
const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.format = def.format;
bag.minimum = minimum;
bag.maximum = maximum;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (input < minimum) {
payload.issues.push({
origin: "bigint",
input,
code: "too_small",
minimum: minimum,
inclusive: true,
inst,
continue: !def.abort,
});
}
if (input > maximum) {
payload.issues.push({
origin: "bigint",
input,
code: "too_big",
maximum,
inst,
});
}
};
});
export const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor("$ZodCheckMaxSize", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.size !== undefined;
};
inst._zod.onattach.push((inst) => {
const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);
if (def.maximum < curr)
inst._zod.bag.maximum = def.maximum;
});
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size <= def.maximum)
return;
payload.issues.push({
origin: util.getSizableOrigin(input),
code: "too_big",
maximum: def.maximum,
input,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor("$ZodCheckMinSize", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.size !== undefined;
};
inst._zod.onattach.push((inst) => {
const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);
if (def.minimum > curr)
inst._zod.bag.minimum = def.minimum;
});
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size >= def.minimum)
return;
payload.issues.push({
origin: util.getSizableOrigin(input),
code: "too_small",
minimum: def.minimum,
input,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor("$ZodCheckSizeEquals", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.size !== undefined;
};
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.minimum = def.size;
bag.maximum = def.size;
bag.size = def.size;
});
inst._zod.check = (payload) => {
const input = payload.value;
const size = input.size;
if (size === def.size)
return;
const tooBig = size > def.size;
payload.issues.push({
origin: util.getSizableOrigin(input),
...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }),
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor("$ZodCheckMaxLength", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.length !== undefined;
};
inst._zod.onattach.push((inst) => {
const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);
if (def.maximum < curr)
inst._zod.bag.maximum = def.maximum;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length <= def.maximum)
return;
const origin = util.getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor("$ZodCheckMinLength", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.length !== undefined;
};
inst._zod.onattach.push((inst) => {
const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);
if (def.minimum > curr)
inst._zod.bag.minimum = def.minimum;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length >= def.minimum)
return;
const origin = util.getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor("$ZodCheckLengthEquals", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.when = (payload) => {
const val = payload.value;
return !util.nullish(val) && val.length !== undefined;
};
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.minimum = def.length;
bag.maximum = def.length;
bag.length = def.length;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length === def.length)
return;
const origin = util.getLengthableOrigin(input);
const tooBig = length > def.length;
payload.issues.push({
origin,
...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }),
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor("$ZodCheckStringFormat", (inst, def) => {
var _a, _b;
$ZodCheck.init(inst, def);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.format = def.format;
if (def.pattern) {
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(def.pattern);
}
});
if (def.pattern)
(_a = inst._zod).check ?? (_a.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: def.format,
input: payload.value,
...(def.pattern ? { pattern: def.pattern.toString() } : {}),
inst,
continue: !def.abort,
});
});
else
(_b = inst._zod).check ?? (_b.check = () => { });
});
export const $ZodCheckRegex = /*@__PURE__*/ core.$constructor("$ZodCheckRegex", (inst, def) => {
$ZodCheckStringFormat.init(inst, def);
inst._zod.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "regex",
input: payload.value,
pattern: def.pattern.toString(),
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor("$ZodCheckLowerCase", (inst, def) => {
def.pattern ?? (def.pattern = regexes.lowercase);
$ZodCheckStringFormat.init(inst, def);
});
export const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor("$ZodCheckUpperCase", (inst, def) => {
def.pattern ?? (def.pattern = regexes.uppercase);
$ZodCheckStringFormat.init(inst, def);
});
export const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor("$ZodCheckIncludes", (inst, def) => {
$ZodCheck.init(inst, def);
const escapedRegex = util.escapeRegex(def.includes);
const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
def.pattern = pattern;
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.includes(def.includes, def.position))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "includes",
includes: def.includes,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor("$ZodCheckStartsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.startsWith(def.prefix))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "starts_with",
prefix: def.prefix,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
export const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor("$ZodCheckEndsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.endsWith(def.suffix))
return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "ends_with",
suffix: def.suffix,
input: payload.value,
inst,
continue: !def.abort,
});
};
});
///////////////////////////////////
///// $ZodCheckProperty /////
///////////////////////////////////
function handleCheckPropertyResult(result, payload, property) {
if (result.issues.length) {
payload.issues.push(...util.prefixIssues(property, result.issues));
}
}
export const $ZodCheckProperty = /*@__PURE__*/ core.$constructor("$ZodCheckProperty", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
const result = def.schema._zod.run({
value: payload.value[def.property],
issues: [],
}, {});
if (result instanceof Promise) {
return result.then((result) => handleCheckPropertyResult(result, payload, def.property));
}
handleCheckPropertyResult(result, payload, def.property);
return;
};
});
export const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor("$ZodCheckMimeType", (inst, def) => {
$ZodCheck.init(inst, def);
const mimeSet = new Set(def.mime);
inst._zod.onattach.push((inst) => {
inst._zod.bag.mime = def.mime;
});
inst._zod.check = (payload) => {
if (mimeSet.has(payload.value.type))
return;
payload.issues.push({
code: "invalid_value",
values: def.mime,
input: payload.value.type,
inst,
});
};
});
export const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor("$ZodCheckOverwrite", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
payload.value = def.tx(payload.value);
};
});

61
extracted-source/node_modules/zod/v4/core/core.js generated vendored Normal file
View File

@@ -0,0 +1,61 @@
/** A special constant with type `never` */
export const NEVER = Object.freeze({
status: "aborted",
});
export /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {
function init(inst, def) {
var _a;
Object.defineProperty(inst, "_zod", {
value: inst._zod ?? {},
enumerable: false,
});
(_a = inst._zod).traits ?? (_a.traits = new Set());
inst._zod.traits.add(name);
initializer(inst, def);
// support prototype modifications
for (const k in _.prototype) {
if (!(k in inst))
Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
}
inst._zod.constr = _;
inst._zod.def = def;
}
// doesn't work if Parent has a constructor with arguments
const Parent = params?.Parent ?? Object;
class Definition extends Parent {
}
Object.defineProperty(Definition, "name", { value: name });
function _(def) {
var _a;
const inst = params?.Parent ? new Definition() : this;
init(inst, def);
(_a = inst._zod).deferred ?? (_a.deferred = []);
for (const fn of inst._zod.deferred) {
fn();
}
return inst;
}
Object.defineProperty(_, "init", { value: init });
Object.defineProperty(_, Symbol.hasInstance, {
value: (inst) => {
if (params?.Parent && inst instanceof params.Parent)
return true;
return inst?._zod?.traits?.has(name);
},
});
Object.defineProperty(_, "name", { value: name });
return _;
}
////////////////////////////// UTILITIES ///////////////////////////////////////
export const $brand = Symbol("zod_brand");
export class $ZodAsyncError extends Error {
constructor() {
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
}
}
export const globalConfig = {};
export function config(newConfig) {
if (newConfig)
Object.assign(globalConfig, newConfig);
return globalConfig;
}

35
extracted-source/node_modules/zod/v4/core/doc.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
export class Doc {
constructor(args = []) {
this.content = [];
this.indent = 0;
if (this)
this.args = args;
}
indented(fn) {
this.indent += 1;
fn(this);
this.indent -= 1;
}
write(arg) {
if (typeof arg === "function") {
arg(this, { execution: "sync" });
arg(this, { execution: "async" });
return;
}
const content = arg;
const lines = content.split("\n").filter((x) => x);
const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
for (const line of dedented) {
this.content.push(line);
}
}
compile() {
const F = Function;
const args = this?.args;
const content = this?.content ?? [``];
const lines = [...content.map((x) => ` ${x}`)];
// console.log(lines.join("\n"));
return new F(...args, lines.join("\n"));
}
}

191
extracted-source/node_modules/zod/v4/core/errors.js generated vendored Normal file
View File

@@ -0,0 +1,191 @@
import { $constructor } from "./core.js";
import * as util from "./util.js";
const initializer = (inst, def) => {
inst.name = "$ZodError";
Object.defineProperty(inst, "_zod", {
value: inst._zod,
enumerable: false,
});
Object.defineProperty(inst, "issues", {
value: def,
enumerable: false,
});
Object.defineProperty(inst, "message", {
get() {
return JSON.stringify(def, util.jsonStringifyReplacer, 2);
},
enumerable: true,
// configurable: false,
});
};
export const $ZodError = $constructor("$ZodError", initializer);
export const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
export function flattenError(error, mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of error.issues) {
if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(mapper(sub));
}
else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
export function formatError(error, _mapper) {
const mapper = _mapper ||
function (issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union" && issue.errors.length) {
issue.errors.map((issues) => processError({ issues }));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues });
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues });
}
else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
}
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: [] };
}
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(error);
return fieldErrors;
}
export function treeifyError(error, _mapper) {
const mapper = _mapper ||
function (issue) {
return issue.message;
};
const result = { errors: [] };
const processError = (error, path = []) => {
var _a, _b;
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));
}
else if (issue.code === "invalid_key") {
processError({ issues: issue.issues }, issue.path);
}
else if (issue.code === "invalid_element") {
processError({ issues: issue.issues }, issue.path);
}
else {
const fullpath = [...path, ...issue.path];
if (fullpath.length === 0) {
result.errors.push(mapper(issue));
continue;
}
let curr = result;
let i = 0;
while (i < fullpath.length) {
const el = fullpath[i];
const terminal = i === fullpath.length - 1;
if (typeof el === "string") {
curr.properties ?? (curr.properties = {});
(_a = curr.properties)[el] ?? (_a[el] = { errors: [] });
curr = curr.properties[el];
}
else {
curr.items ?? (curr.items = []);
(_b = curr.items)[el] ?? (_b[el] = { errors: [] });
curr = curr.items[el];
}
if (terminal) {
curr.errors.push(mapper(issue));
}
i++;
}
}
}
};
processError(error);
return result;
}
/** Format a ZodError as a human-readable string in the following form.
*
* From
*
* ```ts
* ZodError {
* issues: [
* {
* expected: 'string',
* code: 'invalid_type',
* path: [ 'username' ],
* message: 'Invalid input: expected string'
* },
* {
* expected: 'number',
* code: 'invalid_type',
* path: [ 'favoriteNumbers', 1 ],
* message: 'Invalid input: expected number'
* }
* ];
* }
* ```
*
* to
*
* ```
* username
* ✖ Expected number, received string at "username
* favoriteNumbers[0]
* ✖ Invalid input: expected number
* ```
*/
export function toDotPath(path) {
const segs = [];
for (const seg of path) {
if (typeof seg === "number")
segs.push(`[${seg}]`);
else if (typeof seg === "symbol")
segs.push(`[${JSON.stringify(String(seg))}]`);
else if (/[^\w$]/.test(seg))
segs.push(`[${JSON.stringify(seg)}]`);
else {
if (segs.length)
segs.push(".");
segs.push(seg);
}
}
return segs.join("");
}
export function prettifyError(error) {
const lines = [];
// sort by path length
const issues = [...error.issues].sort((a, b) => a.path.length - b.path.length);
// Process each issue
for (const issue of issues) {
lines.push(`${issue.message}`);
if (issue.path?.length)
lines.push(` → at ${toDotPath(issue.path)}`);
}
// Convert Map to formatted string
return lines.join("\n");
}

75
extracted-source/node_modules/zod/v4/core/function.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
import { _array, _tuple, _unknown } from "./api.js";
import { parse, parseAsync } from "./parse.js";
import * as schemas from "./schemas.js";
import { $ZodTuple } from "./schemas.js";
export class $ZodFunction {
constructor(def) {
this._def = def;
this.def = def;
}
implement(func) {
if (typeof func !== "function") {
throw new Error("implement() must be called with a function");
}
const impl = ((...args) => {
const parsedArgs = this._def.input ? parse(this._def.input, args, undefined, { callee: impl }) : args;
if (!Array.isArray(parsedArgs)) {
throw new Error("Invalid arguments schema: not an array or tuple schema.");
}
const output = func(...parsedArgs);
return this._def.output ? parse(this._def.output, output, undefined, { callee: impl }) : output;
});
return impl;
}
implementAsync(func) {
if (typeof func !== "function") {
throw new Error("implement() must be called with a function");
}
const impl = (async (...args) => {
const parsedArgs = this._def.input ? await parseAsync(this._def.input, args, undefined, { callee: impl }) : args;
if (!Array.isArray(parsedArgs)) {
throw new Error("Invalid arguments schema: not an array or tuple schema.");
}
const output = await func(...parsedArgs);
return this._def.output ? parseAsync(this._def.output, output, undefined, { callee: impl }) : output;
});
return impl;
}
input(...args) {
const F = this.constructor;
if (Array.isArray(args[0])) {
return new F({
type: "function",
input: new $ZodTuple({
type: "tuple",
items: args[0],
rest: args[1],
}),
output: this._def.output,
});
}
return new F({
type: "function",
input: args[0],
output: this._def.output,
});
}
output(output) {
const F = this.constructor;
return new F({
type: "function",
input: this._def.input,
output,
});
}
}
function _function(params) {
return new $ZodFunction({
type: "function",
input: Array.isArray(params?.input)
? _tuple(schemas.$ZodTuple, params?.input)
: (params?.input ?? _array(schemas.$ZodArray, _unknown(schemas.$ZodUnknown))),
output: params?.output ?? _unknown(schemas.$ZodUnknown),
});
}
export { _function as function };

15
extracted-source/node_modules/zod/v4/core/index.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
export * from "./core.js";
export * from "./parse.js";
export * from "./errors.js";
export * from "./schemas.js";
export * from "./checks.js";
export * from "./versions.js";
export * as util from "./util.js";
export * as regexes from "./regexes.js";
export * as locales from "../locales/index.js";
export * from "./registries.js";
export * from "./doc.js";
export * from "./function.js";
export * from "./api.js";
export * from "./to-json-schema.js";
export * as JSONSchema from "./json-schema.js";

57
extracted-source/node_modules/zod/v4/core/parse.js generated vendored Normal file
View File

@@ -0,0 +1,57 @@
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 result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
if (result.issues.length) {
const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
util.captureStackTrace(e, _params?.callee);
throw e;
}
return result.value;
};
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 };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
if (result.issues.length) {
const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
util.captureStackTrace(e, params?.callee);
throw e;
}
return result.value;
};
export const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);
export const _safeParse = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
return result.issues.length
? {
success: false,
error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),
}
: { success: true, data: result.value };
};
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 };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
return result.issues.length
? {
success: false,
error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),
}
: { success: true, data: result.value };
};
export const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);

95
extracted-source/node_modules/zod/v4/core/regexes.js generated vendored Normal file
View File

@@ -0,0 +1,95 @@
export const cuid = /^[cC][^\s-]{8,}$/;
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}$/;
export const ksuid = /^[A-Za-z0-9]{27}$/;
export const nanoid = /^[a-zA-Z0-9_-]{21}$/;
/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
export const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */
export const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
export const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
/** Returns a regex for validating an RFC 4122 UUID.
*
* @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
export const uuid = (version) => {
if (!version)
return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
export const uuid4 = /*@__PURE__*/ uuid(4);
export const uuid6 = /*@__PURE__*/ uuid(6);
export const uuid7 = /*@__PURE__*/ uuid(7);
/** Practical email validation */
export const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */
export const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/** The classic emailregex.com regex for RFC 5322-compliant emails */
export const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */
export const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
export const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
export const _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
export function emoji() {
return new RegExp(_emoji, "u");
}
export const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
export const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
export const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
export const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
export const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
export const base64url = /^[A-Za-z0-9_-]*$/;
// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
// export const hostname: RegExp =
// /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/;
export const hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
export const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
export const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
// const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
export const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);
function timeSource(args) {
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
const regex = typeof args.precision === "number"
? args.precision === -1
? `${hhmm}`
: args.precision === 0
? `${hhmm}:[0-5]\\d`
: `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`
: `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
return regex;
}
export function time(args) {
return new RegExp(`^${timeSource(args)}$`);
}
// Adapted from https://stackoverflow.com/a/3143231
export function datetime(args) {
const time = timeSource({ precision: args.precision });
const opts = ["Z"];
if (args.local)
opts.push("");
if (args.offset)
opts.push(`([+-]\\d{2}:\\d{2})`);
const timeRegex = `${time}(?:${opts.join("|")})`;
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
export const string = (params) => {
const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
return new RegExp(`^${regex}$`);
};
export const bigint = /^\d+n?$/;
export const integer = /^\d+$/;
export const number = /^-?\d+(?:\.\d+)?/i;
export const boolean = /true|false/i;
const _null = /null/i;
export { _null as null };
const _undefined = /undefined/i;
export { _undefined as undefined };
// regex for string with no uppercase letters
export const lowercase = /^[^A-Z]*$/;
// regex for string with no lowercase letters
export const uppercase = /^[^a-z]*$/;

View File

@@ -0,0 +1,42 @@
export const $output = Symbol("ZodOutput");
export const $input = Symbol("ZodInput");
export class $ZodRegistry {
constructor() {
this._map = new WeakMap();
this._idmap = new Map();
}
add(schema, ..._meta) {
const meta = _meta[0];
this._map.set(schema, meta);
if (meta && typeof meta === "object" && "id" in meta) {
if (this._idmap.has(meta.id)) {
throw new Error(`ID ${meta.id} already exists in the registry`);
}
this._idmap.set(meta.id, schema);
}
return this;
}
remove(schema) {
this._map.delete(schema);
return this;
}
get(schema) {
// return this._map.get(schema) as any;
// inherit metadata
const p = schema._zod.parent;
if (p) {
const pm = { ...(this.get(p) ?? {}) };
delete pm.id; // do not inherit id
return { ...pm, ...this._map.get(schema) };
}
return this._map.get(schema);
}
has(schema) {
return this._map.has(schema);
}
}
// registries
export function registry() {
return new $ZodRegistry();
}
export const globalRegistry = /*@__PURE__*/ registry();

1717
extracted-source/node_modules/zod/v4/core/schemas.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,825 @@
import { $ZodRegistry, globalRegistry } from "./registries.js";
import { getEnumValues } from "./util.js";
export class JSONSchemaGenerator {
constructor(params) {
this.counter = 0;
this.metadataRegistry = params?.metadata ?? globalRegistry;
this.target = params?.target ?? "draft-2020-12";
this.unrepresentable = params?.unrepresentable ?? "throw";
this.override = params?.override ?? (() => { });
this.io = params?.io ?? "output";
this.seen = new Map();
}
process(schema, _params = { path: [], schemaPath: [] }) {
var _a;
const def = schema._zod.def;
const formatMap = {
guid: "uuid",
url: "uri",
datetime: "date-time",
json_string: "json-string",
regex: "", // do not set
};
// check for schema in seens
const seen = this.seen.get(schema);
if (seen) {
seen.count++;
// check if cycle
const isCycle = _params.schemaPath.includes(schema);
if (isCycle) {
seen.cycle = _params.path;
}
return seen.schema;
}
// initialize
const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
this.seen.set(schema, result);
// custom method overrides default behavior
const overrideSchema = schema._zod.toJSONSchema?.();
if (overrideSchema) {
result.schema = overrideSchema;
}
else {
const params = {
..._params,
schemaPath: [..._params.schemaPath, schema],
path: _params.path,
};
const parent = schema._zod.parent;
if (parent) {
// schema was cloned from another schema
result.ref = parent;
this.process(parent, params);
this.seen.get(parent).isParent = true;
}
else {
const _json = result.schema;
switch (def.type) {
case "string": {
const json = _json;
json.type = "string";
const { minimum, maximum, format, patterns, contentEncoding } = schema._zod
.bag;
if (typeof minimum === "number")
json.minLength = minimum;
if (typeof maximum === "number")
json.maxLength = maximum;
// custom pattern overrides format
if (format) {
json.format = formatMap[format] ?? format;
if (json.format === "")
delete json.format; // empty format is not valid
}
if (contentEncoding)
json.contentEncoding = contentEncoding;
if (patterns && patterns.size > 0) {
const regexes = [...patterns];
if (regexes.length === 1)
json.pattern = regexes[0].source;
else if (regexes.length > 1) {
result.schema.allOf = [
...regexes.map((regex) => ({
...(this.target === "draft-7" ? { type: "string" } : {}),
pattern: regex.source,
})),
];
}
}
break;
}
case "number": {
const json = _json;
const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
if (typeof format === "string" && format.includes("int"))
json.type = "integer";
else
json.type = "number";
if (typeof exclusiveMinimum === "number")
json.exclusiveMinimum = exclusiveMinimum;
if (typeof minimum === "number") {
json.minimum = minimum;
if (typeof exclusiveMinimum === "number") {
if (exclusiveMinimum >= minimum)
delete json.minimum;
else
delete json.exclusiveMinimum;
}
}
if (typeof exclusiveMaximum === "number")
json.exclusiveMaximum = exclusiveMaximum;
if (typeof maximum === "number") {
json.maximum = maximum;
if (typeof exclusiveMaximum === "number") {
if (exclusiveMaximum <= maximum)
delete json.maximum;
else
delete json.exclusiveMaximum;
}
}
if (typeof multipleOf === "number")
json.multipleOf = multipleOf;
break;
}
case "boolean": {
const json = _json;
json.type = "boolean";
break;
}
case "bigint": {
if (this.unrepresentable === "throw") {
throw new Error("BigInt cannot be represented in JSON Schema");
}
break;
}
case "symbol": {
if (this.unrepresentable === "throw") {
throw new Error("Symbols cannot be represented in JSON Schema");
}
break;
}
case "null": {
_json.type = "null";
break;
}
case "any": {
break;
}
case "unknown": {
break;
}
case "undefined":
case "never": {
_json.not = {};
break;
}
case "void": {
if (this.unrepresentable === "throw") {
throw new Error("Void cannot be represented in JSON Schema");
}
break;
}
case "date": {
if (this.unrepresentable === "throw") {
throw new Error("Date cannot be represented in JSON Schema");
}
break;
}
case "array": {
const json = _json;
const { minimum, maximum } = schema._zod.bag;
if (typeof minimum === "number")
json.minItems = minimum;
if (typeof maximum === "number")
json.maxItems = maximum;
json.type = "array";
json.items = this.process(def.element, { ...params, path: [...params.path, "items"] });
break;
}
case "object": {
const json = _json;
json.type = "object";
json.properties = {};
const shape = def.shape; // params.shapeCache.get(schema)!;
for (const key in shape) {
json.properties[key] = this.process(shape[key], {
...params,
path: [...params.path, "properties", key],
});
}
// required keys
const allKeys = new Set(Object.keys(shape));
// const optionalKeys = new Set(def.optional);
const requiredKeys = new Set([...allKeys].filter((key) => {
const v = def.shape[key]._zod;
if (this.io === "input") {
return v.optin === undefined;
}
else {
return v.optout === undefined;
}
}));
if (requiredKeys.size > 0) {
json.required = Array.from(requiredKeys);
}
// catchall
if (def.catchall?._zod.def.type === "never") {
// strict
json.additionalProperties = false;
}
else if (!def.catchall) {
// regular
if (this.io === "output")
json.additionalProperties = false;
}
else if (def.catchall) {
json.additionalProperties = this.process(def.catchall, {
...params,
path: [...params.path, "additionalProperties"],
});
}
break;
}
case "union": {
const json = _json;
json.anyOf = def.options.map((x, i) => this.process(x, {
...params,
path: [...params.path, "anyOf", i],
}));
break;
}
case "intersection": {
const json = _json;
const a = this.process(def.left, {
...params,
path: [...params.path, "allOf", 0],
});
const b = this.process(def.right, {
...params,
path: [...params.path, "allOf", 1],
});
const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
const allOf = [
...(isSimpleIntersection(a) ? a.allOf : [a]),
...(isSimpleIntersection(b) ? b.allOf : [b]),
];
json.allOf = allOf;
break;
}
case "tuple": {
const json = _json;
json.type = "array";
const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] }));
if (this.target === "draft-2020-12") {
json.prefixItems = prefixItems;
}
else {
json.items = prefixItems;
}
if (def.rest) {
const rest = this.process(def.rest, {
...params,
path: [...params.path, "items"],
});
if (this.target === "draft-2020-12") {
json.items = rest;
}
else {
json.additionalItems = rest;
}
}
// additionalItems
if (def.rest) {
json.items = this.process(def.rest, {
...params,
path: [...params.path, "items"],
});
}
// length
const { minimum, maximum } = schema._zod.bag;
if (typeof minimum === "number")
json.minItems = minimum;
if (typeof maximum === "number")
json.maxItems = maximum;
break;
}
case "record": {
const json = _json;
json.type = "object";
json.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] });
json.additionalProperties = this.process(def.valueType, {
...params,
path: [...params.path, "additionalProperties"],
});
break;
}
case "map": {
if (this.unrepresentable === "throw") {
throw new Error("Map cannot be represented in JSON Schema");
}
break;
}
case "set": {
if (this.unrepresentable === "throw") {
throw new Error("Set cannot be represented in JSON Schema");
}
break;
}
case "enum": {
const json = _json;
const values = getEnumValues(def.entries);
// Number enums can have both string and number values
if (values.every((v) => typeof v === "number"))
json.type = "number";
if (values.every((v) => typeof v === "string"))
json.type = "string";
json.enum = values;
break;
}
case "literal": {
const json = _json;
const vals = [];
for (const val of def.values) {
if (val === undefined) {
if (this.unrepresentable === "throw") {
throw new Error("Literal `undefined` cannot be represented in JSON Schema");
}
else {
// do not add to vals
}
}
else if (typeof val === "bigint") {
if (this.unrepresentable === "throw") {
throw new Error("BigInt literals cannot be represented in JSON Schema");
}
else {
vals.push(Number(val));
}
}
else {
vals.push(val);
}
}
if (vals.length === 0) {
// do nothing (an undefined literal was stripped)
}
else if (vals.length === 1) {
const val = vals[0];
json.type = val === null ? "null" : typeof val;
json.const = val;
}
else {
if (vals.every((v) => typeof v === "number"))
json.type = "number";
if (vals.every((v) => typeof v === "string"))
json.type = "string";
if (vals.every((v) => typeof v === "boolean"))
json.type = "string";
if (vals.every((v) => v === null))
json.type = "null";
json.enum = vals;
}
break;
}
case "file": {
const json = _json;
const file = {
type: "string",
format: "binary",
contentEncoding: "binary",
};
const { minimum, maximum, mime } = schema._zod.bag;
if (minimum !== undefined)
file.minLength = minimum;
if (maximum !== undefined)
file.maxLength = maximum;
if (mime) {
if (mime.length === 1) {
file.contentMediaType = mime[0];
Object.assign(json, file);
}
else {
json.anyOf = mime.map((m) => {
const mFile = { ...file, contentMediaType: m };
return mFile;
});
}
}
else {
Object.assign(json, file);
}
// if (this.unrepresentable === "throw") {
// throw new Error("File cannot be represented in JSON Schema");
// }
break;
}
case "transform": {
if (this.unrepresentable === "throw") {
throw new Error("Transforms cannot be represented in JSON Schema");
}
break;
}
case "nullable": {
const inner = this.process(def.innerType, params);
_json.anyOf = [inner, { type: "null" }];
break;
}
case "nonoptional": {
this.process(def.innerType, params);
result.ref = def.innerType;
break;
}
case "success": {
const json = _json;
json.type = "boolean";
break;
}
case "default": {
this.process(def.innerType, params);
result.ref = def.innerType;
_json.default = JSON.parse(JSON.stringify(def.defaultValue));
break;
}
case "prefault": {
this.process(def.innerType, params);
result.ref = def.innerType;
if (this.io === "input")
_json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
break;
}
case "catch": {
// use conditionals
this.process(def.innerType, params);
result.ref = def.innerType;
let catchValue;
try {
catchValue = def.catchValue(undefined);
}
catch {
throw new Error("Dynamic catch values are not supported in JSON Schema");
}
_json.default = catchValue;
break;
}
case "nan": {
if (this.unrepresentable === "throw") {
throw new Error("NaN cannot be represented in JSON Schema");
}
break;
}
case "template_literal": {
const json = _json;
const pattern = schema._zod.pattern;
if (!pattern)
throw new Error("Pattern not found in template literal");
json.type = "string";
json.pattern = pattern.source;
break;
}
case "pipe": {
const innerType = this.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out;
this.process(innerType, params);
result.ref = innerType;
break;
}
case "readonly": {
this.process(def.innerType, params);
result.ref = def.innerType;
_json.readOnly = true;
break;
}
// passthrough types
case "promise": {
this.process(def.innerType, params);
result.ref = def.innerType;
break;
}
case "optional": {
this.process(def.innerType, params);
result.ref = def.innerType;
break;
}
case "lazy": {
const innerType = schema._zod.innerType;
this.process(innerType, params);
result.ref = innerType;
break;
}
case "custom": {
if (this.unrepresentable === "throw") {
throw new Error("Custom types cannot be represented in JSON Schema");
}
break;
}
default: {
def;
}
}
}
}
// metadata
const meta = this.metadataRegistry.get(schema);
if (meta)
Object.assign(result.schema, meta);
if (this.io === "input" && isTransforming(schema)) {
// examples/defaults only apply to output type of pipe
delete result.schema.examples;
delete result.schema.default;
}
// set prefault as default
if (this.io === "input" && result.schema._prefault)
(_a = result.schema).default ?? (_a.default = result.schema._prefault);
delete result.schema._prefault;
// pulling fresh from this.seen in case it was overwritten
const _result = this.seen.get(schema);
return _result.schema;
}
emit(schema, _params) {
const params = {
cycles: _params?.cycles ?? "ref",
reused: _params?.reused ?? "inline",
// unrepresentable: _params?.unrepresentable ?? "throw",
// uri: _params?.uri ?? ((id) => `${id}`),
external: _params?.external ?? undefined,
};
// iterate over seen map;
const root = this.seen.get(schema);
if (!root)
throw new Error("Unprocessed schema. This is a bug in Zod.");
// initialize result with root schema fields
// Object.assign(result, seen.cached);
const makeURI = (entry) => {
// comparing the seen objects because sometimes
// multiple schemas map to the same seen object.
// e.g. lazy
// external is configured
const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";
if (params.external) {
const externalId = params.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${this.counter++}`;
// check if schema is in the external registry
if (externalId)
return { ref: params.external.uri(externalId) };
// otherwise, add to __shared
const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;
entry[1].defId = id;
return { defId: id, ref: `${params.external.uri("__shared")}#/${defsSegment}/${id}` };
}
if (entry[1] === root) {
return { ref: "#" };
}
// self-contained schema
const uriPrefix = `#`;
const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
const defId = entry[1].schema.id ?? `__schema${this.counter++}`;
return { defId, ref: defUriPrefix + defId };
};
// stored cached version in `def` property
// remove all properties, set $ref
const extractToDef = (entry) => {
if (entry[1].schema.$ref) {
return;
}
const seen = entry[1];
const { ref, defId } = makeURI(entry);
seen.def = { ...seen.schema };
// defId won't be set if the schema is a reference to an external schema
if (defId)
seen.defId = defId;
// wipe away all properties except $ref
const schema = seen.schema;
for (const key in schema) {
delete schema[key];
}
schema.$ref = ref;
};
// extract schemas into $defs
for (const entry of this.seen.entries()) {
const seen = entry[1];
// convert root schema to # $ref
// also prevents root schema from being extracted
if (schema === entry[0]) {
// do not copy to defs...this is the root schema
extractToDef(entry);
continue;
}
// extract schemas that are in the external registry
if (params.external) {
const ext = params.external.registry.get(entry[0])?.id;
if (schema !== entry[0] && ext) {
extractToDef(entry);
continue;
}
}
// extract schemas with `id` meta
const id = this.metadataRegistry.get(entry[0])?.id;
if (id) {
extractToDef(entry);
continue;
}
// break cycles
if (seen.cycle) {
if (params.cycles === "throw") {
throw new Error("Cycle detected: " +
`#/${seen.cycle?.join("/")}/<root>` +
'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
}
else if (params.cycles === "ref") {
extractToDef(entry);
}
continue;
}
// extract reused schemas
if (seen.count > 1) {
if (params.reused === "ref") {
extractToDef(entry);
// biome-ignore lint:
continue;
}
}
}
// flatten _refs
const flattenRef = (zodSchema, params) => {
const seen = this.seen.get(zodSchema);
const schema = seen.def ?? seen.schema;
const _cached = { ...schema };
// already seen
if (seen.ref === null) {
return;
}
// flatten ref if defined
const ref = seen.ref;
seen.ref = null; // prevent recursion
if (ref) {
flattenRef(ref, params);
// merge referenced schema into current
const refSchema = this.seen.get(ref).schema;
if (refSchema.$ref && params.target === "draft-7") {
schema.allOf = schema.allOf ?? [];
schema.allOf.push(refSchema);
}
else {
Object.assign(schema, refSchema);
Object.assign(schema, _cached); // prevent overwriting any fields in the original schema
}
}
// execute overrides
if (!seen.isParent)
this.override({
zodSchema: zodSchema,
jsonSchema: schema,
path: seen.path ?? [],
});
};
for (const entry of [...this.seen.entries()].reverse()) {
flattenRef(entry[0], { target: this.target });
}
const result = {};
if (this.target === "draft-2020-12") {
result.$schema = "https://json-schema.org/draft/2020-12/schema";
}
else if (this.target === "draft-7") {
result.$schema = "http://json-schema.org/draft-07/schema#";
}
else {
console.warn(`Invalid target: ${this.target}`);
}
Object.assign(result, root.def);
// build defs object
const defs = params.external?.defs ?? {};
for (const entry of this.seen.entries()) {
const seen = entry[1];
if (seen.def && seen.defId) {
defs[seen.defId] = seen.def;
}
}
// set definitions in result
if (!params.external && Object.keys(defs).length > 0) {
if (this.target === "draft-2020-12") {
result.$defs = defs;
}
else {
result.definitions = defs;
}
}
try {
// this "finalizes" this schema and ensures all cycles are removed
// each call to .emit() is functionally independent
// though the seen map is shared
return JSON.parse(JSON.stringify(result));
}
catch (_err) {
throw new Error("Error converting schema to JSON.");
}
}
}
export function toJSONSchema(input, _params) {
if (input instanceof $ZodRegistry) {
const gen = new JSONSchemaGenerator(_params);
const defs = {};
for (const entry of input._idmap.entries()) {
const [_, schema] = entry;
gen.process(schema);
}
const schemas = {};
const external = {
registry: input,
uri: _params?.uri || ((id) => id),
defs,
};
for (const entry of input._idmap.entries()) {
const [key, schema] = entry;
schemas[key] = gen.emit(schema, {
..._params,
external,
});
}
if (Object.keys(defs).length > 0) {
const defsSegment = gen.target === "draft-2020-12" ? "$defs" : "definitions";
schemas.__shared = {
[defsSegment]: defs,
};
}
return { schemas };
}
const gen = new JSONSchemaGenerator(_params);
gen.process(input);
return gen.emit(input, _params);
}
function isTransforming(_schema, _ctx) {
const ctx = _ctx ?? { seen: new Set() };
if (ctx.seen.has(_schema))
return false;
ctx.seen.add(_schema);
const schema = _schema;
const def = schema._zod.def;
switch (def.type) {
case "string":
case "number":
case "bigint":
case "boolean":
case "date":
case "symbol":
case "undefined":
case "null":
case "any":
case "unknown":
case "never":
case "void":
case "literal":
case "enum":
case "nan":
case "file":
case "template_literal":
return false;
case "array": {
return isTransforming(def.element, ctx);
}
case "object": {
for (const key in def.shape) {
if (isTransforming(def.shape[key], ctx))
return true;
}
return false;
}
case "union": {
for (const option of def.options) {
if (isTransforming(option, ctx))
return true;
}
return false;
}
case "intersection": {
return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
}
case "tuple": {
for (const item of def.items) {
if (isTransforming(item, ctx))
return true;
}
if (def.rest && isTransforming(def.rest, ctx))
return true;
return false;
}
case "record": {
return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
}
case "map": {
return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
}
case "set": {
return isTransforming(def.valueType, ctx);
}
// inner types
case "promise":
case "optional":
case "nonoptional":
case "nullable":
case "readonly":
return isTransforming(def.innerType, ctx);
case "lazy":
return isTransforming(def.getter(), ctx);
case "default": {
return isTransforming(def.innerType, ctx);
}
case "prefault": {
return isTransforming(def.innerType, ctx);
}
case "custom": {
return false;
}
case "transform": {
return true;
}
case "pipe": {
return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
}
case "success": {
return false;
}
case "catch": {
return false;
}
default:
def;
}
throw new Error(`Unknown schema type: ${def.type}`);
}

493
extracted-source/node_modules/zod/v4/core/util.js generated vendored Normal file
View File

@@ -0,0 +1,493 @@
// functions
export function assertEqual(val) {
return val;
}
export function assertNotEqual(val) {
return val;
}
export function assertIs(_arg) { }
export function assertNever(_x) {
throw new Error();
}
export function assert(_) { }
export function getEnumValues(entries) {
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
const values = Object.entries(entries)
.filter(([k, _]) => numericValues.indexOf(+k) === -1)
.map(([_, v]) => v);
return values;
}
export function joinValues(array, separator = "|") {
return array.map((val) => stringifyPrimitive(val)).join(separator);
}
export function jsonStringifyReplacer(_, value) {
if (typeof value === "bigint")
return value.toString();
return value;
}
export function cached(getter) {
const set = false;
return {
get value() {
if (!set) {
const value = getter();
Object.defineProperty(this, "value", { value });
return value;
}
throw new Error("cached value already set");
},
};
}
export function nullish(input) {
return input === null || input === undefined;
}
export function cleanRegex(source) {
const start = source.startsWith("^") ? 1 : 0;
const end = source.endsWith("$") ? source.length - 1 : source.length;
return source.slice(start, end);
}
export function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
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;
}
export function defineLazy(object, key, getter) {
const set = false;
Object.defineProperty(object, key, {
get() {
if (!set) {
const value = getter();
object[key] = value;
return value;
}
throw new Error("cached value already set");
},
set(v) {
Object.defineProperty(object, key, {
value: v,
// configurable: true,
});
// object[key] = v;
},
configurable: true,
});
}
export function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
writable: true,
enumerable: true,
configurable: true,
});
}
export function getElementAtPath(obj, path) {
if (!path)
return obj;
return path.reduce((acc, key) => acc?.[key], obj);
}
export function promiseAllObject(promisesObj) {
const keys = Object.keys(promisesObj);
const promises = keys.map((key) => promisesObj[key]);
return Promise.all(promises).then((results) => {
const resolvedObj = {};
for (let i = 0; i < keys.length; i++) {
resolvedObj[keys[i]] = results[i];
}
return resolvedObj;
});
}
export function randomString(length = 10) {
const chars = "abcdefghijklmnopqrstuvwxyz";
let str = "";
for (let i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
export function esc(str) {
return JSON.stringify(str);
}
export const captureStackTrace = Error.captureStackTrace
? Error.captureStackTrace
: (..._args) => { };
export function isObject(data) {
return typeof data === "object" && data !== null && !Array.isArray(data);
}
export const allowsEval = cached(() => {
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
return false;
}
try {
const F = Function;
new F("");
return true;
}
catch (_) {
return false;
}
});
export function isPlainObject(o) {
if (isObject(o) === false)
return false;
// modified constructor
const ctor = o.constructor;
if (ctor === undefined)
return true;
// modified prototype
const prot = ctor.prototype;
if (isObject(prot) === false)
return false;
// ctor doesn't have static `isPrototypeOf`
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
return false;
}
return true;
}
export function numKeys(data) {
let keyCount = 0;
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
keyCount++;
}
}
return keyCount;
}
export const getParsedType = (data) => {
const t = typeof data;
switch (t) {
case "undefined":
return "undefined";
case "string":
return "string";
case "number":
return Number.isNaN(data) ? "nan" : "number";
case "boolean":
return "boolean";
case "function":
return "function";
case "bigint":
return "bigint";
case "symbol":
return "symbol";
case "object":
if (Array.isArray(data)) {
return "array";
}
if (data === null) {
return "null";
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return "promise";
}
if (typeof Map !== "undefined" && data instanceof Map) {
return "map";
}
if (typeof Set !== "undefined" && data instanceof Set) {
return "set";
}
if (typeof Date !== "undefined" && data instanceof Date) {
return "date";
}
if (typeof File !== "undefined" && data instanceof File) {
return "file";
}
return "object";
default:
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 function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// zod-specific utils
export function clone(inst, def, params) {
const cl = new inst._zod.constr(def ?? inst._zod.def);
if (!def || params?.parent)
cl._zod.parent = inst;
return cl;
}
export function normalizeParams(_params) {
const params = _params;
if (!params)
return {};
if (typeof params === "string")
return { error: () => params };
if (params?.message !== undefined) {
if (params?.error !== undefined)
throw new Error("Cannot specify both `message` and `error` params");
params.error = params.message;
}
delete params.message;
if (typeof params.error === "string")
return { ...params, error: () => params.error };
return params;
}
export function createTransparentProxy(getter) {
let target;
return new Proxy({}, {
get(_, prop, receiver) {
target ?? (target = getter());
return Reflect.get(target, prop, receiver);
},
set(_, prop, value, receiver) {
target ?? (target = getter());
return Reflect.set(target, prop, value, receiver);
},
has(_, prop) {
target ?? (target = getter());
return Reflect.has(target, prop);
},
deleteProperty(_, prop) {
target ?? (target = getter());
return Reflect.deleteProperty(target, prop);
},
ownKeys(_) {
target ?? (target = getter());
return Reflect.ownKeys(target);
},
getOwnPropertyDescriptor(_, prop) {
target ?? (target = getter());
return Reflect.getOwnPropertyDescriptor(target, prop);
},
defineProperty(_, prop, descriptor) {
target ?? (target = getter());
return Reflect.defineProperty(target, prop, descriptor);
},
});
}
export function stringifyPrimitive(value) {
if (typeof value === "bigint")
return value.toString() + "n";
if (typeof value === "string")
return `"${value}"`;
return `${value}`;
}
export function optionalKeys(shape) {
return Object.keys(shape).filter((k) => {
return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
});
}
export const NUMBER_FORMAT_RANGES = {
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
int32: [-2147483648, 2147483647],
uint32: [0, 4294967295],
float32: [-3.4028234663852886e38, 3.4028234663852886e38],
float64: [-Number.MAX_VALUE, Number.MAX_VALUE],
};
export const BIGINT_FORMAT_RANGES = {
int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")],
uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")],
};
export function pick(schema, mask) {
const newShape = {};
const currDef = schema._zod.def; //.shape;
for (const key in mask) {
if (!(key in currDef.shape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!mask[key])
continue;
// pick key
newShape[key] = currDef.shape[key];
}
return clone(schema, {
...schema._zod.def,
shape: newShape,
checks: [],
});
}
export function omit(schema, mask) {
const newShape = { ...schema._zod.def.shape };
const currDef = schema._zod.def; //.shape;
for (const key in mask) {
if (!(key in currDef.shape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!mask[key])
continue;
delete newShape[key];
}
return clone(schema, {
...schema._zod.def,
shape: newShape,
checks: [],
});
}
export function extend(schema, shape) {
if (!isPlainObject(shape)) {
throw new Error("Invalid input to extend: expected a plain object");
}
const def = {
...schema._zod.def,
get shape() {
const _shape = { ...schema._zod.def.shape, ...shape };
assignProp(this, "shape", _shape); // self-caching
return _shape;
},
checks: [], // delete existing checks
};
return clone(schema, def);
}
export function merge(a, b) {
return clone(a, {
...a._zod.def,
get shape() {
const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
assignProp(this, "shape", _shape); // self-caching
return _shape;
},
catchall: b._zod.def.catchall,
checks: [], // delete existing checks
});
}
export function partial(Class, schema, mask) {
const oldShape = schema._zod.def.shape;
const shape = { ...oldShape };
if (mask) {
for (const key in mask) {
if (!(key in oldShape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!mask[key])
continue;
// if (oldShape[key]!._zod.optin === "optional") continue;
shape[key] = Class
? new Class({
type: "optional",
innerType: oldShape[key],
})
: oldShape[key];
}
}
else {
for (const key in oldShape) {
// if (oldShape[key]!._zod.optin === "optional") continue;
shape[key] = Class
? new Class({
type: "optional",
innerType: oldShape[key],
})
: oldShape[key];
}
}
return clone(schema, {
...schema._zod.def,
shape,
checks: [],
});
}
export function required(Class, schema, mask) {
const oldShape = schema._zod.def.shape;
const shape = { ...oldShape };
if (mask) {
for (const key in mask) {
if (!(key in shape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!mask[key])
continue;
// overwrite with non-optional
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key],
});
}
}
else {
for (const key in oldShape) {
// overwrite with non-optional
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key],
});
}
}
return clone(schema, {
...schema._zod.def,
shape,
// optional: [],
checks: [],
});
}
export function aborted(x, startIndex = 0) {
for (let i = startIndex; i < x.issues.length; i++) {
if (x.issues[i]?.continue !== true)
return true;
}
return false;
}
export function prefixIssues(path, issues) {
return issues.map((iss) => {
var _a;
(_a = iss).path ?? (_a.path = []);
iss.path.unshift(path);
return iss;
});
}
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)) ??
unwrapMessage(ctx?.error?.(iss)) ??
unwrapMessage(config.customError?.(iss)) ??
unwrapMessage(config.localeError?.(iss)) ??
"Invalid input";
full.message = message;
}
// delete (full as any).def;
delete full.inst;
delete full.continue;
if (!ctx?.reportInput) {
delete full.input;
}
return full;
}
export function getSizableOrigin(input) {
if (input instanceof Set)
return "set";
if (input instanceof Map)
return "map";
if (input instanceof File)
return "file";
return "unknown";
}
export function getLengthableOrigin(input) {
if (Array.isArray(input))
return "array";
if (typeof input === "string")
return "string";
return "unknown";
}
export function issue(...args) {
const [iss, input, inst] = args;
if (typeof iss === "string") {
return {
message: iss,
code: "custom",
input,
inst,
};
}
return { ...iss };
}
export function cleanEnum(obj) {
return Object.entries(obj)
.filter(([k, _]) => {
// return true if NaN, meaning it's not a number, thus a string key
return Number.isNaN(Number.parseInt(k, 10));
})
.map((el) => el[1]);
}
// instanceof
export class Class {
constructor(..._args) { }
}

View File

@@ -0,0 +1,5 @@
export const version = {
major: 4,
minor: 0,
patch: 0,
};