mcp-proxy
Version:
A TypeScript SSE proxy for MCP servers that use stdio transport.
1,537 lines (1,525 loc) • 870 kB
JavaScript
import { createRequire } from "node:module";
import { randomUUID } from "node:crypto";
import { URL as URL$1 } from "node:url";
import http from "http";
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (var keys = __getOwnPropNames(from), i$3 = 0, n = keys.length, key$1; i$3 < n; i$3++) {
key$1 = keys[i$3];
if (!__hasOwnProp.call(to, key$1) && key$1 !== except) {
__defProp(to, key$1, {
get: ((k) => from[k]).bind(null, key$1),
enumerable: !(desc = __getOwnPropDesc(from, key$1)) || desc.enumerable
});
}
}
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
var __require = /* @__PURE__ */ createRequire(import.meta.url);
//#endregion
//#region src/authentication.ts
var AuthenticationMiddleware = class {
constructor(config$1 = {}) {
this.config = config$1;
}
getScopeChallengeResponse(requiredScopes, errorDescription, requestId) {
const headers = { "Content-Type": "application/json" };
if (this.config.oauth?.protectedResource?.resource) {
const parts = [
"Bearer",
"error=\"insufficient_scope\"",
`scope="${requiredScopes.join(" ")}"`,
`resource_metadata="${this.config.oauth.protectedResource.resource}/.well-known/oauth-protected-resource"`
];
if (errorDescription) {
const escaped = errorDescription.replace(/"/g, "\\\"");
parts.push(`error_description="${escaped}"`);
}
headers["WWW-Authenticate"] = parts.join(", ");
}
return {
body: JSON.stringify({
error: {
code: -32001,
data: {
error: "insufficient_scope",
required_scopes: requiredScopes
},
message: errorDescription || "Insufficient scope"
},
id: requestId ?? null,
jsonrpc: "2.0"
}),
headers,
statusCode: 403
};
}
getUnauthorizedResponse(options) {
const headers = { "Content-Type": "application/json" };
if (this.config.oauth) {
const params = [];
if (this.config.oauth.realm) params.push(`realm="${this.config.oauth.realm}"`);
if (this.config.oauth.protectedResource?.resource) params.push(`resource_metadata="${this.config.oauth.protectedResource.resource}/.well-known/oauth-protected-resource"`);
const error$1 = options?.error || this.config.oauth.error || "invalid_token";
params.push(`error="${error$1}"`);
const escaped = (options?.error_description || this.config.oauth.error_description || "Unauthorized: Invalid or missing API key").replace(/"/g, "\\\"");
params.push(`error_description="${escaped}"`);
const error_uri = options?.error_uri || this.config.oauth.error_uri;
if (error_uri) params.push(`error_uri="${error_uri}"`);
const scope = options?.scope || this.config.oauth.scope;
if (scope) params.push(`scope="${scope}"`);
if (params.length > 0) headers["WWW-Authenticate"] = `Bearer ${params.join(", ")}`;
}
return {
body: JSON.stringify({
error: {
code: 401,
message: options?.error_description || "Unauthorized: Invalid or missing API key"
},
id: null,
jsonrpc: "2.0"
}),
headers
};
}
validateRequest(req) {
if (!this.config.apiKey) return true;
const apiKey = req.headers["x-api-key"];
if (!apiKey || typeof apiKey !== "string") return false;
return apiKey === this.config.apiKey;
}
};
//#endregion
//#region src/InMemoryEventStore.ts
/**
* Simple in-memory implementation of the EventStore interface for resumability
* This is primarily intended for examples and testing, not for production use
* where a persistent storage solution would be more appropriate.
*/
var InMemoryEventStore = class {
events = /* @__PURE__ */ new Map();
lastTimestamp = 0;
lastTimestampCounter = 0;
/**
* Replays events that occurred after a specific event ID
* Implements EventStore.replayEventsAfter
*/
async replayEventsAfter(lastEventId, { send }) {
if (!lastEventId || !this.events.has(lastEventId)) return "";
const streamId = this.getStreamIdFromEventId(lastEventId);
if (!streamId) return "";
let foundLastEvent = false;
const sortedEvents = [...this.events.entries()].sort((a, b) => a[0].localeCompare(b[0]));
for (const [eventId, { message, streamId: eventStreamId }] of sortedEvents) {
if (eventStreamId !== streamId) continue;
if (eventId === lastEventId) {
foundLastEvent = true;
continue;
}
if (foundLastEvent) await send(eventId, message);
}
return streamId;
}
/**
* Stores an event with a generated event ID
* Implements EventStore.storeEvent
*/
async storeEvent(streamId, message) {
const eventId = this.generateEventId(streamId);
this.events.set(eventId, {
message,
streamId
});
return eventId;
}
/**
* Generates a monotonic unique event ID in
* `${streamId}_${timestamp}_${counter}_${random}` format.
*/
generateEventId(streamId) {
const now = Date.now();
if (now === this.lastTimestamp) this.lastTimestampCounter++;
else {
this.lastTimestampCounter = 0;
this.lastTimestamp = now;
}
return `${streamId}_${now.toString()}_${this.lastTimestampCounter.toString(36).padStart(4, "0")}_${Math.random().toString(36).substring(2, 5)}`;
}
/**
* Extracts the stream ID from an event ID
*/
getStreamIdFromEventId(eventId) {
const parts = eventId.split("_");
return parts.length > 0 ? parts[0] : "";
}
};
//#endregion
//#region node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/core.js
/** A special constant with type `never` */
const NEVER = Object.freeze({ status: "aborted" });
function $constructor(name, initializer$2, params) {
function init(inst, def$30) {
var _a;
Object.defineProperty(inst, "_zod", {
value: inst._zod ?? {},
enumerable: false
});
(_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set());
inst._zod.traits.add(name);
initializer$2(inst, def$30);
for (const k in _$1.prototype) if (!(k in inst)) Object.defineProperty(inst, k, { value: _$1.prototype[k].bind(inst) });
inst._zod.constr = _$1;
inst._zod.def = def$30;
}
const Parent = params?.Parent ?? Object;
class Definition extends Parent {}
Object.defineProperty(Definition, "name", { value: name });
function _$1(def$30) {
var _a;
const inst = params?.Parent ? new Definition() : this;
init(inst, def$30);
(_a = inst._zod).deferred ?? (_a.deferred = []);
for (const fn of inst._zod.deferred) fn();
return inst;
}
Object.defineProperty(_$1, "init", { value: init });
Object.defineProperty(_$1, Symbol.hasInstance, { value: (inst) => {
if (params?.Parent && inst instanceof params.Parent) return true;
return inst?._zod?.traits?.has(name);
} });
Object.defineProperty(_$1, "name", { value: name });
return _$1;
}
var $ZodAsyncError = class extends Error {
constructor() {
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
}
};
const globalConfig = {};
function config(newConfig) {
if (newConfig) Object.assign(globalConfig, newConfig);
return globalConfig;
}
//#endregion
//#region node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/util.js
function getEnumValues(entries) {
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
return Object.entries(entries).filter(([k, _$1]) => numericValues.indexOf(+k) === -1).map(([_$1, v]) => v);
}
function jsonStringifyReplacer(_$1, value) {
if (typeof value === "bigint") return value.toString();
return value;
}
function cached(getter) {
return { get value() {
{
const value = getter();
Object.defineProperty(this, "value", { value });
return value;
}
throw new Error("cached value already set");
} };
}
function nullish(input) {
return input === null || input === void 0;
}
function cleanRegex(source) {
const start = source.startsWith("^") ? 1 : 0;
const end = source.endsWith("$") ? source.length - 1 : source.length;
return source.slice(start, end);
}
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
}
function defineLazy(object$1, key$1, getter) {
Object.defineProperty(object$1, key$1, {
get() {
{
const value = getter();
object$1[key$1] = value;
return value;
}
throw new Error("cached value already set");
},
set(v) {
Object.defineProperty(object$1, key$1, { value: v });
},
configurable: true
});
}
function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
writable: true,
enumerable: true,
configurable: true
});
}
function esc(str$1) {
return JSON.stringify(str$1);
}
const captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {};
function isObject(data) {
return typeof data === "object" && data !== null && !Array.isArray(data);
}
const allowsEval = cached(() => {
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
try {
new Function("");
return true;
} catch (_$1) {
return false;
}
});
function isPlainObject$1(o) {
if (isObject(o) === false) return false;
const ctor = o.constructor;
if (ctor === void 0) return true;
const prot = ctor.prototype;
if (isObject(prot) === false) return false;
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
return true;
}
const propertyKeyTypes = new Set([
"string",
"number",
"symbol"
]);
function escapeRegex(str$1) {
return str$1.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone(inst, def$30, params) {
const cl = new inst._zod.constr(def$30 ?? inst._zod.def);
if (!def$30 || params?.parent) cl._zod.parent = inst;
return cl;
}
function normalizeParams(_params) {
const params = _params;
if (!params) return {};
if (typeof params === "string") return { error: () => params };
if (params?.message !== void 0) {
if (params?.error !== void 0) 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;
}
function optionalKeys(shape) {
return Object.keys(shape).filter((k) => {
return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
});
}
const NUMBER_FORMAT_RANGES = {
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
int32: [-2147483648, 2147483647],
uint32: [0, 4294967295],
float32: [-34028234663852886e22, 34028234663852886e22],
float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
};
function pick(schema, mask) {
const newShape = {};
const currDef = schema._zod.def;
for (const key$1 in mask) {
if (!(key$1 in currDef.shape)) throw new Error(`Unrecognized key: "${key$1}"`);
if (!mask[key$1]) continue;
newShape[key$1] = currDef.shape[key$1];
}
return clone(schema, {
...schema._zod.def,
shape: newShape,
checks: []
});
}
function omit(schema, mask) {
const newShape = { ...schema._zod.def.shape };
const currDef = schema._zod.def;
for (const key$1 in mask) {
if (!(key$1 in currDef.shape)) throw new Error(`Unrecognized key: "${key$1}"`);
if (!mask[key$1]) continue;
delete newShape[key$1];
}
return clone(schema, {
...schema._zod.def,
shape: newShape,
checks: []
});
}
function extend(schema, shape) {
if (!isPlainObject$1(shape)) throw new Error("Invalid input to extend: expected a plain object");
return clone(schema, {
...schema._zod.def,
get shape() {
const _shape = {
...schema._zod.def.shape,
...shape
};
assignProp(this, "shape", _shape);
return _shape;
},
checks: []
});
}
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);
return _shape;
},
catchall: b._zod.def.catchall,
checks: []
});
}
function partial(Class, schema, mask) {
const oldShape = schema._zod.def.shape;
const shape = { ...oldShape };
if (mask) for (const key$1 in mask) {
if (!(key$1 in oldShape)) throw new Error(`Unrecognized key: "${key$1}"`);
if (!mask[key$1]) continue;
shape[key$1] = Class ? new Class({
type: "optional",
innerType: oldShape[key$1]
}) : oldShape[key$1];
}
else for (const key$1 in oldShape) shape[key$1] = Class ? new Class({
type: "optional",
innerType: oldShape[key$1]
}) : oldShape[key$1];
return clone(schema, {
...schema._zod.def,
shape,
checks: []
});
}
function required(Class, schema, mask) {
const oldShape = schema._zod.def.shape;
const shape = { ...oldShape };
if (mask) for (const key$1 in mask) {
if (!(key$1 in shape)) throw new Error(`Unrecognized key: "${key$1}"`);
if (!mask[key$1]) continue;
shape[key$1] = new Class({
type: "nonoptional",
innerType: oldShape[key$1]
});
}
else for (const key$1 in oldShape) shape[key$1] = new Class({
type: "nonoptional",
innerType: oldShape[key$1]
});
return clone(schema, {
...schema._zod.def,
shape,
checks: []
});
}
function aborted(x, startIndex = 0) {
for (let i$3 = startIndex; i$3 < x.issues.length; i$3++) if (x.issues[i$3]?.continue !== true) return true;
return false;
}
function prefixIssues(path, issues) {
return issues.map((iss) => {
var _a;
(_a = iss).path ?? (_a.path = []);
iss.path.unshift(path);
return iss;
});
}
function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config$1) {
const full = {
...iss,
path: iss.path ?? []
};
if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config$1.customError?.(iss)) ?? unwrapMessage(config$1.localeError?.(iss)) ?? "Invalid input";
delete full.inst;
delete full.continue;
if (!ctx?.reportInput) delete full.input;
return full;
}
function getLengthableOrigin(input) {
if (Array.isArray(input)) return "array";
if (typeof input === "string") return "string";
return "unknown";
}
function issue(...args) {
const [iss, input, inst] = args;
if (typeof iss === "string") return {
message: iss,
code: "custom",
input,
inst
};
return { ...iss };
}
//#endregion
//#region node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/errors.js
const initializer$1 = (inst, def$30) => {
inst.name = "$ZodError";
Object.defineProperty(inst, "_zod", {
value: inst._zod,
enumerable: false
});
Object.defineProperty(inst, "issues", {
value: def$30,
enumerable: false
});
Object.defineProperty(inst, "message", {
get() {
return JSON.stringify(def$30, jsonStringifyReplacer, 2);
},
enumerable: true
});
Object.defineProperty(inst, "toString", {
value: () => inst.message,
enumerable: false
});
};
const $ZodError = $constructor("$ZodError", initializer$1);
const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
function flattenError(error$1, mapper = (issue$1) => issue$1.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of error$1.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
};
}
function formatError(error$1, _mapper) {
const mapper = _mapper || function(issue$1) {
return issue$1.message;
};
const fieldErrors = { _errors: [] };
const processError = (error$2) => {
for (const issue$1 of error$2.issues) if (issue$1.code === "invalid_union" && issue$1.errors.length) issue$1.errors.map((issues) => processError({ issues }));
else if (issue$1.code === "invalid_key") processError({ issues: issue$1.issues });
else if (issue$1.code === "invalid_element") processError({ issues: issue$1.issues });
else if (issue$1.path.length === 0) fieldErrors._errors.push(mapper(issue$1));
else {
let curr = fieldErrors;
let i$3 = 0;
while (i$3 < issue$1.path.length) {
const el = issue$1.path[i$3];
if (!(i$3 === issue$1.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue$1));
}
curr = curr[el];
i$3++;
}
}
};
processError(error$1);
return fieldErrors;
}
//#endregion
//#region node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js
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 $ZodAsyncError();
if (result.issues.length) {
const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
captureStackTrace(e, _params?.callee);
throw e;
}
return result.value;
};
const parse$4 = /* @__PURE__ */ _parse($ZodRealError);
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) => finalizeIssue(iss, ctx, config())));
captureStackTrace(e, params?.callee);
throw e;
}
return result.value;
};
const parseAsync$1 = /* @__PURE__ */ _parseAsync($ZodRealError);
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 $ZodAsyncError();
return result.issues.length ? {
success: false,
error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
} : {
success: true,
data: result.value
};
};
const safeParse$2 = /* @__PURE__ */ _safeParse($ZodRealError);
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) => finalizeIssue(iss, ctx, config())))
} : {
success: true,
data: result.value
};
};
const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
//#endregion
//#region node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/regexes.js
const cuid = /^[cC][^\s-]{8,}$/;
const cuid2 = /^[0-9a-z]+$/;
const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
const xid = /^[0-9a-vA-V]{20}$/;
const ksuid = /^[A-Za-z0-9]{27}$/;
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. */
const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
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. */
const uuid = (version$1) => {
if (!version$1) 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 /* @__PURE__ */ new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version$1}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
/** Practical email validation */
const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
return new RegExp(_emoji$1, "u");
}
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])$/;
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})$/;
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])$/;
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])$/;
const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
const base64url = /^[A-Za-z0-9_-]*$/;
const hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
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 date$2 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
function timeSource(args) {
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
return 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+)?)?`;
}
function time$1(args) {
return /* @__PURE__ */ new RegExp(`^${timeSource(args)}$`);
}
function datetime$1(args) {
const time$2 = timeSource({ precision: args.precision });
const opts = ["Z"];
if (args.local) opts.push("");
if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`);
const timeRegex = `${time$2}(?:${opts.join("|")})`;
return /* @__PURE__ */ new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
const string$1 = (params) => {
const regex$1 = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
return /* @__PURE__ */ new RegExp(`^${regex$1}$`);
};
const integer = /^\d+$/;
const number$1 = /^-?\d+(?:\.\d+)?/i;
const boolean$1 = /true|false/i;
const _null$2 = /null/i;
const lowercase = /^[^A-Z]*$/;
const uppercase = /^[^a-z]*$/;
//#endregion
//#region node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/checks.js
const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def$30) => {
var _a;
inst._zod ?? (inst._zod = {});
inst._zod.def = def$30;
(_a = inst._zod).onattach ?? (_a.onattach = []);
});
const numericOriginMap = {
number: "number",
bigint: "bigint",
object: "date"
};
const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def$30) => {
$ZodCheck.init(inst, def$30);
const origin = numericOriginMap[typeof def$30.value];
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
const curr = (def$30.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
if (def$30.value < curr) if (def$30.inclusive) bag.maximum = def$30.value;
else bag.exclusiveMaximum = def$30.value;
});
inst._zod.check = (payload) => {
if (def$30.inclusive ? payload.value <= def$30.value : payload.value < def$30.value) return;
payload.issues.push({
origin,
code: "too_big",
maximum: def$30.value,
input: payload.value,
inclusive: def$30.inclusive,
inst,
continue: !def$30.abort
});
};
});
const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def$30) => {
$ZodCheck.init(inst, def$30);
const origin = numericOriginMap[typeof def$30.value];
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
const curr = (def$30.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
if (def$30.value > curr) if (def$30.inclusive) bag.minimum = def$30.value;
else bag.exclusiveMinimum = def$30.value;
});
inst._zod.check = (payload) => {
if (def$30.inclusive ? payload.value >= def$30.value : payload.value > def$30.value) return;
payload.issues.push({
origin,
code: "too_small",
minimum: def$30.value,
input: payload.value,
inclusive: def$30.inclusive,
inst,
continue: !def$30.abort
});
};
});
const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def$30) => {
$ZodCheck.init(inst, def$30);
inst._zod.onattach.push((inst$1) => {
var _a;
(_a = inst$1._zod.bag).multipleOf ?? (_a.multipleOf = def$30.value);
});
inst._zod.check = (payload) => {
if (typeof payload.value !== typeof def$30.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
if (typeof payload.value === "bigint" ? payload.value % def$30.value === BigInt(0) : floatSafeRemainder(payload.value, def$30.value) === 0) return;
payload.issues.push({
origin: typeof payload.value,
code: "not_multiple_of",
divisor: def$30.value,
input: payload.value,
inst,
continue: !def$30.abort
});
};
});
const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def$30) => {
$ZodCheck.init(inst, def$30);
def$30.format = def$30.format || "float64";
const isInt = def$30.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = NUMBER_FORMAT_RANGES[def$30.format];
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.format = def$30.format;
bag.minimum = minimum;
bag.maximum = maximum;
if (isInt) bag.pattern = integer;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
if (!Number.isInteger(input)) {
payload.issues.push({
expected: origin,
format: def$30.format,
code: "invalid_type",
input,
inst
});
return;
}
if (!Number.isSafeInteger(input)) {
if (input > 0) 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$30.abort
});
else 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$30.abort
});
return;
}
}
if (input < minimum) payload.issues.push({
origin: "number",
input,
code: "too_small",
minimum,
inclusive: true,
inst,
continue: !def$30.abort
});
if (input > maximum) payload.issues.push({
origin: "number",
input,
code: "too_big",
maximum,
inst
});
};
});
const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def$30) => {
var _a;
$ZodCheck.init(inst, def$30);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
inst._zod.onattach.push((inst$1) => {
const curr = inst$1._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
if (def$30.maximum < curr) inst$1._zod.bag.maximum = def$30.maximum;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (input.length <= def$30.maximum) return;
const origin = getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_big",
maximum: def$30.maximum,
inclusive: true,
input,
inst,
continue: !def$30.abort
});
};
});
const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def$30) => {
var _a;
$ZodCheck.init(inst, def$30);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
inst._zod.onattach.push((inst$1) => {
const curr = inst$1._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
if (def$30.minimum > curr) inst$1._zod.bag.minimum = def$30.minimum;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (input.length >= def$30.minimum) return;
const origin = getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_small",
minimum: def$30.minimum,
inclusive: true,
input,
inst,
continue: !def$30.abort
});
};
});
const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def$30) => {
var _a;
$ZodCheck.init(inst, def$30);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.minimum = def$30.length;
bag.maximum = def$30.length;
bag.length = def$30.length;
});
inst._zod.check = (payload) => {
const input = payload.value;
const length = input.length;
if (length === def$30.length) return;
const origin = getLengthableOrigin(input);
const tooBig = length > def$30.length;
payload.issues.push({
origin,
...tooBig ? {
code: "too_big",
maximum: def$30.length
} : {
code: "too_small",
minimum: def$30.length
},
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def$30.abort
});
};
});
const $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def$30) => {
var _a, _b;
$ZodCheck.init(inst, def$30);
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.format = def$30.format;
if (def$30.pattern) {
bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
bag.patterns.add(def$30.pattern);
}
});
if (def$30.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => {
def$30.pattern.lastIndex = 0;
if (def$30.pattern.test(payload.value)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: def$30.format,
input: payload.value,
...def$30.pattern ? { pattern: def$30.pattern.toString() } : {},
inst,
continue: !def$30.abort
});
});
else (_b = inst._zod).check ?? (_b.check = () => {});
});
const $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def$30) => {
$ZodCheckStringFormat.init(inst, def$30);
inst._zod.check = (payload) => {
def$30.pattern.lastIndex = 0;
if (def$30.pattern.test(payload.value)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "regex",
input: payload.value,
pattern: def$30.pattern.toString(),
inst,
continue: !def$30.abort
});
};
});
const $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = lowercase);
$ZodCheckStringFormat.init(inst, def$30);
});
const $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = uppercase);
$ZodCheckStringFormat.init(inst, def$30);
});
const $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def$30) => {
$ZodCheck.init(inst, def$30);
const escapedRegex = escapeRegex(def$30.includes);
const pattern = new RegExp(typeof def$30.position === "number" ? `^.{${def$30.position}}${escapedRegex}` : escapedRegex);
def$30.pattern = pattern;
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.includes(def$30.includes, def$30.position)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "includes",
includes: def$30.includes,
input: payload.value,
inst,
continue: !def$30.abort
});
};
});
const $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def$30) => {
$ZodCheck.init(inst, def$30);
const pattern = /* @__PURE__ */ new RegExp(`^${escapeRegex(def$30.prefix)}.*`);
def$30.pattern ?? (def$30.pattern = pattern);
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.startsWith(def$30.prefix)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "starts_with",
prefix: def$30.prefix,
input: payload.value,
inst,
continue: !def$30.abort
});
};
});
const $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def$30) => {
$ZodCheck.init(inst, def$30);
const pattern = /* @__PURE__ */ new RegExp(`.*${escapeRegex(def$30.suffix)}$`);
def$30.pattern ?? (def$30.pattern = pattern);
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
bag.patterns.add(pattern);
});
inst._zod.check = (payload) => {
if (payload.value.endsWith(def$30.suffix)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "ends_with",
suffix: def$30.suffix,
input: payload.value,
inst,
continue: !def$30.abort
});
};
});
const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def$30) => {
$ZodCheck.init(inst, def$30);
inst._zod.check = (payload) => {
payload.value = def$30.tx(payload.value);
};
});
//#endregion
//#region node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/doc.js
var Doc = class {
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 lines = arg.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$1 of dedented) this.content.push(line$1);
}
compile() {
const F = Function;
const args = this?.args;
const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)];
return new F(...args, lines.join("\n"));
}
};
//#endregion
//#region node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/versions.js
const version = {
major: 4,
minor: 0,
patch: 0
};
//#endregion
//#region node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/schemas.js
const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def$30) => {
var _a;
inst ?? (inst = {});
inst._zod.def = def$30;
inst._zod.bag = inst._zod.bag || {};
inst._zod.version = version;
const checks = [...inst._zod.def.checks ?? []];
if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst);
for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
if (checks.length === 0) {
(_a = inst._zod).deferred ?? (_a.deferred = []);
inst._zod.deferred?.push(() => {
inst._zod.run = inst._zod.parse;
});
} else {
const runChecks = (payload, checks$1, ctx) => {
let isAborted = aborted(payload);
let asyncResult;
for (const ch of checks$1) {
if (ch._zod.def.when) {
if (!ch._zod.def.when(payload)) continue;
} else if (isAborted) continue;
const currLen = payload.issues.length;
const _$1 = ch._zod.check(payload);
if (_$1 instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
if (asyncResult || _$1 instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
await _$1;
if (payload.issues.length === currLen) return;
if (!isAborted) isAborted = aborted(payload, currLen);
});
else {
if (payload.issues.length === currLen) continue;
if (!isAborted) isAborted = aborted(payload, currLen);
}
}
if (asyncResult) return asyncResult.then(() => {
return payload;
});
return payload;
};
inst._zod.run = (payload, ctx) => {
const result = inst._zod.parse(payload, ctx);
if (result instanceof Promise) {
if (ctx.async === false) throw new $ZodAsyncError();
return result.then((result$1) => runChecks(result$1, checks, ctx));
}
return runChecks(result, checks, ctx);
};
}
inst["~standard"] = {
validate: (value) => {
try {
const r = safeParse$2(inst, value);
return r.success ? { value: r.data } : { issues: r.error?.issues };
} catch (_$1) {
return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
}
},
vendor: "zod",
version: 1
};
});
const $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def$30) => {
$ZodType.init(inst, def$30);
inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
inst._zod.parse = (payload, _$1) => {
if (def$30.coerce) try {
payload.value = String(payload.value);
} catch (_$2) {}
if (typeof payload.value === "string") return payload;
payload.issues.push({
expected: "string",
code: "invalid_type",
input: payload.value,
inst
});
return payload;
};
});
const $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def$30) => {
$ZodCheckStringFormat.init(inst, def$30);
$ZodString.init(inst, def$30);
});
const $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = guid);
$ZodStringFormat.init(inst, def$30);
});
const $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def$30) => {
if (def$30.version) {
const v = {
v1: 1,
v2: 2,
v3: 3,
v4: 4,
v5: 5,
v6: 6,
v7: 7,
v8: 8
}[def$30.version];
if (v === void 0) throw new Error(`Invalid UUID version: "${def$30.version}"`);
def$30.pattern ?? (def$30.pattern = uuid(v));
} else def$30.pattern ?? (def$30.pattern = uuid());
$ZodStringFormat.init(inst, def$30);
});
const $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = email);
$ZodStringFormat.init(inst, def$30);
});
const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def$30) => {
$ZodStringFormat.init(inst, def$30);
inst._zod.check = (payload) => {
try {
const orig = payload.value;
const url$1 = new URL(orig);
const href = url$1.href;
if (def$30.hostname) {
def$30.hostname.lastIndex = 0;
if (!def$30.hostname.test(url$1.hostname)) payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid hostname",
pattern: hostname.source,
input: payload.value,
inst,
continue: !def$30.abort
});
}
if (def$30.protocol) {
def$30.protocol.lastIndex = 0;
if (!def$30.protocol.test(url$1.protocol.endsWith(":") ? url$1.protocol.slice(0, -1) : url$1.protocol)) payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid protocol",
pattern: def$30.protocol.source,
input: payload.value,
inst,
continue: !def$30.abort
});
}
if (!orig.endsWith("/") && href.endsWith("/")) payload.value = href.slice(0, -1);
else payload.value = href;
return;
} catch (_$1) {
payload.issues.push({
code: "invalid_format",
format: "url",
input: payload.value,
inst,
continue: !def$30.abort
});
}
};
});
const $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = emoji());
$ZodStringFormat.init(inst, def$30);
});
const $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = nanoid);
$ZodStringFormat.init(inst, def$30);
});
const $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = cuid);
$ZodStringFormat.init(inst, def$30);
});
const $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = cuid2);
$ZodStringFormat.init(inst, def$30);
});
const $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = ulid);
$ZodStringFormat.init(inst, def$30);
});
const $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = xid);
$ZodStringFormat.init(inst, def$30);
});
const $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = ksuid);
$ZodStringFormat.init(inst, def$30);
});
const $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = datetime$1(def$30));
$ZodStringFormat.init(inst, def$30);
});
const $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = date$2);
$ZodStringFormat.init(inst, def$30);
});
const $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = time$1(def$30));
$ZodStringFormat.init(inst, def$30);
});
const $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = duration$1);
$ZodStringFormat.init(inst, def$30);
});
const $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = ipv4);
$ZodStringFormat.init(inst, def$30);
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.format = `ipv4`;
});
});
const $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = ipv6);
$ZodStringFormat.init(inst, def$30);
inst._zod.onattach.push((inst$1) => {
const bag = inst$1._zod.bag;
bag.format = `ipv6`;
});
inst._zod.check = (payload) => {
try {
new URL(`http://[${payload.value}]`);
} catch {
payload.issues.push({
code: "invalid_format",
format: "ipv6",
input: payload.value,
inst,
continue: !def$30.abort
});
}
};
});
const $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = cidrv4);
$ZodStringFormat.init(inst, def$30);
});
const $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = cidrv6);
$ZodStringFormat.init(inst, def$30);
inst._zod.check = (payload) => {
const [address, prefix] = payload.value.split("/");
try {
if (!prefix) throw new Error();
const prefixNum = Number(prefix);
if (`${prefixNum}` !== prefix) throw new Error();
if (prefixNum < 0 || prefixNum > 128) throw new Error();
new URL(`http://[${address}]`);
} catch {
payload.issues.push({
code: "invalid_format",
format: "cidrv6",
input: payload.value,
inst,
continue: !def$30.abort
});
}
};
});
function isValidBase64(data) {
if (data === "") return true;
if (data.length % 4 !== 0) return false;
try {
atob(data);
return true;
} catch {
return false;
}
}
const $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = base64);
$ZodStringFormat.init(inst, def$30);
inst._zod.onattach.push((inst$1) => {
inst$1._zod.bag.contentEncoding = "base64";
});
inst._zod.check = (payload) => {
if (isValidBase64(payload.value)) return;
payload.issues.push({
code: "invalid_format",
format: "base64",
input: payload.value,
inst,
continue: !def$30.abort
});
};
});
function isValidBase64URL(data) {
if (!base64url.test(data)) return false;
const base64$1 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
return isValidBase64(base64$1.padEnd(Math.ceil(base64$1.length / 4) * 4, "="));
}
const $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = base64url);
$ZodStringFormat.init(inst, def$30);
inst._zod.onattach.push((inst$1) => {
inst$1._zod.bag.contentEncoding = "base64url";
});
inst._zod.check = (payload) => {
if (isValidBase64URL(payload.value)) return;
payload.issues.push({
code: "invalid_format",
format: "base64url",
input: payload.value,
inst,
continue: !def$30.abort
});
};
});
const $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def$30) => {
def$30.pattern ?? (def$30.pattern = e164);
$ZodStringFormat.init(inst, def$30);
});
function isValidJWT(token, algorithm = null) {
try {
const tokensParts = token.split(".");
if (tokensParts.length !== 3) return false;
const [header] = tokensParts;
if (!header) return false;
const parsedHeader = JSON.parse(atob(header));
if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false;
if (!parsedHeader.alg) return false;
if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
return true;
} catch {
return false;
}
}
const $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def$30) => {
$ZodStringFormat.init(inst, def$30);
inst._zod.check = (payload) => {
if (isValidJWT(payload.value, def$30.alg)) return;
payload.issues.push({
code: "invalid_format",
format: "jwt",
input: payload.value,
inst,
continue: !def$30.abort
});
};
});
const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def$30) => {
$ZodType.init(inst, def$30);
inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
inst._zod.parse = (payload, _ctx) => {
if (def$30.coerce) try {
payload.value = Number(payload.value);
} catch (_$1) {}
const input = payload.value;
if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
payload.issues.push({
expected: "number",
code: "invalid_type",
input,
inst,
...received ? { received } : {}
});
return payload;
};
});
const $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def$30) => {
$ZodCheckNumberFormat.init(inst, def$30);
$ZodNumber.init(inst, def$30);
});
const $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def$30) => {
$ZodType.init(inst, def$30);
inst._zod.pattern = boolean$1;
inst._zod.parse = (payload, _ctx) => {
if (def$30.coerce) try {
payload.value = Boolean(payload.value);
} catch (_$1) {}
const input = payload.value;
if (typeof input === "boolean") return payload;
payload.issues.push({
expected: "boolean",
code: "invalid_type",
input,
inst
});
return payload;
};
});
const $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def$30) => {
$ZodType.init(inst, def$30);
inst._zod.pattern = _null$2;
inst._zod.values = new Set([null]);
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (input === null) return payload;
payload.issues.push({
expected: "null",
code: "invalid_type",
input,
inst
});
return payload;
};
});
const $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def$30) => {
$ZodType.init(inst, def$30);
inst._zod.parse = (payload) => payload;
});
const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def$30) => {
$ZodType.init(inst, def$30);
inst._zod.parse = (payload) => payload;
});
const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def$30) => {
$ZodType.init(inst, def$30);
inst._zod.parse = (payload, _ctx) => {
payload.issues.push({
expected: "never",
code: "invalid_type",
input: payload.value,
inst
});
return payload;
};
});
function handleArrayResult(result, final, index) {
if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
final.value[index] = result.value;
}
const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def$30) => {
$ZodType.init(inst, def$30);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!Array.isArray(input)) {
payload.issues.push({
expected: "array",
code: "invalid_type",
input,
inst
});
return payload;
}
payload.value = Array(input.length);
const proms = [];
for (let i$3 = 0; i$3 < input.length; i$3++) {
const item = input[i$3];
const result = def$30.element._zod.run({
value: item,
issues: []
}, ctx);
if (result instanceof Promise) proms.push(result.then((result$1) => handleArrayResult(result$1, payload, i$3)));
else handleArrayResult(result, payload, i$3);
}
if (proms.length) return Promise.all(proms).then(() => payload);
return payload;
};
});
function handleObjectResult(result, final, key$1) {
if (result.issues.length) final.issues.push(...prefixIssues(key$1, result.issues));
final.value[key$1] = result.value;
}
function handleOptionalObjectResult(result, final, key$1, input) {
if (result.issues.length) if (input[key$1] === void 0) if (key$1 in input) final.value[key$1] = void 0;
else final.value[key$1] = result.value;
else final.issues.push(...prefixIssues(key$1, result.issues));
else if (result.value === void 0) {
if (key$1 in input) final.value[key$1] = void 0;
} else final.value[key$1] = result.value;
}
const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def$30) => {
$ZodType.init(inst, def$30);
const _normalized = cached(() => {
const keys = Object.keys(def$30.shape);
for (const k of keys) if (!(def$30.shape[k] instanceof $ZodType)) throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
const okeys = optionalKeys(def$30.s