Files
QR-master/.output/server/_libs/@ai-sdk/gateway+[...].mjs
2026-07-15 18:08:51 +02:00

12938 lines
396 KiB
JavaScript

import { fileURLToPath as __eveFileURLToPath } from "node:url";
import { dirname as __eveDirname } from "node:path";
__eveDirname(__eveFileURLToPath(import.meta.url));
import { i as __toESM, r as __require, t as __commonJSMin } from "../../_runtime.mjs";
//#region node_modules/@ai-sdk/provider/dist/index.js
var marker$1 = "vercel.ai.error";
var symbol$2 = Symbol.for(marker$1);
var _a$2;
var _b$2;
var AISDKError = class _AISDKError extends (_b$2 = Error, _a$2 = symbol$2, _b$2) {
/**
* Creates an AI SDK Error.
*
* @param {Object} params - The parameters for creating the error.
* @param {string} params.name - The name of the error.
* @param {string} params.message - The error message.
* @param {unknown} [params.cause] - The underlying cause of the error.
*/
constructor({ name: name15, message, cause }) {
super(message);
this[_a$2] = true;
this.name = name15;
this.cause = cause;
}
/**
* Checks if the given error is an AI SDK Error.
* @param {unknown} error - The error to check.
* @returns {boolean} True if the error is an AI SDK Error, false otherwise.
*/
static isInstance(error) {
return _AISDKError.hasMarker(error, marker$1);
}
static hasMarker(error, marker16) {
const markerSymbol = Symbol.for(marker16);
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
}
};
var name$2 = "AI_APICallError";
var marker2$1 = `vercel.ai.error.${name$2}`;
var symbol2$1 = Symbol.for(marker2$1);
var _a2$1;
var _b2$1;
var APICallError = class extends (_b2$1 = AISDKError, _a2$1 = symbol2$1, _b2$1) {
constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {
super({
name: name$2,
message,
cause
});
this[_a2$1] = true;
this.url = url;
this.requestBodyValues = requestBodyValues;
this.statusCode = statusCode;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
this.isRetryable = isRetryable;
this.data = data;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker2$1);
}
};
var name2$1 = "AI_EmptyResponseBodyError";
var marker3$1 = `vercel.ai.error.${name2$1}`;
var symbol3$1 = Symbol.for(marker3$1);
var _a3$1;
var _b3$1;
var EmptyResponseBodyError = class extends (_b3$1 = AISDKError, _a3$1 = symbol3$1, _b3$1) {
constructor({ message = "Empty response body" } = {}) {
super({
name: name2$1,
message
});
this[_a3$1] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker3$1);
}
};
function getErrorMessage(error) {
if (error == null) return "unknown error";
if (typeof error === "string") return error;
if (error instanceof Error) return error.toString();
return JSON.stringify(error);
}
var name3$1 = "AI_InvalidArgumentError";
var marker4$1 = `vercel.ai.error.${name3$1}`;
var symbol4$1 = Symbol.for(marker4$1);
var _a4$1;
var _b4$1;
var InvalidArgumentError = class extends (_b4$1 = AISDKError, _a4$1 = symbol4$1, _b4$1) {
constructor({ message, cause, argument }) {
super({
name: name3$1,
message,
cause
});
this[_a4$1] = true;
this.argument = argument;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker4$1);
}
};
var name4$1 = "AI_InvalidPromptError";
var marker5$1 = `vercel.ai.error.${name4$1}`;
var symbol5$1 = Symbol.for(marker5$1);
var _a5$1;
var _b5$1;
var InvalidPromptError = class extends (_b5$1 = AISDKError, _a5$1 = symbol5$1, _b5$1) {
constructor({ prompt, message, cause }) {
super({
name: name4$1,
message: `Invalid prompt: ${message}`,
cause
});
this[_a5$1] = true;
this.prompt = prompt;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker5$1);
}
};
var name5$1 = "AI_InvalidResponseDataError";
var marker6$1 = `vercel.ai.error.${name5$1}`;
var symbol6$1 = Symbol.for(marker6$1);
var _a6$1;
var _b6$1;
(class extends (_b6$1 = AISDKError, _a6$1 = symbol6$1, _b6$1) {
constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {
super({
name: name5$1,
message
});
this[_a6$1] = true;
this.data = data;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker6$1);
}
});
var name6$1 = "AI_JSONParseError";
var marker7$1 = `vercel.ai.error.${name6$1}`;
var symbol7$1 = Symbol.for(marker7$1);
var _a7$1;
var _b7$1;
var JSONParseError = class extends (_b7$1 = AISDKError, _a7$1 = symbol7$1, _b7$1) {
constructor({ text, cause }) {
super({
name: name6$1,
message: `JSON parsing failed: Text: ${text}.
Error message: ${getErrorMessage(cause)}`,
cause
});
this[_a7$1] = true;
this.text = text;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker7$1);
}
};
var name7$1 = "AI_LoadAPIKeyError";
var marker8$1 = `vercel.ai.error.${name7$1}`;
var symbol8$1 = Symbol.for(marker8$1);
var _a8$1;
var _b8$1;
(class extends (_b8$1 = AISDKError, _a8$1 = symbol8$1, _b8$1) {
constructor({ message }) {
super({
name: name7$1,
message
});
this[_a8$1] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker8$1);
}
});
var name8$1 = "AI_LoadSettingError";
var marker9$1 = `vercel.ai.error.${name8$1}`;
var symbol9$1 = Symbol.for(marker9$1);
var _a9$1;
var _b9$1;
(class extends (_b9$1 = AISDKError, _a9$1 = symbol9$1, _b9$1) {
constructor({ message }) {
super({
name: name8$1,
message
});
this[_a9$1] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker9$1);
}
});
var name9$1 = "AI_NoContentGeneratedError";
var marker10$1 = `vercel.ai.error.${name9$1}`;
var symbol10$1 = Symbol.for(marker10$1);
var _a10$1;
var _b10$1;
(class extends (_b10$1 = AISDKError, _a10$1 = symbol10$1, _b10$1) {
constructor({ message = "No content generated." } = {}) {
super({
name: name9$1,
message
});
this[_a10$1] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker10$1);
}
});
var name10 = "AI_NoSuchModelError";
var marker11 = `vercel.ai.error.${name10}`;
var symbol11 = Symbol.for(marker11);
var _a11;
var _b11;
(class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {
constructor({ errorName = name10, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {
super({
name: errorName,
message
});
this[_a11] = true;
this.modelId = modelId;
this.modelType = modelType;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker11);
}
});
var name11 = "AI_NoSuchProviderReferenceError";
var marker12 = `vercel.ai.error.${name11}`;
var symbol12 = Symbol.for(marker12);
var _a12;
var _b12;
(class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {
constructor({ provider, reference, message = `No provider reference found for provider '${provider}'. Available providers: ${Object.keys(reference).join(", ")}` }) {
super({
name: name11,
message
});
this[_a12] = true;
this.provider = provider;
this.reference = reference;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker12);
}
});
var name12 = "AI_TooManyEmbeddingValuesForCallError";
var marker13 = `vercel.ai.error.${name12}`;
var symbol13 = Symbol.for(marker13);
var _a13;
var _b13;
(class extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
constructor(options) {
super({
name: name12,
message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
});
this[_a13] = true;
this.provider = options.provider;
this.modelId = options.modelId;
this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
this.values = options.values;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker13);
}
});
var name13 = "AI_TypeValidationError";
var marker14 = `vercel.ai.error.${name13}`;
var symbol14 = Symbol.for(marker14);
var _a14;
var _b14;
var TypeValidationError = class _TypeValidationError extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
constructor({ value, cause, context }) {
let contextPrefix = "Type validation failed";
if (context == null ? void 0 : context.field) contextPrefix += ` for ${context.field}`;
if ((context == null ? void 0 : context.entityName) || (context == null ? void 0 : context.entityId)) {
contextPrefix += " (";
const parts = [];
if (context.entityName) parts.push(context.entityName);
if (context.entityId) parts.push(`id: "${context.entityId}"`);
contextPrefix += parts.join(", ");
contextPrefix += ")";
}
super({
name: name13,
message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
Error message: ${getErrorMessage(cause)}`,
cause
});
this[_a14] = true;
this.value = value;
this.context = context;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker14);
}
/**
* Wraps an error into a TypeValidationError.
* If the cause is already a TypeValidationError with the same value and context, it returns the cause.
* Otherwise, it creates a new TypeValidationError.
*
* @param {Object} params - The parameters for wrapping the error.
* @param {unknown} params.value - The value that failed validation.
* @param {unknown} params.cause - The original error or cause of the validation failure.
* @param {TypeValidationContext} params.context - Optional context about what is being validated.
* @returns {TypeValidationError} A TypeValidationError instance.
*/
static wrap({ value, cause, context }) {
var _a16, _b16, _c;
if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a16 = cause.context) == null ? void 0 : _a16.field) === (context == null ? void 0 : context.field) && ((_b16 = cause.context) == null ? void 0 : _b16.entityName) === (context == null ? void 0 : context.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context == null ? void 0 : context.entityId)) return cause;
return new _TypeValidationError({
value,
cause,
context
});
}
};
var name14 = "AI_UnsupportedFunctionalityError";
var marker15 = `vercel.ai.error.${name14}`;
var symbol15 = Symbol.for(marker15);
var _a15;
var _b15;
var UnsupportedFunctionalityError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {
constructor({ functionality, message = `'${functionality}' functionality not supported.` }) {
super({
name: name14,
message
});
this[_a15] = true;
this.functionality = functionality;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker15);
}
};
Object.freeze({ status: "aborted" });
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 = /* @__PURE__ */ new Set());
inst._zod.traits.add(name);
initializer(inst, def);
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;
}
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 _;
}
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/zod/v4/core/util.js
function getEnumValues(entries) {
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
}
function jsonStringifyReplacer(_, 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;
}
} };
}
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$1(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, key, getter) {
Object.defineProperty(object, key, {
get() {
{
const value = getter();
object[key] = value;
return value;
}
},
set(v) {
Object.defineProperty(object, key, { value: v });
},
configurable: true
});
}
function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
writable: true,
enumerable: true,
configurable: true
});
}
function esc(str) {
return JSON.stringify(str);
}
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 (_) {
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 = /* @__PURE__ */ new Set([
"string",
"number",
"symbol"
]);
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
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;
}
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 in mask) {
if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
newShape[key] = currDef.shape[key];
}
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 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: []
});
}
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 in mask) {
if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
shape[key] = Class ? new Class({
type: "optional",
innerType: oldShape[key]
}) : oldShape[key];
}
else for (const key in oldShape) shape[key] = Class ? new Class({
type: "optional",
innerType: oldShape[key]
}) : oldShape[key];
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 in mask) {
if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
if (!mask[key]) continue;
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key]
});
}
else for (const key in oldShape) shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key]
});
return clone(schema, {
...schema._zod.def,
shape,
checks: []
});
}
function aborted(x, startIndex = 0) {
for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.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) {
const full = {
...iss,
path: iss.path ?? []
};
if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.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/zod/v4/core/errors.js
const initializer$1 = (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, 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, 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
};
}
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];
if (!(i === issue.path.length - 1)) 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;
}
//#endregion
//#region node_modules/zod/v4/core/parse.js
const _parse$1 = (_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 _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 _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$1 = /* @__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/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) => {
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})$`);
};
/** 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$1 = /*@__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 new RegExp(`^${timeSource(args)}$`);
}
function datetime$1(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})$`);
}
const string$1 = (params) => {
const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
return new RegExp(`^${regex}$`);
};
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/zod/v4/core/checks.js
const $ZodCheck = /*@__PURE__*/ $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"
};
const $ZodCheckLessThan = /*@__PURE__*/ $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
});
};
});
const $ZodCheckGreaterThan = /*@__PURE__*/ $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
});
};
});
const $ZodCheckMultipleOf = /*@__PURE__*/ $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.");
if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder$1(payload.value, def.value) === 0) return;
payload.issues.push({
origin: typeof payload.value,
code: "not_multiple_of",
divisor: def.value,
input: payload.value,
inst,
continue: !def.abort
});
};
});
const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => {
$ZodCheck.init(inst, def);
def.format = def.format || "float64";
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = 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 = integer;
});
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
if (!Number.isInteger(input)) {
payload.issues.push({
expected: origin,
format: def.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.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.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
});
};
});
const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
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;
if (input.length <= def.maximum) return;
const origin = getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort
});
};
});
const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
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;
if (input.length >= def.minimum) return;
const origin = getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort
});
};
});
const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
});
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 = 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
});
};
});
const $ZodCheckStringFormat = /*@__PURE__*/ $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 = /* @__PURE__ */ 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 = () => {});
});
const $ZodCheckRegex = /*@__PURE__*/ $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
});
};
});
const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => {
def.pattern ?? (def.pattern = lowercase);
$ZodCheckStringFormat.init(inst, def);
});
const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => {
def.pattern ?? (def.pattern = uppercase);
$ZodCheckStringFormat.init(inst, def);
});
const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => {
$ZodCheck.init(inst, def);
const escapedRegex = 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 = /* @__PURE__ */ 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
});
};
});
const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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
});
};
});
const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.patterns ?? (bag.patterns = /* @__PURE__ */ 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
});
};
});
const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
payload.value = def.tx(payload.value);
};
});
//#endregion
//#region 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 of dedented) this.content.push(line);
}
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/zod/v4/core/versions.js
const version = {
major: 4,
minor: 0,
patch: 0
};
//#endregion
//#region node_modules/zod/v4/core/schemas.js
const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
var _a;
inst ?? (inst = {});
inst._zod.def = def;
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, ctx) => {
let isAborted = aborted(payload);
let asyncResult;
for (const ch of checks) {
if (ch._zod.def.when) {
if (!ch._zod.def.when(payload)) continue;
} else if (isAborted) continue;
const currLen = payload.issues.length;
const _ = ch._zod.check(payload);
if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
await _;
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) => runChecks(result, checks, ctx));
}
return runChecks(result, checks, ctx);
};
}
inst["~standard"] = {
validate: (value) => {
try {
const r = safeParse$1(inst, value);
return r.success ? { value: r.data } : { issues: r.error?.issues };
} catch (_) {
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) => {
$ZodType.init(inst, def);
inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
inst._zod.parse = (payload, _) => {
if (def.coerce) try {
payload.value = String(payload.value);
} catch (_) {}
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) => {
$ZodCheckStringFormat.init(inst, def);
$ZodString.init(inst, def);
});
const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => {
def.pattern ?? (def.pattern = guid);
$ZodStringFormat.init(inst, def);
});
const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
if (def.version) {
const v = {
v1: 1,
v2: 2,
v3: 3,
v4: 4,
v5: 5,
v6: 6,
v7: 7,
v8: 8
}[def.version];
if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
def.pattern ?? (def.pattern = uuid(v));
} else def.pattern ?? (def.pattern = uuid());
$ZodStringFormat.init(inst, def);
});
const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => {
def.pattern ?? (def.pattern = email);
$ZodStringFormat.init(inst, def);
});
const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
try {
const orig = payload.value;
const url = new URL(orig);
const href = url.href;
if (def.hostname) {
def.hostname.lastIndex = 0;
if (!def.hostname.test(url.hostname)) payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid hostname",
pattern: hostname.source,
input: payload.value,
inst,
continue: !def.abort
});
}
if (def.protocol) {
def.protocol.lastIndex = 0;
if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid protocol",
pattern: def.protocol.source,
input: payload.value,
inst,
continue: !def.abort
});
}
if (!orig.endsWith("/") && href.endsWith("/")) payload.value = href.slice(0, -1);
else payload.value = href;
return;
} catch (_) {
payload.issues.push({
code: "invalid_format",
format: "url",
input: payload.value,
inst,
continue: !def.abort
});
}
};
});
const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => {
def.pattern ?? (def.pattern = emoji());
$ZodStringFormat.init(inst, def);
});
const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => {
def.pattern ?? (def.pattern = nanoid);
$ZodStringFormat.init(inst, def);
});
const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => {
def.pattern ?? (def.pattern = cuid);
$ZodStringFormat.init(inst, def);
});
const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => {
def.pattern ?? (def.pattern = cuid2);
$ZodStringFormat.init(inst, def);
});
const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => {
def.pattern ?? (def.pattern = ulid);
$ZodStringFormat.init(inst, def);
});
const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => {
def.pattern ?? (def.pattern = xid);
$ZodStringFormat.init(inst, def);
});
const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => {
def.pattern ?? (def.pattern = ksuid);
$ZodStringFormat.init(inst, def);
});
const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => {
def.pattern ?? (def.pattern = datetime$1(def));
$ZodStringFormat.init(inst, def);
});
const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => {
def.pattern ?? (def.pattern = date$1);
$ZodStringFormat.init(inst, def);
});
const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => {
def.pattern ?? (def.pattern = time$1(def));
$ZodStringFormat.init(inst, def);
});
const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => {
def.pattern ?? (def.pattern = duration$1);
$ZodStringFormat.init(inst, def);
});
const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => {
def.pattern ?? (def.pattern = ipv4);
$ZodStringFormat.init(inst, def);
inst._zod.onattach.push((inst) => {
const bag = inst._zod.bag;
bag.format = `ipv4`;
});
});
const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => {
def.pattern ?? (def.pattern = ipv6);
$ZodStringFormat.init(inst, def);
inst._zod.onattach.push((inst) => {
const bag = inst._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.abort
});
}
};
});
const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => {
def.pattern ?? (def.pattern = cidrv4);
$ZodStringFormat.init(inst, def);
});
const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => {
def.pattern ?? (def.pattern = cidrv6);
$ZodStringFormat.init(inst, def);
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.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) => {
def.pattern ?? (def.pattern = base64);
$ZodStringFormat.init(inst, def);
inst._zod.onattach.push((inst) => {
inst._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.abort
});
};
});
function isValidBase64URL(data) {
if (!base64url.test(data)) return false;
const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
}
const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => {
def.pattern ?? (def.pattern = base64url);
$ZodStringFormat.init(inst, def);
inst._zod.onattach.push((inst) => {
inst._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.abort
});
};
});
const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => {
def.pattern ?? (def.pattern = e164);
$ZodStringFormat.init(inst, def);
});
function isValidJWT$1(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) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
if (isValidJWT$1(payload.value, def.alg)) return;
payload.issues.push({
code: "invalid_format",
format: "jwt",
input: payload.value,
inst,
continue: !def.abort
});
};
});
const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce) try {
payload.value = Number(payload.value);
} catch (_) {}
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) => {
$ZodCheckNumberFormat.init(inst, def);
$ZodNumber.init(inst, def);
});
const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = boolean$1;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce) try {
payload.value = Boolean(payload.value);
} catch (_) {}
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) => {
$ZodType.init(inst, def);
inst._zod.pattern = _null$2;
inst._zod.values = /* @__PURE__ */ 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) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload) => payload;
});
const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload) => payload;
});
const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => {
$ZodType.init(inst, def);
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) => {
$ZodType.init(inst, def);
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 = 0; i < input.length; i++) {
const item = input[i];
const result = def.element._zod.run({
value: item,
issues: []
}, ctx);
if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));
else handleArrayResult(result, payload, i);
}
if (proms.length) return Promise.all(proms).then(() => payload);
return payload;
};
});
function handleObjectResult(result, final, key) {
if (result.issues.length) final.issues.push(...prefixIssues(key, result.issues));
final.value[key] = result.value;
}
function handleOptionalObjectResult(result, final, key, input) {
if (result.issues.length) if (input[key] === void 0) if (key in input) final.value[key] = void 0;
else final.value[key] = result.value;
else final.issues.push(...prefixIssues(key, result.issues));
else if (result.value === void 0) {
if (key in input) final.value[key] = void 0;
} else final.value[key] = result.value;
}
const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
$ZodType.init(inst, def);
const _normalized = cached(() => {
const keys = Object.keys(def.shape);
for (const k of keys) if (!(def.shape[k] instanceof $ZodType)) throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
const okeys = optionalKeys(def.shape);
return {
shape: def.shape,
keys,
keySet: new Set(keys),
numKeys: keys.length,
optionalKeys: new Set(okeys)
};
});
defineLazy(inst._zod, "propValues", () => {
const shape = def.shape;
const propValues = {};
for (const key in shape) {
const field = shape[key]._zod;
if (field.values) {
propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
for (const v of field.values) propValues[key].add(v);
}
}
return propValues;
});
const generateFastpass = (shape) => {
const doc = new Doc([
"shape",
"payload",
"ctx"
]);
const normalized = _normalized.value;
const parseStr = (key) => {
const k = esc(key);
return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
};
doc.write(`const input = payload.value;`);
const ids = Object.create(null);
let counter = 0;
for (const key of normalized.keys) ids[key] = `key_${counter++}`;
doc.write(`const newResult = {}`);
for (const key of normalized.keys) if (normalized.optionalKeys.has(key)) {
const id = ids[key];
doc.write(`const ${id} = ${parseStr(key)};`);
const k = esc(key);
doc.write(`
if (${id}.issues.length) {
if (input[${k}] === undefined) {
if (${k} in input) {
newResult[${k}] = undefined;
}
} else {
payload.issues = payload.issues.concat(
${id}.issues.map((iss) => ({
...iss,
path: iss.path ? [${k}, ...iss.path] : [${k}],
}))
);
}
} else if (${id}.value === undefined) {
if (${k} in input) newResult[${k}] = undefined;
} else {
newResult[${k}] = ${id}.value;
}
`);
} else {
const id = ids[key];
doc.write(`const ${id} = ${parseStr(key)};`);
doc.write(`
if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
...iss,
path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
})));`);
doc.write(`newResult[${esc(key)}] = ${id}.value`);
}
doc.write(`payload.value = newResult;`);
doc.write(`return payload;`);
const fn = doc.compile();
return (payload, ctx) => fn(shape, payload, ctx);
};
let fastpass;
const isObject$1 = isObject;
const jit = !globalConfig.jitless;
const fastEnabled = jit && allowsEval.value;
const catchall = def.catchall;
let value;
inst._zod.parse = (payload, ctx) => {
value ?? (value = _normalized.value);
const input = payload.value;
if (!isObject$1(input)) {
payload.issues.push({
expected: "object",
code: "invalid_type",
input,
inst
});
return payload;
}
const proms = [];
if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
if (!fastpass) fastpass = generateFastpass(def.shape);
payload = fastpass(payload, ctx);
} else {
payload.value = {};
const shape = value.shape;
for (const key of value.keys) {
const el = shape[key];
const r = el._zod.run({
value: input[key],
issues: []
}, ctx);
const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
if (r instanceof Promise) proms.push(r.then((r) => isOptional ? handleOptionalObjectResult(r, payload, key, input) : handleObjectResult(r, payload, key)));
else if (isOptional) handleOptionalObjectResult(r, payload, key, input);
else handleObjectResult(r, payload, key);
}
}
if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
const unrecognized = [];
const keySet = value.keySet;
const _catchall = catchall._zod;
const t = _catchall.def.type;
for (const key of Object.keys(input)) {
if (keySet.has(key)) continue;
if (t === "never") {
unrecognized.push(key);
continue;
}
const r = _catchall.run({
value: input[key],
issues: []
}, ctx);
if (r instanceof Promise) proms.push(r.then((r) => handleObjectResult(r, payload, key)));
else handleObjectResult(r, payload, key);
}
if (unrecognized.length) payload.issues.push({
code: "unrecognized_keys",
keys: unrecognized,
input,
inst
});
if (!proms.length) return payload;
return Promise.all(proms).then(() => {
return payload;
});
};
});
function handleUnionResults(results, final, inst, ctx) {
for (const result of results) if (result.issues.length === 0) {
final.value = result.value;
return final;
}
final.issues.push({
code: "invalid_union",
input: final.value,
inst,
errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
});
return final;
}
const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
defineLazy(inst._zod, "values", () => {
if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
});
defineLazy(inst._zod, "pattern", () => {
if (def.options.every((o) => o._zod.pattern)) {
const patterns = def.options.map((o) => o._zod.pattern);
return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
}
});
inst._zod.parse = (payload, ctx) => {
let async = false;
const results = [];
for (const option of def.options) {
const result = option._zod.run({
value: payload.value,
issues: []
}, ctx);
if (result instanceof Promise) {
results.push(result);
async = true;
} else {
if (result.issues.length === 0) return result;
results.push(result);
}
}
if (!async) return handleUnionResults(results, payload, inst, ctx);
return Promise.all(results).then((results) => {
return handleUnionResults(results, payload, inst, ctx);
});
};
});
const $ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
$ZodUnion.init(inst, def);
const _super = inst._zod.parse;
defineLazy(inst._zod, "propValues", () => {
const propValues = {};
for (const option of def.options) {
const pv = option._zod.propValues;
if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
for (const [k, v] of Object.entries(pv)) {
if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set();
for (const val of v) propValues[k].add(val);
}
}
return propValues;
});
const disc = cached(() => {
const opts = def.options;
const map = /* @__PURE__ */ new Map();
for (const o of opts) {
const values = o._zod.propValues[def.discriminator];
if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
for (const v of values) {
if (map.has(v)) throw new Error(`Duplicate discriminator value "${String(v)}"`);
map.set(v, o);
}
}
return map;
});
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!isObject(input)) {
payload.issues.push({
code: "invalid_type",
expected: "object",
input,
inst
});
return payload;
}
const opt = disc.value.get(input?.[def.discriminator]);
if (opt) return opt._zod.run(payload, ctx);
if (def.unionFallback) return _super(payload, ctx);
payload.issues.push({
code: "invalid_union",
errors: [],
note: "No matching discriminator",
input,
path: [def.discriminator],
inst
});
return payload;
};
});
const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
const left = def.left._zod.run({
value: input,
issues: []
}, ctx);
const right = def.right._zod.run({
value: input,
issues: []
}, ctx);
if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => {
return handleIntersectionResults(payload, left, right);
});
return handleIntersectionResults(payload, left, right);
};
});
function mergeValues$1(a, b) {
if (a === b) return {
valid: true,
data: a
};
if (a instanceof Date && b instanceof Date && +a === +b) return {
valid: true,
data: a
};
if (isPlainObject$1(a) && isPlainObject$1(b)) {
const bKeys = Object.keys(b);
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = {
...a,
...b
};
for (const key of sharedKeys) {
const sharedValue = mergeValues$1(a[key], b[key]);
if (!sharedValue.valid) return {
valid: false,
mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
};
newObj[key] = sharedValue.data;
}
return {
valid: true,
data: newObj
};
}
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) return {
valid: false,
mergeErrorPath: []
};
const newArray = [];
for (let index = 0; index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues$1(itemA, itemB);
if (!sharedValue.valid) return {
valid: false,
mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
};
newArray.push(sharedValue.data);
}
return {
valid: true,
data: newArray
};
}
return {
valid: false,
mergeErrorPath: []
};
}
function handleIntersectionResults(result, left, right) {
if (left.issues.length) result.issues.push(...left.issues);
if (right.issues.length) result.issues.push(...right.issues);
if (aborted(result)) return result;
const merged = mergeValues$1(left.value, right.value);
if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
result.value = merged.data;
return result;
}
const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!isPlainObject$1(input)) {
payload.issues.push({
expected: "record",
code: "invalid_type",
input,
inst
});
return payload;
}
const proms = [];
if (def.keyType._zod.values) {
const values = def.keyType._zod.values;
payload.value = {};
for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
const result = def.valueType._zod.run({
value: input[key],
issues: []
}, ctx);
if (result instanceof Promise) proms.push(result.then((result) => {
if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
payload.value[key] = result.value;
}));
else {
if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
payload.value[key] = result.value;
}
}
let unrecognized;
for (const key in input) if (!values.has(key)) {
unrecognized = unrecognized ?? [];
unrecognized.push(key);
}
if (unrecognized && unrecognized.length > 0) payload.issues.push({
code: "unrecognized_keys",
input,
inst,
keys: unrecognized
});
} else {
payload.value = {};
for (const key of Reflect.ownKeys(input)) {
if (key === "__proto__") continue;
const keyResult = def.keyType._zod.run({
value: key,
issues: []
}, ctx);
if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
if (keyResult.issues.length) {
payload.issues.push({
origin: "record",
code: "invalid_key",
issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
input: key,
path: [key],
inst
});
payload.value[keyResult.value] = keyResult.value;
continue;
}
const result = def.valueType._zod.run({
value: input[key],
issues: []
}, ctx);
if (result instanceof Promise) proms.push(result.then((result) => {
if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
payload.value[keyResult.value] = result.value;
}));
else {
if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
payload.value[keyResult.value] = result.value;
}
}
}
if (proms.length) return Promise.all(proms).then(() => payload);
return payload;
};
});
const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
$ZodType.init(inst, def);
const values = getEnumValues(def.entries);
inst._zod.values = new Set(values);
inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (inst._zod.values.has(input)) return payload;
payload.issues.push({
code: "invalid_value",
values,
input,
inst
});
return payload;
};
});
const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.values = new Set(def.values);
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`);
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (inst._zod.values.has(input)) return payload;
payload.issues.push({
code: "invalid_value",
values: def.values,
input,
inst
});
return payload;
};
});
const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, _ctx) => {
const _out = def.transform(payload.value, payload);
if (_ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => {
payload.value = output;
return payload;
});
if (_out instanceof Promise) throw new $ZodAsyncError();
payload.value = _out;
return payload;
};
});
const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
inst._zod.optout = "optional";
defineLazy(inst._zod, "values", () => {
return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
});
defineLazy(inst._zod, "pattern", () => {
const pattern = def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
});
inst._zod.parse = (payload, ctx) => {
if (def.innerType._zod.optin === "optional") return def.innerType._zod.run(payload, ctx);
if (payload.value === void 0) return payload;
return def.innerType._zod.run(payload, ctx);
};
});
const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
defineLazy(inst._zod, "pattern", () => {
const pattern = def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
});
defineLazy(inst._zod, "values", () => {
return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
});
inst._zod.parse = (payload, ctx) => {
if (payload.value === null) return payload;
return def.innerType._zod.run(payload, ctx);
};
});
const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (payload.value === void 0) {
payload.value = def.defaultValue;
/**
* $ZodDefault always returns the default value immediately.
* It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
return payload;
}
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def));
return handleDefaultResult(result, def);
};
});
function handleDefaultResult(payload, def) {
if (payload.value === void 0) payload.value = def.defaultValue;
return payload;
}
const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (payload.value === void 0) payload.value = def.defaultValue;
return def.innerType._zod.run(payload, ctx);
};
});
const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "values", () => {
const v = def.innerType._zod.values;
return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
});
inst._zod.parse = (payload, ctx) => {
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst));
return handleNonOptionalResult(result, inst);
};
});
function handleNonOptionalResult(payload, inst) {
if (!payload.issues.length && payload.value === void 0) payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: payload.value,
inst
});
return payload;
}
const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result) => {
payload.value = result.value;
if (result.issues.length) {
payload.value = def.catchValue({
...payload,
error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
input: payload.value
});
payload.issues = [];
}
return payload;
});
payload.value = result.value;
if (result.issues.length) {
payload.value = def.catchValue({
...payload,
error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
input: payload.value
});
payload.issues = [];
}
return payload;
};
});
const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "values", () => def.in._zod.values);
defineLazy(inst._zod, "optin", () => def.in._zod.optin);
defineLazy(inst._zod, "optout", () => def.out._zod.optout);
inst._zod.parse = (payload, ctx) => {
const left = def.in._zod.run(payload, ctx);
if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def, ctx));
return handlePipeResult(left, def, ctx);
};
});
function handlePipeResult(left, def, ctx) {
if (aborted(left)) return left;
return def.out._zod.run({
value: left.value,
issues: left.issues
}, ctx);
}
const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
inst._zod.parse = (payload, ctx) => {
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then(handleReadonlyResult);
return handleReadonlyResult(result);
};
});
function handleReadonlyResult(payload) {
payload.value = Object.freeze(payload.value);
return payload;
}
const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => {
$ZodType.init(inst, def);
defineLazy(inst._zod, "innerType", () => def.getter());
defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern);
defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues);
defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin);
defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout);
inst._zod.parse = (payload, ctx) => {
return inst._zod.innerType._zod.run(payload, ctx);
};
});
const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => {
$ZodCheck.init(inst, def);
$ZodType.init(inst, def);
inst._zod.parse = (payload, _) => {
return payload;
};
inst._zod.check = (payload) => {
const input = payload.value;
const r = def.fn(input);
if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst));
handleRefineResult(r, payload, input, inst);
};
});
function handleRefineResult(result, payload, input, inst) {
if (!result) {
const _iss = {
code: "custom",
input,
inst,
path: [...inst._zod.def.path ?? []],
continue: !inst._zod.def.abort
};
if (inst._zod.def.params) _iss.params = inst._zod.def.params;
payload.issues.push(issue(_iss));
}
}
//#endregion
//#region node_modules/zod/v4/core/registries.js
var $ZodRegistry = class {
constructor() {
this._map = /* @__PURE__ */ new Map();
this._idmap = /* @__PURE__ */ 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;
}
clear() {
this._map = /* @__PURE__ */ new Map();
this._idmap = /* @__PURE__ */ new Map();
return this;
}
remove(schema) {
const meta = this._map.get(schema);
if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id);
this._map.delete(schema);
return this;
}
get(schema) {
const p = schema._zod.parent;
if (p) {
const pm = { ...this.get(p) ?? {} };
delete pm.id;
return {
...pm,
...this._map.get(schema)
};
}
return this._map.get(schema);
}
has(schema) {
return this._map.has(schema);
}
};
function registry() {
return new $ZodRegistry();
}
const globalRegistry = /*@__PURE__*/ registry();
//#endregion
//#region node_modules/zod/v4/core/api.js
function _string(Class, params) {
return new Class({
type: "string",
...normalizeParams(params)
});
}
function _email(Class, params) {
return new Class({
type: "string",
format: "email",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _guid(Class, params) {
return new Class({
type: "string",
format: "guid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _uuid(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _uuidv4(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v4",
...normalizeParams(params)
});
}
function _uuidv6(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v6",
...normalizeParams(params)
});
}
function _uuidv7(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v7",
...normalizeParams(params)
});
}
function _url(Class, params) {
return new Class({
type: "string",
format: "url",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _emoji(Class, params) {
return new Class({
type: "string",
format: "emoji",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _nanoid(Class, params) {
return new Class({
type: "string",
format: "nanoid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cuid(Class, params) {
return new Class({
type: "string",
format: "cuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cuid2(Class, params) {
return new Class({
type: "string",
format: "cuid2",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ulid(Class, params) {
return new Class({
type: "string",
format: "ulid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _xid(Class, params) {
return new Class({
type: "string",
format: "xid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ksuid(Class, params) {
return new Class({
type: "string",
format: "ksuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ipv4(Class, params) {
return new Class({
type: "string",
format: "ipv4",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _ipv6(Class, params) {
return new Class({
type: "string",
format: "ipv6",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cidrv4(Class, params) {
return new Class({
type: "string",
format: "cidrv4",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _cidrv6(Class, params) {
return new Class({
type: "string",
format: "cidrv6",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _base64(Class, params) {
return new Class({
type: "string",
format: "base64",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _base64url(Class, params) {
return new Class({
type: "string",
format: "base64url",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _e164(Class, params) {
return new Class({
type: "string",
format: "e164",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _jwt(Class, params) {
return new Class({
type: "string",
format: "jwt",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
function _isoDateTime(Class, params) {
return new Class({
type: "string",
format: "datetime",
check: "string_format",
offset: false,
local: false,
precision: null,
...normalizeParams(params)
});
}
function _isoDate(Class, params) {
return new Class({
type: "string",
format: "date",
check: "string_format",
...normalizeParams(params)
});
}
function _isoTime(Class, params) {
return new Class({
type: "string",
format: "time",
check: "string_format",
precision: null,
...normalizeParams(params)
});
}
function _isoDuration(Class, params) {
return new Class({
type: "string",
format: "duration",
check: "string_format",
...normalizeParams(params)
});
}
function _number(Class, params) {
return new Class({
type: "number",
checks: [],
...normalizeParams(params)
});
}
function _int(Class, params) {
return new Class({
type: "number",
check: "number_format",
abort: false,
format: "safeint",
...normalizeParams(params)
});
}
function _boolean(Class, params) {
return new Class({
type: "boolean",
...normalizeParams(params)
});
}
function _null$1(Class, params) {
return new Class({
type: "null",
...normalizeParams(params)
});
}
function _any(Class) {
return new Class({ type: "any" });
}
function _unknown(Class) {
return new Class({ type: "unknown" });
}
function _never(Class, params) {
return new Class({
type: "never",
...normalizeParams(params)
});
}
function _lt(value, params) {
return new $ZodCheckLessThan({
check: "less_than",
...normalizeParams(params),
value,
inclusive: false
});
}
function _lte(value, params) {
return new $ZodCheckLessThan({
check: "less_than",
...normalizeParams(params),
value,
inclusive: true
});
}
function _gt(value, params) {
return new $ZodCheckGreaterThan({
check: "greater_than",
...normalizeParams(params),
value,
inclusive: false
});
}
function _gte(value, params) {
return new $ZodCheckGreaterThan({
check: "greater_than",
...normalizeParams(params),
value,
inclusive: true
});
}
function _multipleOf(value, params) {
return new $ZodCheckMultipleOf({
check: "multiple_of",
...normalizeParams(params),
value
});
}
function _maxLength(maximum, params) {
return new $ZodCheckMaxLength({
check: "max_length",
...normalizeParams(params),
maximum
});
}
function _minLength(minimum, params) {
return new $ZodCheckMinLength({
check: "min_length",
...normalizeParams(params),
minimum
});
}
function _length(length, params) {
return new $ZodCheckLengthEquals({
check: "length_equals",
...normalizeParams(params),
length
});
}
function _regex(pattern, params) {
return new $ZodCheckRegex({
check: "string_format",
format: "regex",
...normalizeParams(params),
pattern
});
}
function _lowercase(params) {
return new $ZodCheckLowerCase({
check: "string_format",
format: "lowercase",
...normalizeParams(params)
});
}
function _uppercase(params) {
return new $ZodCheckUpperCase({
check: "string_format",
format: "uppercase",
...normalizeParams(params)
});
}
function _includes(includes, params) {
return new $ZodCheckIncludes({
check: "string_format",
format: "includes",
...normalizeParams(params),
includes
});
}
function _startsWith(prefix, params) {
return new $ZodCheckStartsWith({
check: "string_format",
format: "starts_with",
...normalizeParams(params),
prefix
});
}
function _endsWith(suffix, params) {
return new $ZodCheckEndsWith({
check: "string_format",
format: "ends_with",
...normalizeParams(params),
suffix
});
}
function _overwrite(tx) {
return new $ZodCheckOverwrite({
check: "overwrite",
tx
});
}
function _normalize(form) {
return _overwrite((input) => input.normalize(form));
}
function _trim() {
return _overwrite((input) => input.trim());
}
function _toLowerCase() {
return _overwrite((input) => input.toLowerCase());
}
function _toUpperCase() {
return _overwrite((input) => input.toUpperCase());
}
function _array(Class, element, params) {
return new Class({
type: "array",
element,
...normalizeParams(params)
});
}
function _custom(Class, fn, _params) {
const norm = normalizeParams(_params);
norm.abort ?? (norm.abort = true);
return new Class({
type: "custom",
check: "custom",
fn,
...norm
});
}
function _refine(Class, fn, _params) {
return new Class({
type: "custom",
check: "custom",
fn,
...normalizeParams(_params)
});
}
//#endregion
//#region node_modules/zod/v4/core/to-json-schema.js
var JSONSchemaGenerator = class {
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 = /* @__PURE__ */ 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: ""
};
const seen = this.seen.get(schema);
if (seen) {
seen.count++;
if (_params.schemaPath.includes(schema)) seen.cycle = _params.path;
return seen.schema;
}
const result = {
schema: {},
count: 1,
cycle: void 0,
path: _params.path
};
this.seen.set(schema, result);
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) {
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;
if (format) {
json.format = formatMap[format] ?? format;
if (json.format === "") delete json.format;
}
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":
if (this.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
break;
case "void":
if (this.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
break;
case "never":
_json.not = {};
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;
for (const key in shape) json.properties[key] = this.process(shape[key], {
...params,
path: [
...params.path,
"properties",
key
]
});
const allKeys = new Set(Object.keys(shape));
const requiredKeys = new Set([...allKeys].filter((key) => {
const v = def.shape[key]._zod;
if (this.io === "input") return v.optin === void 0;
else return v.optout === void 0;
}));
if (requiredKeys.size > 0) json.required = Array.from(requiredKeys);
if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
else if (!def.catchall) {
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;
json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
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;
}
if (def.rest) json.items = this.process(def.rest, {
...params,
path: [...params.path, "items"]
});
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);
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 === void 0) {
if (this.unrepresentable === "throw") throw new Error("Literal `undefined` cannot be represented in JSON Schema");
} 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) {} 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 !== void 0) file.minLength = minimum;
if (maximum !== void 0) file.maxLength = maximum;
if (mime) if (mime.length === 1) {
file.contentMediaType = mime[0];
Object.assign(json, file);
} else json.anyOf = mime.map((m) => {
return {
...file,
contentMediaType: m
};
});
else Object.assign(json, file);
break;
}
case "transform":
if (this.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
break;
case "nullable":
_json.anyOf = [this.process(def.innerType, params), { 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": {
this.process(def.innerType, params);
result.ref = def.innerType;
let catchValue;
try {
catchValue = def.catchValue(void 0);
} 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;
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:
}
}
}
const meta = this.metadataRegistry.get(schema);
if (meta) Object.assign(result.schema, meta);
if (this.io === "input" && isTransforming(schema)) {
delete result.schema.examples;
delete result.schema.default;
}
if (this.io === "input" && result.schema._prefault) (_a = result.schema).default ?? (_a.default = result.schema._prefault);
delete result.schema._prefault;
return this.seen.get(schema).schema;
}
emit(schema, _params) {
const params = {
cycles: _params?.cycles ?? "ref",
reused: _params?.reused ?? "inline",
external: _params?.external ?? void 0
};
const root = this.seen.get(schema);
if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
const makeURI = (entry) => {
const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";
if (params.external) {
const externalId = params.external.registry.get(entry[0])?.id;
const uriGenerator = params.external.uri ?? ((id) => id);
if (externalId) return { ref: uriGenerator(externalId) };
const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;
entry[1].defId = id;
return {
defId: id,
ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}`
};
}
if (entry[1] === root) return { ref: "#" };
const defUriPrefix = `#/${defsSegment}/`;
const defId = entry[1].schema.id ?? `__schema${this.counter++}`;
return {
defId,
ref: defUriPrefix + defId
};
};
const extractToDef = (entry) => {
if (entry[1].schema.$ref) return;
const seen = entry[1];
const { ref, defId } = makeURI(entry);
seen.def = { ...seen.schema };
if (defId) seen.defId = defId;
const schema = seen.schema;
for (const key in schema) delete schema[key];
schema.$ref = ref;
};
if (params.cycles === "throw") for (const entry of this.seen.entries()) {
const seen = entry[1];
if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
}
for (const entry of this.seen.entries()) {
const seen = entry[1];
if (schema === entry[0]) {
extractToDef(entry);
continue;
}
if (params.external) {
const ext = params.external.registry.get(entry[0])?.id;
if (schema !== entry[0] && ext) {
extractToDef(entry);
continue;
}
}
if (this.metadataRegistry.get(entry[0])?.id) {
extractToDef(entry);
continue;
}
if (seen.cycle) {
extractToDef(entry);
continue;
}
if (seen.count > 1) {
if (params.reused === "ref") {
extractToDef(entry);
continue;
}
}
}
const flattenRef = (zodSchema, params) => {
const seen = this.seen.get(zodSchema);
const schema = seen.def ?? seen.schema;
const _cached = { ...schema };
if (seen.ref === null) return;
const ref = seen.ref;
seen.ref = null;
if (ref) {
flattenRef(ref, params);
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);
}
}
if (!seen.isParent) this.override({
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}`);
if (params.external?.uri) {
const id = params.external.registry.get(schema)?.id;
if (!id) throw new Error("Schema is missing an `id` property");
result.$id = params.external.uri(id);
}
Object.assign(result, root.def);
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;
}
if (params.external) {} else if (Object.keys(defs).length > 0) if (this.target === "draft-2020-12") result.$defs = defs;
else result.definitions = defs;
try {
return JSON.parse(JSON.stringify(result));
} catch (_err) {
throw new Error("Error converting schema to JSON.");
}
}
};
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,
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) schemas.__shared = { [gen.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
return { schemas };
}
const gen = new JSONSchemaGenerator(_params);
gen.process(input);
return gen.emit(input, _params);
}
function isTransforming(_schema, _ctx) {
const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
if (ctx.seen.has(_schema)) return false;
ctx.seen.add(_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);
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:
}
throw new Error(`Unknown schema type: ${def.type}`);
}
//#endregion
//#region node_modules/zod/v4/classic/iso.js
const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
$ZodISODateTime.init(inst, def);
ZodStringFormat.init(inst, def);
});
function datetime(params) {
return _isoDateTime(ZodISODateTime, params);
}
const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => {
$ZodISODate.init(inst, def);
ZodStringFormat.init(inst, def);
});
function date(params) {
return _isoDate(ZodISODate, params);
}
const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => {
$ZodISOTime.init(inst, def);
ZodStringFormat.init(inst, def);
});
function time(params) {
return _isoTime(ZodISOTime, params);
}
const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => {
$ZodISODuration.init(inst, def);
ZodStringFormat.init(inst, def);
});
function duration(params) {
return _isoDuration(ZodISODuration, params);
}
//#endregion
//#region node_modules/zod/v4/classic/errors.js
const initializer = (inst, issues) => {
$ZodError.init(inst, issues);
inst.name = "ZodError";
Object.defineProperties(inst, {
format: { value: (mapper) => formatError(inst, mapper) },
flatten: { value: (mapper) => flattenError(inst, mapper) },
addIssue: { value: (issue) => inst.issues.push(issue) },
addIssues: { value: (issues) => inst.issues.push(...issues) },
isEmpty: { get() {
return inst.issues.length === 0;
} }
});
};
$constructor("ZodError", initializer);
const ZodRealError = $constructor("ZodError", initializer, { Parent: Error });
//#endregion
//#region node_modules/zod/v4/classic/parse.js
const parse = /* @__PURE__ */ _parse$1(ZodRealError);
const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
//#endregion
//#region node_modules/zod/v4/classic/schemas.js
const ZodType$1 = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
$ZodType.init(inst, def);
inst.def = def;
Object.defineProperty(inst, "_def", { value: def });
inst.check = (...checks) => {
return inst.clone({
...def,
checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
check: ch,
def: { check: "custom" },
onattach: []
} } : ch)]
});
};
inst.clone = (def, params) => clone(inst, def, params);
inst.brand = () => inst;
inst.register = ((reg, meta) => {
reg.add(inst, meta);
return inst;
});
inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
inst.safeParse = (data, params) => safeParse(inst, data, params);
inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
inst.spa = inst.safeParseAsync;
inst.refine = (check, params) => inst.check(refine(check, params));
inst.superRefine = (refinement) => inst.check(superRefine(refinement));
inst.overwrite = (fn) => inst.check(_overwrite(fn));
inst.optional = () => optional(inst);
inst.nullable = () => nullable(inst);
inst.nullish = () => optional(nullable(inst));
inst.nonoptional = (params) => nonoptional(inst, params);
inst.array = () => array(inst);
inst.or = (arg) => union([inst, arg]);
inst.and = (arg) => intersection(inst, arg);
inst.transform = (tx) => pipe(inst, transform(tx));
inst.default = (def) => _default(inst, def);
inst.prefault = (def) => prefault(inst, def);
inst.catch = (params) => _catch(inst, params);
inst.pipe = (target) => pipe(inst, target);
inst.readonly = () => readonly(inst);
inst.describe = (description) => {
const cl = inst.clone();
globalRegistry.add(cl, { description });
return cl;
};
Object.defineProperty(inst, "description", {
get() {
return globalRegistry.get(inst)?.description;
},
configurable: true
});
inst.meta = (...args) => {
if (args.length === 0) return globalRegistry.get(inst);
const cl = inst.clone();
globalRegistry.add(cl, args[0]);
return cl;
};
inst.isOptional = () => inst.safeParse(void 0).success;
inst.isNullable = () => inst.safeParse(null).success;
return inst;
});
/** @internal */
const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => {
$ZodString.init(inst, def);
ZodType$1.init(inst, def);
const bag = inst._zod.bag;
inst.format = bag.format ?? null;
inst.minLength = bag.minimum ?? null;
inst.maxLength = bag.maximum ?? null;
inst.regex = (...args) => inst.check(_regex(...args));
inst.includes = (...args) => inst.check(_includes(...args));
inst.startsWith = (...args) => inst.check(_startsWith(...args));
inst.endsWith = (...args) => inst.check(_endsWith(...args));
inst.min = (...args) => inst.check(_minLength(...args));
inst.max = (...args) => inst.check(_maxLength(...args));
inst.length = (...args) => inst.check(_length(...args));
inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
inst.lowercase = (params) => inst.check(_lowercase(params));
inst.uppercase = (params) => inst.check(_uppercase(params));
inst.trim = () => inst.check(_trim());
inst.normalize = (...args) => inst.check(_normalize(...args));
inst.toLowerCase = () => inst.check(_toLowerCase());
inst.toUpperCase = () => inst.check(_toUpperCase());
});
const ZodString$1 = /*@__PURE__*/ $constructor("ZodString", (inst, def) => {
$ZodString.init(inst, def);
_ZodString.init(inst, def);
inst.email = (params) => inst.check(_email(ZodEmail, params));
inst.url = (params) => inst.check(_url(ZodURL, params));
inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
inst.guid = (params) => inst.check(_guid(ZodGUID, params));
inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
inst.guid = (params) => inst.check(_guid(ZodGUID, params));
inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
inst.xid = (params) => inst.check(_xid(ZodXID, params));
inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
inst.e164 = (params) => inst.check(_e164(ZodE164, params));
inst.datetime = (params) => inst.check(datetime(params));
inst.date = (params) => inst.check(date(params));
inst.time = (params) => inst.check(time(params));
inst.duration = (params) => inst.check(duration(params));
});
function string(params) {
return _string(ZodString$1, params);
}
const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => {
$ZodStringFormat.init(inst, def);
_ZodString.init(inst, def);
});
const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => {
$ZodEmail.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => {
$ZodGUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => {
$ZodUUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
$ZodURL.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => {
$ZodEmoji.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => {
$ZodNanoID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => {
$ZodCUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => {
$ZodCUID2.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => {
$ZodULID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => {
$ZodXID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => {
$ZodKSUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => {
$ZodIPv4.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => {
$ZodIPv6.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => {
$ZodCIDRv4.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => {
$ZodCIDRv6.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => {
$ZodBase64.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => {
$ZodBase64URL.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => {
$ZodE164.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => {
$ZodJWT.init(inst, def);
ZodStringFormat.init(inst, def);
});
const ZodNumber$1 = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => {
$ZodNumber.init(inst, def);
ZodType$1.init(inst, def);
inst.gt = (value, params) => inst.check(_gt(value, params));
inst.gte = (value, params) => inst.check(_gte(value, params));
inst.min = (value, params) => inst.check(_gte(value, params));
inst.lt = (value, params) => inst.check(_lt(value, params));
inst.lte = (value, params) => inst.check(_lte(value, params));
inst.max = (value, params) => inst.check(_lte(value, params));
inst.int = (params) => inst.check(int(params));
inst.safe = (params) => inst.check(int(params));
inst.positive = (params) => inst.check(_gt(0, params));
inst.nonnegative = (params) => inst.check(_gte(0, params));
inst.negative = (params) => inst.check(_lt(0, params));
inst.nonpositive = (params) => inst.check(_lte(0, params));
inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
inst.step = (value, params) => inst.check(_multipleOf(value, params));
inst.finite = () => inst;
const bag = inst._zod.bag;
inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5);
inst.isFinite = true;
inst.format = bag.format ?? null;
});
function number(params) {
return _number(ZodNumber$1, params);
}
const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => {
$ZodNumberFormat.init(inst, def);
ZodNumber$1.init(inst, def);
});
function int(params) {
return _int(ZodNumberFormat, params);
}
const ZodBoolean$1 = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => {
$ZodBoolean.init(inst, def);
ZodType$1.init(inst, def);
});
function boolean(params) {
return _boolean(ZodBoolean$1, params);
}
const ZodNull$1 = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => {
$ZodNull.init(inst, def);
ZodType$1.init(inst, def);
});
function _null(params) {
return _null$1(ZodNull$1, params);
}
const ZodAny$1 = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => {
$ZodAny.init(inst, def);
ZodType$1.init(inst, def);
});
function any() {
return _any(ZodAny$1);
}
const ZodUnknown$1 = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => {
$ZodUnknown.init(inst, def);
ZodType$1.init(inst, def);
});
function unknown() {
return _unknown(ZodUnknown$1);
}
const ZodNever$1 = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => {
$ZodNever.init(inst, def);
ZodType$1.init(inst, def);
});
function never(params) {
return _never(ZodNever$1, params);
}
const ZodArray$1 = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => {
$ZodArray.init(inst, def);
ZodType$1.init(inst, def);
inst.element = def.element;
inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
inst.nonempty = (params) => inst.check(_minLength(1, params));
inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
inst.length = (len, params) => inst.check(_length(len, params));
inst.unwrap = () => inst.element;
});
function array(element, params) {
return _array(ZodArray$1, element, params);
}
const ZodObject$1 = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
$ZodObject.init(inst, def);
ZodType$1.init(inst, def);
defineLazy(inst, "shape", () => def.shape);
inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
inst.catchall = (catchall) => inst.clone({
...inst._zod.def,
catchall
});
inst.passthrough = () => inst.clone({
...inst._zod.def,
catchall: unknown()
});
inst.loose = () => inst.clone({
...inst._zod.def,
catchall: unknown()
});
inst.strict = () => inst.clone({
...inst._zod.def,
catchall: never()
});
inst.strip = () => inst.clone({
...inst._zod.def,
catchall: void 0
});
inst.extend = (incoming) => {
return extend(inst, incoming);
};
inst.merge = (other) => merge(inst, other);
inst.pick = (mask) => pick(inst, mask);
inst.omit = (mask) => omit(inst, mask);
inst.partial = (...args) => partial(ZodOptional$1, inst, args[0]);
inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
});
function object(shape, params) {
const def = {
type: "object",
get shape() {
assignProp(this, "shape", { ...shape });
return this.shape;
},
...normalizeParams(params)
};
return new ZodObject$1(def);
}
function strictObject(shape, params) {
return new ZodObject$1({
type: "object",
get shape() {
assignProp(this, "shape", { ...shape });
return this.shape;
},
catchall: never(),
...normalizeParams(params)
});
}
const ZodUnion$1 = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => {
$ZodUnion.init(inst, def);
ZodType$1.init(inst, def);
inst.options = def.options;
});
function union(options, params) {
return new ZodUnion$1({
type: "union",
options,
...normalizeParams(params)
});
}
const ZodDiscriminatedUnion$1 = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => {
ZodUnion$1.init(inst, def);
$ZodDiscriminatedUnion.init(inst, def);
});
function discriminatedUnion(discriminator, options, params) {
return new ZodDiscriminatedUnion$1({
type: "union",
options,
discriminator,
...normalizeParams(params)
});
}
const ZodIntersection$1 = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => {
$ZodIntersection.init(inst, def);
ZodType$1.init(inst, def);
});
function intersection(left, right) {
return new ZodIntersection$1({
type: "intersection",
left,
right
});
}
const ZodRecord$1 = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => {
$ZodRecord.init(inst, def);
ZodType$1.init(inst, def);
inst.keyType = def.keyType;
inst.valueType = def.valueType;
});
function record(keyType, valueType, params) {
return new ZodRecord$1({
type: "record",
keyType,
valueType,
...normalizeParams(params)
});
}
const ZodEnum$1 = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => {
$ZodEnum.init(inst, def);
ZodType$1.init(inst, def);
inst.enum = def.entries;
inst.options = Object.values(def.entries);
const keys = new Set(Object.keys(def.entries));
inst.extract = (values, params) => {
const newEntries = {};
for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value];
else throw new Error(`Key ${value} not found in enum`);
return new ZodEnum$1({
...def,
checks: [],
...normalizeParams(params),
entries: newEntries
});
};
inst.exclude = (values, params) => {
const newEntries = { ...def.entries };
for (const value of values) if (keys.has(value)) delete newEntries[value];
else throw new Error(`Key ${value} not found in enum`);
return new ZodEnum$1({
...def,
checks: [],
...normalizeParams(params),
entries: newEntries
});
};
});
function _enum(values, params) {
const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
return new ZodEnum$1({
type: "enum",
entries,
...normalizeParams(params)
});
}
const ZodLiteral$1 = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => {
$ZodLiteral.init(inst, def);
ZodType$1.init(inst, def);
inst.values = new Set(def.values);
Object.defineProperty(inst, "value", { get() {
if (def.values.length > 1) throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
return def.values[0];
} });
});
function literal(value, params) {
return new ZodLiteral$1({
type: "literal",
values: Array.isArray(value) ? value : [value],
...normalizeParams(params)
});
}
const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => {
$ZodTransform.init(inst, def);
ZodType$1.init(inst, def);
inst._zod.parse = (payload, _ctx) => {
payload.addIssue = (issue$2) => {
if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, def));
else {
const _issue = issue$2;
if (_issue.fatal) _issue.continue = false;
_issue.code ?? (_issue.code = "custom");
_issue.input ?? (_issue.input = payload.value);
_issue.inst ?? (_issue.inst = inst);
_issue.continue ?? (_issue.continue = true);
payload.issues.push(issue(_issue));
}
};
const output = def.transform(payload.value, payload);
if (output instanceof Promise) return output.then((output) => {
payload.value = output;
return payload;
});
payload.value = output;
return payload;
};
});
function transform(fn) {
return new ZodTransform({
type: "transform",
transform: fn
});
}
const ZodOptional$1 = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => {
$ZodOptional.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
});
function optional(innerType) {
return new ZodOptional$1({
type: "optional",
innerType
});
}
const ZodNullable$1 = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => {
$ZodNullable.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
});
function nullable(innerType) {
return new ZodNullable$1({
type: "nullable",
innerType
});
}
const ZodDefault$1 = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => {
$ZodDefault.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
inst.removeDefault = inst.unwrap;
});
function _default(innerType, defaultValue) {
return new ZodDefault$1({
type: "default",
innerType,
get defaultValue() {
return typeof defaultValue === "function" ? defaultValue() : defaultValue;
}
});
}
const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => {
$ZodPrefault.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
});
function prefault(innerType, defaultValue) {
return new ZodPrefault({
type: "prefault",
innerType,
get defaultValue() {
return typeof defaultValue === "function" ? defaultValue() : defaultValue;
}
});
}
const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => {
$ZodNonOptional.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional(innerType, params) {
return new ZodNonOptional({
type: "nonoptional",
innerType,
...normalizeParams(params)
});
}
const ZodCatch$1 = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => {
$ZodCatch.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.innerType;
inst.removeCatch = inst.unwrap;
});
function _catch(innerType, catchValue) {
return new ZodCatch$1({
type: "catch",
innerType,
catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
});
}
const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => {
$ZodPipe.init(inst, def);
ZodType$1.init(inst, def);
inst.in = def.in;
inst.out = def.out;
});
function pipe(in_, out) {
return new ZodPipe({
type: "pipe",
in: in_,
out
});
}
const ZodReadonly$1 = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => {
$ZodReadonly.init(inst, def);
ZodType$1.init(inst, def);
});
function readonly(innerType) {
return new ZodReadonly$1({
type: "readonly",
innerType
});
}
const ZodLazy$1 = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => {
$ZodLazy.init(inst, def);
ZodType$1.init(inst, def);
inst.unwrap = () => inst._zod.def.getter();
});
function lazy(getter) {
return new ZodLazy$1({
type: "lazy",
getter
});
}
const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => {
$ZodCustom.init(inst, def);
ZodType$1.init(inst, def);
});
function check(fn) {
const ch = new $ZodCheck({ check: "custom" });
ch._zod.check = fn;
return ch;
}
function custom(fn, _params) {
return _custom(ZodCustom, fn ?? (() => true), _params);
}
function refine(fn, _params = {}) {
return _refine(ZodCustom, fn, _params);
}
function superRefine(fn) {
const ch = check((payload) => {
payload.addIssue = (issue$1) => {
if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
else {
const _issue = issue$1;
if (_issue.fatal) _issue.continue = false;
_issue.code ?? (_issue.code = "custom");
_issue.input ?? (_issue.input = payload.value);
_issue.inst ?? (_issue.inst = ch);
_issue.continue ?? (_issue.continue = !ch._zod.def.abort);
payload.issues.push(issue(_issue));
}
};
return fn(payload.value, payload);
});
return ch;
}
function _instanceof(cls, params = { error: `Input not instance of ${cls.name}` }) {
const inst = new ZodCustom({
type: "custom",
check: "custom",
fn: (data) => data instanceof cls,
abort: true,
...normalizeParams(params)
});
inst._zod.bag.Class = cls;
return inst;
}
//#endregion
//#region node_modules/zod/v3/helpers/util.js
var util;
(function(util) {
util.assertEqual = (_) => {};
function assertIs(_arg) {}
util.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util.assertNever = assertNever;
util.arrayToEnum = (items) => {
const obj = {};
for (const item of items) obj[item] = item;
return obj;
};
util.getValidEnumValues = (obj) => {
const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) filtered[k] = obj[k];
return util.objectValues(filtered);
};
util.objectValues = (obj) => {
return util.objectKeys(obj).map(function(e) {
return obj[e];
});
};
util.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
return keys;
};
util.find = (arr, checker) => {
for (const item of arr) if (checker(item)) return item;
};
util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
}
util.joinValues = joinValues;
util.jsonStringifyReplacer = (_, value) => {
if (typeof value === "bigint") return value.toString();
return value;
};
})(util || (util = {}));
var objectUtil;
(function(objectUtil) {
objectUtil.mergeShapes = (first, second) => {
return {
...first,
...second
};
};
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
const getParsedType = (data) => {
switch (typeof data) {
case "undefined": return ZodParsedType.undefined;
case "string": return ZodParsedType.string;
case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean": return ZodParsedType.boolean;
case "function": return ZodParsedType.function;
case "bigint": return ZodParsedType.bigint;
case "symbol": return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) return ZodParsedType.array;
if (data === null) return ZodParsedType.null;
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") return ZodParsedType.promise;
if (typeof Map !== "undefined" && data instanceof Map) return ZodParsedType.map;
if (typeof Set !== "undefined" && data instanceof Set) return ZodParsedType.set;
if (typeof Date !== "undefined" && data instanceof Date) return ZodParsedType.date;
return ZodParsedType.object;
default: return ZodParsedType.unknown;
}
};
//#endregion
//#region node_modules/zod/v3/ZodError.js
const ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
var ZodError = class ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
else this.__proto__ = actualProto;
this.name = "ZodError";
this.issues = issues;
}
format(_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.unionErrors.map(processError);
else if (issue.code === "invalid_return_type") processError(issue.returnTypeError);
else if (issue.code === "invalid_arguments") processError(issue.argumentsError);
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];
if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) if (sub.path.length > 0) {
const firstEl = sub.path[0];
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
fieldErrors[firstEl].push(mapper(sub));
} else formErrors.push(mapper(sub));
return {
formErrors,
fieldErrors
};
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => {
return new ZodError(issues);
};
//#endregion
//#region node_modules/zod/v3/locales/en.js
const errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) message = "Required";
else message = `Expected ${issue.expected}, received ${issue.received}`;
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
} else if ("startsWith" in issue.validation) message = `Invalid input: must start with "${issue.validation.startsWith}"`;
else if ("endsWith" in issue.validation) message = `Invalid input: must end with "${issue.validation.endsWith}"`;
else util.assertNever(issue.validation);
else if (issue.validation !== "regex") message = `Invalid ${issue.validation}`;
else message = "Invalid";
break;
case ZodIssueCode.too_small:
if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "bigint") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
//#endregion
//#region node_modules/zod/v3/errors.js
let overrideErrorMap = errorMap;
function getErrorMap() {
return overrideErrorMap;
}
//#endregion
//#region node_modules/zod/v3/helpers/parseUtil.js
const makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== void 0) return {
...issueData,
path: fullPath,
message: issueData.message
};
let errorMessage = "";
const maps = errorMaps.filter((m) => !!m).slice().reverse();
for (const map of maps) errorMessage = map(fullIssue, {
data,
defaultError: errorMessage
}).message;
return {
...issueData,
path: fullPath,
message: errorMessage
};
};
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === errorMap ? void 0 : errorMap
].filter((x) => !!x)
});
ctx.common.issues.push(issue);
}
var ParseStatus = class ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid") this.value = "dirty";
}
abort() {
if (this.value !== "aborted") this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted") return INVALID;
if (s.status === "dirty") status.dirty();
arrayValue.push(s.value);
}
return {
status: status.value,
value: arrayValue
};
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted") return INVALID;
if (value.status === "aborted") return INVALID;
if (key.status === "dirty") status.dirty();
if (value.status === "dirty") status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) finalObject[key.value] = value.value;
}
return {
status: status.value,
value: finalObject
};
}
};
const INVALID = Object.freeze({ status: "aborted" });
const DIRTY = (value) => ({
status: "dirty",
value
});
const OK = (value) => ({
status: "valid",
value
});
const isAborted = (x) => x.status === "aborted";
const isDirty = (x) => x.status === "dirty";
const isValid = (x) => x.status === "valid";
const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
//#endregion
//#region node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil) {
errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));
//#endregion
//#region node_modules/zod/v3/types.js
var ParseInputLazyPath = class {
constructor(parent, value, path, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
this._key = key;
}
get path() {
if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key);
else this._cachedPath.push(...this._path, this._key);
return this._cachedPath;
}
};
const handleResult = (ctx, result) => {
if (isValid(result)) return {
success: true,
data: result.value
};
else {
if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected.");
return {
success: false,
get error() {
if (this._error) return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
}
};
}
};
function processCreateParams(params) {
if (!params) return {};
const { errorMap, invalid_type_error, required_error, description } = params;
if (errorMap && (invalid_type_error || required_error)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
if (errorMap) return {
errorMap,
description
};
const customMap = (iss, ctx) => {
const { message } = params;
if (iss.code === "invalid_enum_value") return { message: message ?? ctx.defaultError };
if (typeof ctx.data === "undefined") return { message: message ?? required_error ?? ctx.defaultError };
if (iss.code !== "invalid_type") return { message: ctx.defaultError };
return { message: message ?? invalid_type_error ?? ctx.defaultError };
};
return {
errorMap: customMap,
description
};
}
var ZodType = class {
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) throw new Error("Synchronous parse encountered promise.");
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success) return result.data;
throw result.error;
}
safeParse(data, params) {
const ctx = {
common: {
issues: [],
async: params?.async ?? false,
contextualErrorMap: params?.errorMap
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result = this._parseSync({
data,
path: ctx.path,
parent: ctx
});
return handleResult(ctx, result);
}
"~validate"(data) {
const ctx = {
common: {
issues: [],
async: !!this["~standard"].async
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
if (!this["~standard"].async) try {
const result = this._parseSync({
data,
path: [],
parent: ctx
});
return isValid(result) ? { value: result.value } : { issues: ctx.common.issues };
} catch (err) {
if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true;
ctx.common = {
issues: [],
async: true
};
}
return this._parseAsync({
data,
path: [],
parent: ctx
}).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues });
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success) return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params?.errorMap,
async: true
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({
data,
path: ctx.path,
parent: ctx
});
const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") return { message };
else if (typeof message === "function") return message(val);
else return message;
};
return this._refinement((val, ctx) => {
const result = check(val);
const setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
if (typeof Promise !== "undefined" && result instanceof Promise) return result.then((data) => {
if (!data) {
setError();
return false;
} else return true;
});
if (!result) {
setError();
return false;
} else return true;
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else return true;
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: {
type: "refinement",
refinement
}
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def) {
/** Alias of safeParseAsync */
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data) => this["~validate"](data)
};
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: {
type: "transform",
transform
}
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
};
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex = /^[-+]?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)?)??$/;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex$1;
const ipv4Regex = /^(?:(?: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 ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/;
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
const dateRegexSource = `((\\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 dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let secondsRegexSource = `[0-5]\\d`;
if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
else if (args.precision == null) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
const secondsQuantifier = args.precision ? "+" : "?";
return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
if ((version === "v4" || !version) && ipv4Regex.test(ip)) return true;
if ((version === "v6" || !version) && ipv6Regex.test(ip)) return true;
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt)) return false;
try {
const [header] = jwt.split(".");
if (!header) return false;
const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
const decoded = JSON.parse(atob(base64));
if (typeof decoded !== "object" || decoded === null) return false;
if ("typ" in decoded && decoded?.typ !== "JWT") return false;
if (!decoded.alg) return false;
if (alg && decoded.alg !== alg) return false;
return true;
} catch {
return false;
}
}
function isValidCidr(ip, version) {
if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) return true;
if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) return true;
return false;
}
var ZodString = class ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = String(input.data);
if (this._getType(input) !== ZodParsedType.string) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx.parsedType
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
else if (tooSmall) addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
status.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex$1) emojiRegex$1 = new RegExp(_emojiRegex, "u");
if (!emojiRegex$1.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "url") try {
new URL(input.data);
} catch {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
else if (check.kind === "regex") {
check.regex.lastIndex = 0;
if (!check.regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "trim") input.data = input.data.trim();
else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: {
includes: check.value,
position: check.position
},
message: check.message
});
status.dirty();
}
} else if (check.kind === "toLowerCase") input.data = input.data.toLowerCase();
else if (check.kind === "toUpperCase") input.data = input.data.toUpperCase();
else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "datetime") {
if (!datetimeRegex(check).test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if (check.kind === "date") {
if (!dateRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
});
status.dirty();
}
} else if (check.kind === "time") {
if (!timeRegex(check).test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
});
status.dirty();
}
} else if (check.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "jwt") {
if (!isValidJWT(input.data, check.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cidr") {
if (!isValidCidr(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64url") {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else util.assertNever(check);
return {
status: status.value,
value: input.data
};
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message)
});
}
_addCheck(check) {
return new ZodString({
...this._def,
checks: [...this._def.checks, check]
});
}
email(message) {
return this._addCheck({
kind: "email",
...errorUtil.errToObj(message)
});
}
url(message) {
return this._addCheck({
kind: "url",
...errorUtil.errToObj(message)
});
}
emoji(message) {
return this._addCheck({
kind: "emoji",
...errorUtil.errToObj(message)
});
}
uuid(message) {
return this._addCheck({
kind: "uuid",
...errorUtil.errToObj(message)
});
}
nanoid(message) {
return this._addCheck({
kind: "nanoid",
...errorUtil.errToObj(message)
});
}
cuid(message) {
return this._addCheck({
kind: "cuid",
...errorUtil.errToObj(message)
});
}
cuid2(message) {
return this._addCheck({
kind: "cuid2",
...errorUtil.errToObj(message)
});
}
ulid(message) {
return this._addCheck({
kind: "ulid",
...errorUtil.errToObj(message)
});
}
base64(message) {
return this._addCheck({
kind: "base64",
...errorUtil.errToObj(message)
});
}
base64url(message) {
return this._addCheck({
kind: "base64url",
...errorUtil.errToObj(message)
});
}
jwt(options) {
return this._addCheck({
kind: "jwt",
...errorUtil.errToObj(options)
});
}
ip(options) {
return this._addCheck({
kind: "ip",
...errorUtil.errToObj(options)
});
}
cidr(options) {
return this._addCheck({
kind: "cidr",
...errorUtil.errToObj(options)
});
}
datetime(options) {
if (typeof options === "string") return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
return this._addCheck({
kind: "datetime",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
offset: options?.offset ?? false,
local: options?.local ?? false,
...errorUtil.errToObj(options?.message)
});
}
date(message) {
return this._addCheck({
kind: "date",
message
});
}
time(options) {
if (typeof options === "string") return this._addCheck({
kind: "time",
precision: null,
message: options
});
return this._addCheck({
kind: "time",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
...errorUtil.errToObj(options?.message)
});
}
duration(message) {
return this._addCheck({
kind: "duration",
...errorUtil.errToObj(message)
});
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options?.position,
...errorUtil.errToObj(options?.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
/**
* Equivalent to `.min(1)`
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isCIDR() {
return !!this._def.checks.find((ch) => ch.kind === "cidr");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get isBase64url() {
return !!this._def.checks.find((ch) => ch.kind === "base64url");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
};
ZodString.create = (params) => {
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
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;
}
var ZodNumber = class ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) input.data = Number(input.data);
if (this._getType(input) !== ZodParsedType.number) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx.parsedType
});
return INVALID;
}
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status.dirty();
}
} else if (check.kind === "min") {
if (check.inclusive ? input.data < check.value : input.data <= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (check.inclusive ? input.data > check.value : input.data >= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
});
status.dirty();
}
} else util.assertNever(check);
return {
status: status.value,
value: input.data
};
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodNumber({
...this._def,
checks: [...this._def.checks, {
kind,
value,
inclusive,
message: errorUtil.toString(message)
}]
});
}
_addCheck(check) {
return new ZodNumber({
...this._def,
checks: [...this._def.checks, check]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null;
let min = null;
for (const ch of this._def.checks) if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") return true;
else if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
var ZodBigInt = class ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) try {
input.data = BigInt(input.data);
} catch {
return this._getInvalidInput(input);
}
if (this._getType(input) !== ZodParsedType.bigint) return this._getInvalidInput(input);
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) if (check.kind === "min") {
if (check.inclusive ? input.data < check.value : input.data <= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (check.inclusive ? input.data > check.value : input.data >= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else util.assertNever(check);
return {
status: status.value,
value: input.data
};
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType
});
return INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodBigInt({
...this._def,
checks: [...this._def.checks, {
kind,
value,
inclusive,
message: errorUtil.toString(message)
}]
});
}
_addCheck(check) {
return new ZodBigInt({
...this._def,
checks: [...this._def.checks, check]
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
};
ZodBigInt.create = (params) => {
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
var ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = Boolean(input.data);
if (this._getType(input) !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
var ZodDate = class ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = new Date(input.data);
if (this._getType(input) !== ZodParsedType.date) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx.parsedType
});
return INVALID;
}
if (Number.isNaN(input.data.getTime())) {
addIssueToContext(this._getOrReturnCtx(input), { code: ZodIssueCode.invalid_date });
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status.dirty();
}
} else util.assertNever(check);
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check) {
return new ZodDate({
...this._def,
checks: [...this._def.checks, check]
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: params?.coerce || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
var ZodSymbol = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
};
var ZodUndefined = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
};
var ZodNull = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
};
var ZodAny = class extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
var ZodUnknown = class extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
var ZodNever = class extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
};
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
var ZodVoid = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
};
var ZodArray = class ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) return Promise.all([...ctx.data].map((item, i) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
})).then((result) => {
return ParseStatus.mergeArray(status, result);
});
const result = [...ctx.data].map((item, i) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new ZodArray({
...this._def,
minLength: {
value: minLength,
message: errorUtil.toString(message)
}
});
}
max(maxLength, message) {
return new ZodArray({
...this._def,
maxLength: {
value: maxLength,
message: errorUtil.toString(message)
}
});
}
length(len, message) {
return new ZodArray({
...this._def,
exactLength: {
value: len,
message: errorUtil.toString(message)
}
});
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray.create = (schema, params) => {
return new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
};
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: () => newShape
});
} else if (schema instanceof ZodArray) return new ZodArray({
...schema._def,
type: deepPartialify(schema.element)
});
else if (schema instanceof ZodOptional) return ZodOptional.create(deepPartialify(schema.unwrap()));
else if (schema instanceof ZodNullable) return ZodNullable.create(deepPartialify(schema.unwrap()));
else if (schema instanceof ZodTuple) return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
else return schema;
}
var ZodObject = class ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
/**
* @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
* If you want to pass through unknown properties, use `.passthrough()` instead.
*/
this.nonstrict = this.passthrough;
/**
* @deprecated Use `.extend` instead
* */
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null) return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
this._cached = {
shape,
keys
};
return this._cached;
}
_parse(input) {
if (this._getType(input) !== ZodParsedType.object) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key in ctx.data) if (!shapeKeys.includes(key)) extraKeys.push(key);
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: {
status: "valid",
value: key
},
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") for (const key of extraKeys) pairs.push({
key: {
status: "valid",
value: key
},
value: {
status: "valid",
value: ctx.data[key]
}
});
else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip") {} else throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: {
status: "valid",
value: key
},
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
}
if (ctx.common.async) return Promise.resolve().then(async () => {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
else return ParseStatus.mergeObjectSync(status, pairs);
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new ZodObject({
...this._def,
unknownKeys: "strict",
...message !== void 0 ? { errorMap: (issue, ctx) => {
const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
if (issue.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError };
return { message: defaultError };
} } : {}
});
}
strip() {
return new ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
extend(augmentation) {
return new ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation
})
});
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(merging) {
return new ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape()
}),
typeName: ZodFirstPartyTypeKind.ZodObject
});
}
setKey(key, schema) {
return this.augment({ [key]: schema });
}
catchall(index) {
return new ZodObject({
...this._def,
catchall: index
});
}
pick(mask) {
const shape = {};
for (const key of util.objectKeys(mask)) if (mask[key] && this.shape[key]) shape[key] = this.shape[key];
return new ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
const shape = {};
for (const key of util.objectKeys(this.shape)) if (!mask[key]) shape[key] = this.shape[key];
return new ZodObject({
...this._def,
shape: () => shape
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) newShape[key] = fieldSchema;
else newShape[key] = fieldSchema.optional();
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) if (mask && !mask[key]) newShape[key] = this.shape[key];
else {
let newField = this.shape[key];
while (newField instanceof ZodOptional) newField = newField._def.innerType;
newShape[key] = newField;
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
var ZodUnion = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) if (result.result.status === "valid") return result.result;
for (const result of results) if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
if (ctx.common.async) return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
else {
let dirty = void 0;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid") return result;
else if (result.status === "dirty" && !dirty) dirty = {
result,
ctx: childCtx
};
if (childCtx.common.issues.length) issues.push(childCtx.common.issues);
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues) => new ZodError(issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types, params) => {
return new ZodUnion({
options: types,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
};
const getDiscriminator = (type) => {
if (type instanceof ZodLazy) return getDiscriminator(type.schema);
else if (type instanceof ZodEffects) return getDiscriminator(type.innerType());
else if (type instanceof ZodLiteral) return [type.value];
else if (type instanceof ZodEnum) return type.options;
else if (type instanceof ZodNativeEnum) return util.objectValues(type.enum);
else if (type instanceof ZodDefault) return getDiscriminator(type._def.innerType);
else if (type instanceof ZodUndefined) return [void 0];
else if (type instanceof ZodNull) return [null];
else if (type instanceof ZodOptional) return [void 0, ...getDiscriminator(type.unwrap())];
else if (type instanceof ZodNullable) return [null, ...getDiscriminator(type.unwrap())];
else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap());
else if (type instanceof ZodReadonly) return getDiscriminator(type.unwrap());
else if (type instanceof ZodCatch) return getDiscriminator(type._def.innerType);
else return [];
};
var ZodDiscriminatedUnion = class ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
else return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
const optionsMap = /* @__PURE__ */ new Map();
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
for (const value of discriminatorValues) {
if (optionsMap.has(value)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
optionsMap.set(value, type);
}
}
return new ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
};
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) return {
valid: true,
data: a
};
else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = {
...a,
...b
};
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) return { valid: false };
newObj[key] = sharedValue.data;
}
return {
valid: true,
data: newObj
};
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) return { valid: false };
const newArray = [];
for (let index = 0; index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) return { valid: false };
newArray.push(sharedValue.data);
}
return {
valid: true,
data: newArray
};
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) return {
valid: true,
data: a
};
else return { valid: false };
}
var ZodIntersection = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID;
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types });
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) status.dirty();
return {
status: status.value,
value: merged.data
};
};
if (ctx.common.async) return Promise.all([this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})]).then(([left, right]) => handleParsed(left, right));
else return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
};
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
};
var ZodTuple = class ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
if (!this._def.rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema) return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x) => !!x);
if (ctx.common.async) return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
else return ParseStatus.mergeArray(status, items);
}
get items() {
return this._def.items;
}
rest(rest) {
return new ZodTuple({
...this._def,
rest
});
}
};
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params)
});
};
var ZodRecord = class ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data
});
if (ctx.common.async) return ParseStatus.mergeObjectAsync(status, pairs);
else return ParseStatus.mergeObjectSync(status, pairs);
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) return new ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
return new ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
};
var ZodMap = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
};
});
if (ctx.common.async) {
const finalMap = /* @__PURE__ */ new Map();
return Promise.resolve().then(async () => {
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
if (key.status === "aborted" || value.status === "aborted") return INVALID;
if (key.status === "dirty" || value.status === "dirty") status.dirty();
finalMap.set(key.value, value.value);
}
return {
status: status.value,
value: finalMap
};
});
} else {
const finalMap = /* @__PURE__ */ new Map();
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") return INVALID;
if (key.status === "dirty" || value.status === "dirty") status.dirty();
finalMap.set(key.value, value.value);
}
return {
status: status.value,
value: finalMap
};
}
}
};
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
};
var ZodSet = class ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements) {
const parsedSet = /* @__PURE__ */ new Set();
for (const element of elements) {
if (element.status === "aborted") return INVALID;
if (element.status === "dirty") status.dirty();
parsedSet.add(element.value);
}
return {
status: status.value,
value: parsedSet
};
}
const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
if (ctx.common.async) return Promise.all(elements).then((elements) => finalizeSet(elements));
else return finalizeSet(elements);
}
min(minSize, message) {
return new ZodSet({
...this._def,
minSize: {
value: minSize,
message: errorUtil.toString(message)
}
});
}
max(maxSize, message) {
return new ZodSet({
...this._def,
maxSize: {
value: maxSize,
message: errorUtil.toString(message)
}
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
};
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
};
var ZodFunction = class ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function(...args) {
const error = new ZodError([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
return await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
});
} else {
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
return this.parse(func);
}
strictImplement(func) {
return this.parse(func);
}
static create(args, returns, params) {
return new ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
};
var ZodLazy = class extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
return this._def.getter()._parse({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
};
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
};
var ZodLiteral = class extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return {
status: "valid",
value: input.data
};
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
};
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
var ZodEnum = class ZodEnum extends ZodType {
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) this._cache = new Set(this._def.values);
if (!this._cache.has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
extract(values, newDef = this._def) {
return ZodEnum.create(values, {
...this._def,
...newDef
});
}
exclude(values, newDef = this._def) {
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
...this._def,
...newDef
});
}
};
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) this._cache = new Set(util.getValidEnumValues(this._def.values));
if (!this._cache.has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
};
var ZodPromise = class extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
return OK((ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data)).then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
};
ZodPromise.create = (schema, params) => {
return new ZodPromise({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
};
var ZodEffects = class extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) status.abort();
else status.dirty();
},
get path() {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) return Promise.resolve(processed).then(async (processed) => {
if (status.value === "aborted") return INVALID;
const result = await this._def.schema._parseAsync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted") return INVALID;
if (result.status === "dirty") return DIRTY(result.value);
if (status.value === "dirty") return DIRTY(result.value);
return result;
});
else {
if (status.value === "aborted") return INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted") return INVALID;
if (result.status === "dirty") return DIRTY(result.value);
if (status.value === "dirty") return DIRTY(result.value);
return result;
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) return Promise.resolve(result);
if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inner.status === "aborted") return INVALID;
if (inner.status === "dirty") status.dirty();
executeRefinement(inner.value);
return {
status: status.value,
value: inner.value
};
} else return this._def.schema._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}).then((inner) => {
if (inner.status === "aborted") return INVALID;
if (inner.status === "dirty") status.dirty();
return executeRefinement(inner.value).then(() => {
return {
status: status.value,
value: inner.value
};
});
});
}
if (effect.type === "transform") if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base)) return INVALID;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
return {
status: status.value,
value: result
};
} else return this._def.schema._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}).then((base) => {
if (!isValid(base)) return INVALID;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
status: status.value,
value: result
}));
});
util.assertNever(effect);
}
};
ZodEffects.create = (schema, effect, params) => {
return new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects({
schema,
effect: {
type: "preprocess",
transform: preprocess
},
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
};
var ZodOptional = class extends ZodType {
_parse(input) {
if (this._getType(input) === ZodParsedType.undefined) return OK(void 0);
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type, params) => {
return new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
};
var ZodNullable = class extends ZodType {
_parse(input) {
if (this._getType(input) === ZodParsedType.null) return OK(null);
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type, params) => {
return new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
};
var ZodDefault = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) data = this._def.defaultValue();
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault.create = (type, params) => {
return new ZodDefault({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
...processCreateParams(params)
});
};
var ZodCatch = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: { ...newCtx }
});
if (isAsync(result)) return result.then((result) => {
return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
});
else return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
removeCatch() {
return this._def.innerType;
}
};
ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params)
});
};
var ZodNaN = class extends ZodType {
_parse(input) {
if (this._getType(input) !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return {
status: "valid",
value: input.data
};
}
};
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
};
var ZodBranded = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
};
var ZodPipeline = class ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted") return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
} else return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
};
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted") return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
static create(a, b) {
return new ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
};
var ZodReadonly = class extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze = (data) => {
if (isValid(data)) data.value = Object.freeze(data.value);
return data;
};
return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
};
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
};
ZodObject.lazycreate;
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind) {
ZodFirstPartyTypeKind["ZodString"] = "ZodString";
ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
ZodString.create;
ZodNumber.create;
ZodNaN.create;
ZodBigInt.create;
ZodBoolean.create;
ZodDate.create;
ZodSymbol.create;
ZodUndefined.create;
ZodNull.create;
ZodAny.create;
ZodUnknown.create;
ZodNever.create;
ZodVoid.create;
ZodArray.create;
ZodObject.create;
ZodObject.strictCreate;
ZodUnion.create;
ZodDiscriminatedUnion.create;
ZodIntersection.create;
ZodTuple.create;
ZodRecord.create;
ZodMap.create;
ZodSet.create;
ZodFunction.create;
ZodLazy.create;
ZodLiteral.create;
ZodEnum.create;
ZodNativeEnum.create;
ZodPromise.create;
ZodEffects.create;
ZodOptional.create;
ZodNullable.create;
ZodEffects.createWithPreprocess;
ZodPipeline.create;
//#endregion
//#region node_modules/eventsource-parser/dist/index.js
var ParseError = class extends Error {
constructor(message, options) {
super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
}
};
const LF = 10;
const CR = 13;
const SPACE = 32;
function noop(_arg) {}
function createParser(config) {
if (typeof config == "function") throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");
const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];
let pendingFragmentsLength = 0, isFirstChunk = !0, id, data = "", dataLines = 0, eventType, terminated = !1;
function feed(chunk) {
if (terminated) throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");
if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
const trailing2 = processLines(chunk);
trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
return;
}
if (chunk.indexOf(`
`) === -1 && chunk.indexOf("\r") === -1) {
pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
return;
}
pendingFragments.push(chunk);
const input = pendingFragments.join("");
pendingFragments.length = 0, pendingFragmentsLength = 0;
const trailing = processLines(input);
trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
}
function checkBufferSize() {
maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = !0, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, { type: "max-buffer-size-exceeded" }))));
}
function processLines(chunk) {
let searchIndex = 0;
if (chunk.indexOf("\r") === -1) {
let lfIndex = chunk.indexOf(`
`, searchIndex);
for (; lfIndex !== -1;) {
if (searchIndex === lfIndex) {
dataLines > 0 && onEvent({
id,
event: eventType,
data
}), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
`, searchIndex);
continue;
}
const firstCharCode = chunk.charCodeAt(searchIndex);
if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
onEvent({
id,
event: eventType,
data: value
}), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
`, searchIndex);
continue;
}
data = dataLines === 0 ? value : `${data}
${value}`, dataLines++;
} else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || void 0 : parseLine(chunk, searchIndex, lfIndex);
searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
`, searchIndex);
}
return chunk.slice(searchIndex);
}
for (; searchIndex < chunk.length;) {
const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
`, searchIndex);
let lineEnd = -1;
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break;
parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
}
return chunk.slice(searchIndex);
}
function parseLine(chunk, start, end) {
if (start === end) {
dispatchEvent();
return;
}
const firstCharCode = chunk.charCodeAt(start);
if (isDataPrefix(chunk, start, firstCharCode)) {
const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
data = dataLines === 0 ? value2 : `${data}
${value2}`, dataLines++;
return;
}
if (isEventPrefix(chunk, start, firstCharCode)) {
eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
return;
}
if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
id = value2.includes("\0") ? void 0 : value2;
return;
}
if (firstCharCode === 58) {
if (onComment) {
const line2 = chunk.slice(start, end);
onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
}
return;
}
const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
if (fieldSeparatorIndex === -1) {
processField(line, "", line);
return;
}
const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;
processField(field, line.slice(fieldSeparatorIndex + offset), line);
}
function processField(field, value, line) {
switch (field) {
case "event":
eventType = value || void 0;
break;
case "data":
data = dataLines === 0 ? value : `${data}
${value}`, dataLines++;
break;
case "id":
id = value.includes("\0") ? void 0 : value;
break;
case "retry":
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
type: "invalid-retry",
value,
line
}));
break;
default:
onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, {
type: "unknown-field",
field,
value,
line
}));
break;
}
}
function dispatchEvent() {
dataLines > 0 && onEvent({
id,
event: eventType,
data
}), id = void 0, data = "", dataLines = 0, eventType = void 0;
}
function reset(options = {}) {
if (options.consume && pendingFragments.length > 0) {
const incompleteLine = pendingFragments.join("");
parseLine(incompleteLine, 0, incompleteLine.length);
}
isFirstChunk = !0, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = !1;
}
return {
feed,
reset
};
}
function isDataPrefix(chunk, i, firstCharCode) {
return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
}
function isEventPrefix(chunk, i, firstCharCode) {
return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
}
//#endregion
//#region node_modules/eventsource-parser/dist/stream.js
var EventSourceParserStream = class extends TransformStream {
constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
let parser;
super({
start(controller) {
parser = createParser({
onEvent: (event) => {
controller.enqueue(event);
},
onError(error) {
typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
},
onRetry,
onComment,
maxBufferSize
});
},
transform(chunk) {
parser.feed(chunk);
}
});
}
};
//#endregion
//#region node_modules/@workflow/serde/dist/index.js
/**
* Symbol used to define custom serialization for user-defined class instances.
* The static method should accept an instance and return serializable data.
*
* @example
* ```ts
* import { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from '@workflow/serde';
*
* class MyClass {
* constructor(public value: string) {}
*
* static [WORKFLOW_SERIALIZE](instance: MyClass) {
* return { value: instance.value };
* }
*
* static [WORKFLOW_DESERIALIZE](data: { value: string }) {
* return new MyClass(data.value);
* }
* }
* ```
*/
const WORKFLOW_SERIALIZE = Symbol.for("workflow-serialize");
/**
* Symbol used to define custom deserialization for user-defined class instances.
* The static method should accept serialized data and return a class instance.
*
* @see WORKFLOW_SERIALIZE for usage example
*/
const WORKFLOW_DESERIALIZE = Symbol.for("workflow-deserialize");
//#endregion
//#region node_modules/@ai-sdk/provider-utils/dist/index.js
function asArray(value) {
return value === void 0 ? [] : Array.isArray(value) ? value : [value];
}
function combineHeaders(...headers) {
return headers.reduce((combinedHeaders, currentHeaders) => ({
...combinedHeaders,
...currentHeaders != null ? currentHeaders : {}
}), {});
}
function removeUndefinedEntries(record) {
return Object.fromEntries(Object.entries(record).filter(([_key, value]) => value != null));
}
async function delay(delayInMs, options) {
if (delayInMs == null) return Promise.resolve();
const signal = options == null ? void 0 : options.abortSignal;
return new Promise((resolve2, reject) => {
if (signal == null ? void 0 : signal.aborted) {
reject(createAbortError());
return;
}
const timeoutId = setTimeout(() => {
cleanup();
resolve2();
}, delayInMs);
const cleanup = () => {
clearTimeout(timeoutId);
signal?.removeEventListener("abort", onAbort);
};
const onAbort = () => {
cleanup();
reject(createAbortError());
};
signal?.addEventListener("abort", onAbort);
});
}
function createAbortError() {
return new DOMException("Delay was aborted", "AbortError");
}
function getWebSocketConstructor(webSocket) {
const WebSocketConstructor = webSocket != null ? webSocket : globalThis.WebSocket;
if (WebSocketConstructor == null) throw new Error("No WebSocket implementation available.");
return WebSocketConstructor;
}
var textDecoder = new TextDecoder();
async function readWebSocketMessageText(data) {
if (typeof data === "string") return data;
if (data instanceof ArrayBuffer) return textDecoder.decode(data);
if (ArrayBuffer.isView(data)) return textDecoder.decode(data);
if (typeof Blob !== "undefined" && data instanceof Blob) return data.text();
return String(data);
}
var WEBSOCKET_OPEN_STATE = 1;
async function waitForWebSocketBufferDrain(socket, { highWaterMark = 1024 * 1024, pollIntervalMs = 20, abortSignal } = {}) {
var _a2;
while (socket.readyState === WEBSOCKET_OPEN_STATE && ((_a2 = socket.bufferedAmount) != null ? _a2 : 0) > highWaterMark) {
if ((abortSignal == null ? void 0 : abortSignal.aborted) === true) return;
await delay(pollIntervalMs);
}
}
function connectToWebSocket({ url, protocols, headers, webSocket, abortSignal, onOpen, onMessageText, onProcessingError, onSocketError, onClose, onAbort }) {
var _a2;
let socket;
let abortListener;
const close = (code) => {
if (abortListener != null) {
abortSignal?.removeEventListener("abort", abortListener);
abortListener = void 0;
}
try {
socket?.close(code);
} catch (e) {}
};
if (abortSignal == null ? void 0 : abortSignal.aborted) {
onAbort?.((_a2 = abortSignal.reason) != null ? _a2 : /* @__PURE__ */ new Error("Aborted"));
return {
socket: void 0,
close
};
}
try {
socket = new (getWebSocketConstructor(webSocket))(url, protocols, { headers: removeUndefinedEntries(headers != null ? headers : {}) });
} catch (error) {
onProcessingError(error);
return {
socket: void 0,
close
};
}
if (abortSignal != null && onAbort != null) {
abortListener = () => {
var _a3;
return onAbort((_a3 = abortSignal.reason) != null ? _a3 : /* @__PURE__ */ new Error("Aborted"));
};
abortSignal.addEventListener("abort", abortListener, { once: true });
}
const openedSocket = socket;
socket.onopen = () => {
try {
onOpen?.(openedSocket);
} catch (error) {
onProcessingError(error);
}
};
let tail = Promise.resolve();
socket.onmessage = (event) => {
tail = tail.then(() => readWebSocketMessageText(event.data)).then((text) => onMessageText(text)).catch(onProcessingError);
};
socket.onerror = () => {
tail = tail.then(() => onSocketError == null ? void 0 : onSocketError()).catch(onProcessingError);
};
socket.onclose = () => {
tail = tail.then(() => onClose == null ? void 0 : onClose()).catch(onProcessingError);
};
return {
socket,
close
};
}
var { btoa: btoa$1, atob: atob$1 } = globalThis;
function convertBase64ToUint8Array(base64String) {
const latin1string = atob$1(base64String.replace(/-/g, "+").replace(/_/g, "/"));
return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
}
function convertUint8ArrayToBase64(array) {
let latin1string = "";
for (let i = 0; i < array.length; i++) latin1string += String.fromCodePoint(array[i]);
return btoa$1(latin1string);
}
var DelayedPromise = class {
constructor() {
this.status = { type: "pending" };
this._resolve = void 0;
this._reject = void 0;
}
get promise() {
if (this._promise) return this._promise;
this._promise = new Promise((resolve2, reject) => {
if (this.status.type === "resolved") resolve2(this.status.value);
else if (this.status.type === "rejected") reject(this.status.error);
this._resolve = resolve2;
this._reject = reject;
});
return this._promise;
}
resolve(value) {
var _a2;
this.status = {
type: "resolved",
value
};
if (this._promise) (_a2 = this._resolve) == null || _a2.call(this, value);
}
reject(error) {
var _a2;
this.status = {
type: "rejected",
error
};
if (this._promise) (_a2 = this._reject) == null || _a2.call(this, error);
}
isResolved() {
return this.status.type === "resolved";
}
isRejected() {
return this.status.type === "rejected";
}
isPending() {
return this.status.type === "pending";
}
};
var imageMediaTypeSignatures = [
{
mediaType: "image/gif",
bytesPrefix: [
71,
73,
70
]
},
{
mediaType: "image/png",
bytesPrefix: [
137,
80,
78,
71
]
},
{
mediaType: "image/jpeg",
bytesPrefix: [255, 216]
},
{
mediaType: "image/webp",
bytesPrefix: [
82,
73,
70,
70,
null,
null,
null,
null,
87,
69,
66,
80
]
},
{
mediaType: "image/bmp",
bytesPrefix: [66, 77]
},
{
mediaType: "image/tiff",
bytesPrefix: [
73,
73,
42,
0
]
},
{
mediaType: "image/tiff",
bytesPrefix: [
77,
77,
0,
42
]
},
{
mediaType: "image/avif",
bytesPrefix: [
0,
0,
0,
32,
102,
116,
121,
112,
97,
118,
105,
102
]
},
{
mediaType: "image/heic",
bytesPrefix: [
0,
0,
0,
32,
102,
116,
121,
112,
104,
101,
105,
99
]
}
];
var documentMediaTypeSignatures = [{
mediaType: "application/pdf",
bytesPrefix: [
37,
80,
68,
70
]
}];
var audioMediaTypeSignatures = [
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 251]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 250]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 243]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 242]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 227]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 226]
},
{
mediaType: "audio/wav",
bytesPrefix: [
82,
73,
70,
70,
null,
null,
null,
null,
87,
65,
86,
69
]
},
{
mediaType: "audio/ogg",
bytesPrefix: [
79,
103,
103,
83
]
},
{
mediaType: "audio/flac",
bytesPrefix: [
102,
76,
97,
67
]
},
{
mediaType: "audio/aac",
bytesPrefix: [
64,
21,
0,
0
]
},
{
mediaType: "audio/mp4",
bytesPrefix: [
102,
116,
121,
112
]
},
{
mediaType: "audio/webm",
bytesPrefix: [
26,
69,
223,
163
]
}
];
var videoMediaTypeSignatures = [
{
mediaType: "video/mp4",
bytesPrefix: [
0,
0,
0,
null,
102,
116,
121,
112
]
},
{
mediaType: "video/webm",
bytesPrefix: [
26,
69,
223,
163
]
},
{
mediaType: "video/quicktime",
bytesPrefix: [
0,
0,
0,
20,
102,
116,
121,
112,
113,
116
]
},
{
mediaType: "video/x-msvideo",
bytesPrefix: [
82,
73,
70,
70
]
}
];
var stripID3 = (data) => {
const bytes = typeof data === "string" ? convertBase64ToUint8Array(data) : data;
const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
return bytes.slice(id3Size + 10);
};
function stripID3TagsIfPresent(data) {
return typeof data === "string" && data.startsWith("SUQz") || typeof data !== "string" && data.length > 10 && data[0] === 73 && data[1] === 68 && data[2] === 51 ? stripID3(data) : data;
}
function detectMediaTypeBySignatures({ data, signatures }) {
const processedData = stripID3TagsIfPresent(data);
const bytes = typeof processedData === "string" ? convertBase64ToUint8Array(processedData.substring(0, Math.min(processedData.length, 24))) : processedData;
for (const signature of signatures) if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => byte === null || bytes[index] === byte)) return signature.mediaType;
}
var topLevelSignatureTables = {
image: imageMediaTypeSignatures,
audio: audioMediaTypeSignatures,
video: videoMediaTypeSignatures,
application: documentMediaTypeSignatures
};
function detectMediaType({ data, topLevelType }) {
if (topLevelType === void 0) return detectMediaTypeBySignatures({
data,
signatures: [
...imageMediaTypeSignatures,
...documentMediaTypeSignatures,
...audioMediaTypeSignatures,
...videoMediaTypeSignatures
]
});
const signatures = topLevelSignatureTables[topLevelType];
if (signatures === void 0) return;
return detectMediaTypeBySignatures({
data,
signatures
});
}
function isFullMediaType(mediaType) {
const slashIndex = mediaType.indexOf("/");
if (slashIndex === -1) return false;
const subtype = mediaType.substring(slashIndex + 1);
return subtype.length > 0 && subtype !== "*";
}
async function cancelResponseBody(response) {
var _a2;
try {
await ((_a2 = response.body) == null ? void 0 : _a2.cancel());
} catch (e) {}
}
var name$1 = "AI_DownloadError";
var marker = `vercel.ai.error.${name$1}`;
var symbol$1 = Symbol.for(marker);
var _a$1;
var _b$1;
var DownloadError = class extends (_b$1 = AISDKError, _a$1 = symbol$1, _b$1) {
constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {
super({
name: name$1,
message,
cause
});
this[_a$1] = true;
this.url = url;
this.statusCode = statusCode;
this.statusText = statusText;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker);
}
};
function isBrowserRuntime(globalThisAny = globalThis) {
return globalThisAny.window != null;
}
function isSameOrigin(url, baseUrl) {
try {
return new URL(url).origin === new URL(baseUrl).origin;
} catch (e) {
return false;
}
}
var BLOCKED_REQUEST_HEADERS = [
"connection",
"keep-alive",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"host",
"forwarded",
"proxy-authorization",
"via",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-proto",
"x-real-ip",
"metadata",
"metadata-flavor",
"x-aws-ec2-metadata-token",
"x-metadata-token",
"cookie",
"set-cookie"
];
function sanitizeRequestHeaders(input) {
const headers = new Headers(input);
for (const name2 of BLOCKED_REQUEST_HEADERS) headers.delete(name2);
return headers;
}
function validateDownloadUrl(url) {
let parsed;
try {
parsed = new URL(url);
} catch (e) {
throw new DownloadError({
url,
message: `Invalid URL: ${url}`
});
}
if (parsed.protocol === "data:") return;
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new DownloadError({
url,
message: `URL scheme must be http, https, or data, got ${parsed.protocol}`
});
const hostname = parsed.hostname.toLowerCase().replace(/\.+$/, "");
if (!hostname) throw new DownloadError({
url,
message: `URL must have a hostname`
});
if (hostname === "localhost" || hostname.endsWith(".local") || hostname.endsWith(".localhost")) throw new DownloadError({
url,
message: `URL with hostname ${hostname} is not allowed`
});
if (hostname.startsWith("[") && hostname.endsWith("]")) {
if (isPrivateIPv6(hostname.slice(1, -1))) throw new DownloadError({
url,
message: `URL with IPv6 address ${hostname} is not allowed`
});
return;
}
if (isIPv4(hostname)) {
if (isPrivateIPv4(hostname)) throw new DownloadError({
url,
message: `URL with IP address ${hostname} is not allowed`
});
return;
}
}
function isIPv4(hostname) {
const parts = hostname.split(".");
if (parts.length !== 4) return false;
return parts.every((part) => {
const num = Number(part);
return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;
});
}
function isPrivateIPv4(ip) {
const [a, b, c] = ip.split(".").map(Number);
if (a === 0) return true;
if (a === 10) return true;
if (a === 100 && b >= 64 && b <= 127) return true;
if (a === 127) return true;
if (a === 169 && b === 254) return true;
if (a === 172 && b >= 16 && b <= 31) return true;
if (a === 192 && b === 0 && c === 0) return true;
if (a === 192 && b === 0 && c === 2) return true;
if (a === 192 && b === 168) return true;
if (a === 198 && (b === 18 || b === 19)) return true;
if (a === 198 && b === 51 && c === 100) return true;
if (a === 203 && b === 0 && c === 113) return true;
if (a >= 224) return true;
return false;
}
function parseIPv6(ip) {
let address = ip.toLowerCase();
const zoneIndex = address.indexOf("%");
if (zoneIndex !== -1) address = address.slice(0, zoneIndex);
const halves = address.split("::");
if (halves.length > 2) return null;
const toGroups = (segment) => {
if (segment === "") return [];
const groups = [];
const parts = segment.split(":");
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.includes(".")) {
if (i !== parts.length - 1 || !isIPv4(part)) return null;
const [a, b, c, d] = part.split(".").map(Number);
groups.push(a << 8 | b, c << 8 | d);
continue;
}
if (!/^[0-9a-f]{1,4}$/.test(part)) return null;
groups.push(parseInt(part, 16));
}
return groups;
};
const head = toGroups(halves[0]);
if (head === null) return null;
if (halves.length === 2) {
const tail = toGroups(halves[1]);
if (tail === null) return null;
const fill = 8 - head.length - tail.length;
if (fill < 0) return null;
return [
...head,
...new Array(fill).fill(0),
...tail
];
}
return head.length === 8 ? head : null;
}
function isPrivateIPv6(ip) {
const groups = parseIPv6(ip);
if (groups === null) return true;
const topZero = (count) => groups.slice(0, count).every((group) => group === 0);
if (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true;
if ((groups[0] & 65024) === 64512) return true;
if ((groups[0] & 65472) === 65152) return true;
if ((groups[0] & 65472) === 65216) return true;
if ((groups[0] & 65280) === 65280) return true;
if (groups[0] === 8193 && groups[1] === 3512) return true;
if (groups[0] === 16383 && (groups[1] & 61440) === 0) return true;
if (topZero(6) || topZero(5) && groups[5] === 65535 || topZero(4) && groups[4] === 65535 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 1) return isPrivateIPv4(`${groups[6] >> 8 & 255}.${groups[6] & 255}.${groups[7] >> 8 & 255}.${groups[7] & 255}`);
return false;
}
var MAX_DOWNLOAD_REDIRECTS = 10;
var REDIRECT_STATUS_CODES = /* @__PURE__ */ new Set([
301,
302,
303,
307,
308
]);
async function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects = MAX_DOWNLOAD_REDIRECTS, fetch = globalThis.fetch, trustedOrigin }) {
let currentHeaders = headers === void 0 ? void 0 : sanitizeRequestHeaders(headers);
const perHopInit = (redirect) => {
const init = {
signal: abortSignal,
redirect
};
if (currentHeaders !== void 0) init.headers = new Headers(currentHeaders);
return init;
};
let currentUrl = url;
for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {
if (trustedOrigin === void 0 || !isSameOrigin(currentUrl, trustedOrigin)) validateDownloadUrl(currentUrl);
const response = await fetch(currentUrl, perHopInit("manual"));
if (response.type === "opaqueredirect") {
if (!isBrowserRuntime()) throw new DownloadError({
url,
message: `Redirect from ${currentUrl} could not be validated and was blocked`
});
return await fetch(currentUrl, perHopInit("follow"));
}
const location = response.headers.get("location");
if (REDIRECT_STATUS_CODES.has(response.status) && location) {
await cancelResponseBody(response);
const nextUrl = new URL(location, currentUrl).toString();
if (currentHeaders !== void 0 && !isSameOrigin(nextUrl, currentUrl)) {
const userAgent = currentHeaders.get("user-agent");
currentHeaders = new Headers(userAgent == null ? void 0 : { "user-agent": userAgent });
}
currentUrl = nextUrl;
continue;
}
return response;
}
throw new DownloadError({
url,
message: `Too many redirects (max ${maxRedirects})`
});
}
async function readResponseWithSizeLimit({ response, url, maxBytes = 2147483648 }) {
const contentLength = response.headers.get("content-length");
if (contentLength != null) {
const length = parseInt(contentLength, 10);
if (!isNaN(length) && length > maxBytes) {
await cancelResponseBody(response);
throw new DownloadError({
url,
message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`
});
}
}
const body = response.body;
if (body == null) return /* @__PURE__ */ new Uint8Array(0);
const reader = body.getReader();
const chunks = [];
let totalBytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.length;
if (totalBytes > maxBytes) throw new DownloadError({
url,
message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`
});
chunks.push(value);
}
} finally {
try {
await reader.cancel();
} finally {
reader.releaseLock();
}
}
const result = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
function extractResponseHeaders(response) {
return Object.fromEntries([...response.headers]);
}
function filterNullable(...values) {
return values.filter((value) => value != null);
}
var createIdGenerator = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => {
const generator = () => {
const alphabetLength = alphabet.length;
const chars = new Array(size);
for (let i = 0; i < size; i++) chars[i] = alphabet[Math.random() * alphabetLength | 0];
return chars.join("");
};
if (prefix == null) return generator;
if (alphabet.includes(separator)) throw new InvalidArgumentError({
argument: "separator",
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
});
return () => `${prefix}${separator}${generator()}`;
};
createIdGenerator();
function isAbortError(error) {
return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
}
var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
var BUN_ERROR_CODES = [
"ConnectionRefused",
"ConnectionClosed",
"FailedToOpenSocket",
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"EPIPE"
];
function isBunNetworkError(error) {
if (!(error instanceof Error)) return false;
const code = error.code;
if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) return true;
return false;
}
function handleFetchError({ error, url, requestBodyValues }) {
if (isAbortError(error)) return error;
if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
const cause = error.cause;
if (cause != null) return new APICallError({
message: `Cannot connect to API: ${cause.message}`,
cause,
url,
requestBodyValues,
isRetryable: true
});
}
if (isBunNetworkError(error)) return new APICallError({
message: `Cannot connect to API: ${error.message}`,
cause: error,
url,
requestBodyValues,
isRetryable: true
});
return error;
}
function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
var _a2, _b2, _c;
if (globalThisAny.window) return `runtime/browser`;
if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;
if (globalThisAny.EdgeRuntime) return `runtime/vercel-edge`;
return "runtime/unknown";
}
function normalizeHeaders(headers) {
if (headers == null) return {};
const normalized = {};
if (headers instanceof Headers) headers.forEach((value, key) => {
normalized[key.toLowerCase()] = value;
});
else {
if (!Array.isArray(headers)) headers = Object.entries(headers);
for (const [key, value] of headers) if (value != null) normalized[key.toLowerCase()] = value;
}
return normalized;
}
function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
const normalizedHeaders = new Headers(normalizeHeaders(headers));
const currentUserAgentHeader = normalizedHeaders.get("user-agent") || "";
normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
return Object.fromEntries(normalizedHeaders.entries());
}
var getOriginalFetch = () => globalThis.fetch;
var getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch(), validateUrl, credentialedOrigin, trustedOrigin }) => {
try {
const requestHeaders = withUserAgentSuffix(credentialedOrigin !== void 0 && !isSameOrigin(url, credentialedOrigin) ? {} : headers, `ai-sdk/provider-utils/5.0.10`, getRuntimeEnvironmentUserAgent());
const response = validateUrl ? await fetchWithValidatedRedirects({
url,
headers: requestHeaders,
abortSignal,
fetch,
trustedOrigin
}) : await fetch(url, {
method: "GET",
headers: requestHeaders,
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
throw new APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
}
throw new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
} catch (error) {
throw handleFetchError({
error,
url,
requestBodyValues: {}
});
}
};
function isBuffer(value) {
var _a2, _b2;
return (_b2 = (_a2 = globalThis.Buffer) == null ? void 0 : _a2.isBuffer(value)) != null ? _b2 : false;
}
function isProviderReference(data) {
return typeof data === "object" && data !== null && !(data instanceof Uint8Array) && !(data instanceof URL) && !(data instanceof ArrayBuffer) && !isBuffer(data) && !("type" in data);
}
function isUrlSupported({ mediaType, url, supportedUrls }) {
url = url.toLowerCase();
mediaType = mediaType.toLowerCase();
const isTopLevelOnly = !mediaType.includes("/");
return Object.entries(supportedUrls).map(([key, value]) => {
const mediaType2 = key.toLowerCase();
return mediaType2 === "*" || mediaType2 === "*/*" ? {
mediaTypePrefix: "",
regexes: value
} : {
mediaTypePrefix: mediaType2.replace(/\*/, ""),
regexes: value
};
}).filter(({ mediaTypePrefix }) => {
if (mediaTypePrefix === "") return true;
if (isTopLevelOnly) return `${mediaType}/` === mediaTypePrefix;
return mediaType.startsWith(mediaTypePrefix);
}).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));
}
function loadOptionalSetting({ settingValue, environmentVariableName }) {
if (typeof settingValue === "string") return settingValue;
if (settingValue != null || typeof process === "undefined") return;
settingValue = process.env[environmentVariableName];
if (settingValue == null || typeof settingValue !== "string") return;
return settingValue;
}
var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
function _parse(text) {
const obj = JSON.parse(text);
if (obj === null || typeof obj !== "object") return obj;
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) return obj;
return filter(obj);
}
function filter(obj) {
let next = [obj];
while (next.length) {
const nodes = next;
next = [];
for (const node of nodes) {
if (Object.prototype.hasOwnProperty.call(node, "__proto__")) throw new SyntaxError("Object contains forbidden prototype property");
if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) throw new SyntaxError("Object contains forbidden prototype property");
for (const key in node) {
const value = node[key];
if (value && typeof value === "object") next.push(value);
}
}
}
return obj;
}
function secureJsonParse(text) {
const { stackTraceLimit } = Error;
try {
Error.stackTraceLimit = 0;
} catch (e) {
return _parse(text);
}
try {
return _parse(text);
} finally {
Error.stackTraceLimit = stackTraceLimit;
}
}
function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
jsonSchema2.additionalProperties = false;
const { properties } = jsonSchema2;
if (properties != null) for (const key of Object.keys(properties)) properties[key] = visit(properties[key]);
}
if (jsonSchema2.items != null) jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
if (jsonSchema2.anyOf != null) jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
if (jsonSchema2.allOf != null) jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
if (jsonSchema2.oneOf != null) jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
const { definitions } = jsonSchema2;
if (definitions != null) for (const key of Object.keys(definitions)) definitions[key] = visit(definitions[key]);
return jsonSchema2;
}
function visit(def) {
if (typeof def === "boolean") return def;
return addAdditionalPropertiesToJsonSchema(def);
}
var ignoreOverride = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions = {
name: void 0,
$refStrategy: "root",
basePath: ["#"],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: true,
rejectedAdditionalProperties: false,
definitionPath: "definitions",
strictUnions: false,
definitions: {},
errorMessages: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref"
};
var getDefaultOptions = (options) => typeof options === "string" ? {
...defaultOptions,
name: options
} : {
...defaultOptions,
...options
};
function parseAnyDef() {
return {};
}
function parseArrayDef(def, refs) {
var _a2, _b2, _c;
const res = { type: "array" };
if (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
});
if (def.minLength) res.minItems = def.minLength.value;
if (def.maxLength) res.maxItems = def.maxLength.value;
if (def.exactLength) {
res.minItems = def.exactLength.value;
res.maxItems = def.exactLength.value;
}
return res;
}
function parseBigintDef(def) {
const res = {
type: "integer",
format: "int64"
};
if (!def.checks) return res;
for (const check of def.checks) switch (check.kind) {
case "min":
if (check.inclusive) res.minimum = check.value;
else res.exclusiveMinimum = check.value;
break;
case "max":
if (check.inclusive) res.maximum = check.value;
else res.exclusiveMaximum = check.value;
break;
case "multipleOf":
res.multipleOf = check.value;
break;
}
return res;
}
function parseBooleanDef() {
return { type: "boolean" };
}
function parseBrandedDef(_def, refs) {
return parseDef(_def.type._def, refs);
}
var parseCatchDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
function parseDateDef(def, refs, overrideDateStrategy) {
const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
if (Array.isArray(strategy)) return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) };
switch (strategy) {
case "string":
case "format:date-time": return {
type: "string",
format: "date-time"
};
case "format:date": return {
type: "string",
format: "date"
};
case "integer": return integerDateParser(def);
}
}
var integerDateParser = (def) => {
const res = {
type: "integer",
format: "unix-time"
};
for (const check of def.checks) switch (check.kind) {
case "min":
res.minimum = check.value;
break;
case "max":
res.maximum = check.value;
break;
}
return res;
};
function parseDefaultDef(_def, refs) {
return {
...parseDef(_def.innerType._def, refs),
default: _def.defaultValue()
};
}
function parseEffectsDef(_def, refs) {
return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
}
function parseEnumDef(def) {
return {
type: "string",
enum: Array.from(def.values)
};
}
var isJsonSchema7AllOfType = (type) => {
if ("type" in type && type.type === "string") return false;
return "allOf" in type;
};
function parseIntersectionDef(def, refs) {
const allOf = [parseDef(def.left._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
}), parseDef(def.right._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"1"
]
})].filter((x) => !!x);
const mergedAllOf = [];
allOf.forEach((schema) => {
if (isJsonSchema7AllOfType(schema)) mergedAllOf.push(...schema.allOf);
else {
let nestedSchema = schema;
if ("additionalProperties" in schema && schema.additionalProperties === false) {
const { additionalProperties: _additionalProperties, ...rest } = schema;
nestedSchema = rest;
}
mergedAllOf.push(nestedSchema);
}
});
return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
}
function parseLiteralDef(def) {
const parsedType = typeof def.value;
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" };
return {
type: parsedType === "bigint" ? "integer" : parsedType,
const: def.value
};
}
var emojiRegex = void 0;
var zodPatterns = {
/**
* `c` was changed to `[cC]` to replicate /i flag
*/
cuid: /^[cC][^\s-]{8,}$/,
cuid2: /^[0-9a-z]+$/,
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
/**
* `a-z` was added to replicate /i flag
*/
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
/**
* Constructed a valid Unicode RegExp
*
* Lazily instantiate since this type of regex isn't supported
* in all envs (e.g. React Native).
*
* See:
* https://github.com/colinhacks/zod/issues/2433
* Fix in Zod:
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
*/
emoji: () => {
if (emojiRegex === void 0) emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
return emojiRegex;
},
/**
* Unused
*/
uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
/**
* Unused
*/
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])$/,
ipv4Cidr: /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,
/**
* Unused
*/
ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
nanoid: /^[a-zA-Z0-9_-]{21}$/,
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
};
function parseStringDef(def, refs) {
const res = { type: "string" };
if (def.checks) for (const check of def.checks) switch (check.kind) {
case "min":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
break;
case "max":
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
break;
case "email":
switch (refs.emailStrategy) {
case "format:email":
addFormat(res, "email", check.message, refs);
break;
case "format:idn-email":
addFormat(res, "idn-email", check.message, refs);
break;
case "pattern:zod":
addPattern(res, zodPatterns.email, check.message, refs);
break;
}
break;
case "url":
addFormat(res, "uri", check.message, refs);
break;
case "uuid":
addFormat(res, "uuid", check.message, refs);
break;
case "regex":
addPattern(res, check.regex, check.message, refs);
break;
case "cuid":
addPattern(res, zodPatterns.cuid, check.message, refs);
break;
case "cuid2":
addPattern(res, zodPatterns.cuid2, check.message, refs);
break;
case "startsWith":
addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
break;
case "endsWith":
addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
break;
case "datetime":
addFormat(res, "date-time", check.message, refs);
break;
case "date":
addFormat(res, "date", check.message, refs);
break;
case "time":
addFormat(res, "time", check.message, refs);
break;
case "duration":
addFormat(res, "duration", check.message, refs);
break;
case "length":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
break;
case "includes":
addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
break;
case "ip":
if (check.version !== "v6") addFormat(res, "ipv4", check.message, refs);
if (check.version !== "v4") addFormat(res, "ipv6", check.message, refs);
break;
case "base64url":
addPattern(res, zodPatterns.base64url, check.message, refs);
break;
case "jwt":
addPattern(res, zodPatterns.jwt, check.message, refs);
break;
case "cidr":
if (check.version !== "v6") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
if (check.version !== "v4") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
break;
case "emoji":
addPattern(res, zodPatterns.emoji(), check.message, refs);
break;
case "ulid":
addPattern(res, zodPatterns.ulid, check.message, refs);
break;
case "base64":
switch (refs.base64Strategy) {
case "format:binary":
addFormat(res, "binary", check.message, refs);
break;
case "contentEncoding:base64":
res.contentEncoding = "base64";
break;
case "pattern:zod":
addPattern(res, zodPatterns.base64, check.message, refs);
break;
}
break;
case "nanoid": addPattern(res, zodPatterns.nanoid, check.message, refs);
case "toLowerCase":
case "toUpperCase":
case "trim": break;
default:
}
return res;
}
function escapeLiteralCheckValue(literal, refs) {
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
}
var ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric(source) {
let result = "";
for (let i = 0; i < source.length; i++) {
if (!ALPHA_NUMERIC.has(source[i])) result += "\\";
result += source[i];
}
return result;
}
function addFormat(schema, value, message, refs) {
var _a2;
if (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {
if (!schema.anyOf) schema.anyOf = [];
if (schema.format) {
schema.anyOf.push({ format: schema.format });
delete schema.format;
}
schema.anyOf.push({
format: value,
...message && refs.errorMessages && { errorMessage: { format: message } }
});
} else schema.format = value;
}
function addPattern(schema, regex, message, refs) {
var _a2;
if (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {
if (!schema.allOf) schema.allOf = [];
if (schema.pattern) {
schema.allOf.push({ pattern: schema.pattern });
delete schema.pattern;
}
schema.allOf.push({
pattern: stringifyRegExpWithFlags(regex, refs),
...message && refs.errorMessages && { errorMessage: { pattern: message } }
});
} else schema.pattern = stringifyRegExpWithFlags(regex, refs);
}
function stringifyRegExpWithFlags(regex, refs) {
var _a2;
if (!refs.applyRegexFlags || !regex.flags) return regex.source;
const flags = {
i: regex.flags.includes("i"),
m: regex.flags.includes("m"),
s: regex.flags.includes("s")
};
const source = flags.i ? regex.source.toLowerCase() : regex.source;
let pattern = "";
let isEscaped = false;
let inCharGroup = false;
let inCharRange = false;
for (let i = 0; i < source.length; i++) {
if (isEscaped) {
pattern += source[i];
isEscaped = false;
continue;
}
if (flags.i) {
if (inCharGroup) {
if (source[i].match(/[a-z]/)) {
if (inCharRange) {
pattern += source[i];
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
inCharRange = false;
} else if (source[i + 1] === "-" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {
pattern += source[i];
inCharRange = true;
} else pattern += `${source[i]}${source[i].toUpperCase()}`;
continue;
}
} else if (source[i].match(/[a-z]/)) {
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
continue;
}
}
if (flags.m) {
if (source[i] === "^") {
pattern += `(^|(?<=[\r
]))`;
continue;
} else if (source[i] === "$") {
pattern += `($|(?=[\r
]))`;
continue;
}
}
if (flags.s && source[i] === ".") {
pattern += inCharGroup ? `${source[i]}\r
` : `[${source[i]}\r
]`;
continue;
}
pattern += source[i];
if (source[i] === "\\") isEscaped = true;
else if (inCharGroup && source[i] === "]") inCharGroup = false;
else if (!inCharGroup && source[i] === "[") inCharGroup = true;
}
try {
new RegExp(pattern);
} catch (e) {
console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
return regex.source;
}
return pattern;
}
function parseRecordDef(def, refs) {
var _a2, _b2, _c, _d, _e, _f;
const schema = {
type: "object",
additionalProperties: (_a2 = parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
})) != null ? _a2 : refs.allowedAdditionalProperties
};
if (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
const { type: _type, ...keyType } = parseStringDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) return {
...schema,
propertyNames: { enum: def.keyType._def.values }
};
else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
const { type: _type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
}
return schema;
}
function parseMapDef(def, refs) {
if (refs.mapStrategy === "record") return parseRecordDef(def, refs);
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [parseDef(def.keyType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"0"
]
}) || parseAnyDef(), parseDef(def.valueType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"1"
]
}) || parseAnyDef()],
minItems: 2,
maxItems: 2
}
};
}
function parseNativeEnumDef(def) {
const object = def.values;
const actualValues = Object.keys(def.values).filter((key) => {
return typeof object[object[key]] !== "number";
}).map((key) => object[key]);
const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
return {
type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
enum: actualValues
};
}
function parseNeverDef() {
return { not: parseAnyDef() };
}
function parseNullDef() {
return { type: "null" };
}
var primitiveMappings = {
ZodString: "string",
ZodNumber: "number",
ZodBigInt: "integer",
ZodBoolean: "boolean",
ZodNull: "null"
};
function parseUnionDef(def, refs) {
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
const types = options.reduce((types2, x) => {
const type = primitiveMappings[x._def.typeName];
return type && !types2.includes(type) ? [...types2, type] : types2;
}, []);
return { type: types.length > 1 ? types : types[0] };
} else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
const types = options.reduce((acc, x) => {
const type = typeof x._def.value;
switch (type) {
case "string":
case "number":
case "boolean": return [...acc, type];
case "bigint": return [...acc, "integer"];
case "object": if (x._def.value === null) return [...acc, "null"];
default: return acc;
}
}, []);
if (types.length === options.length) {
const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
return {
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
enum: options.reduce((acc, x) => {
return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
}, [])
};
}
} else if (options.every((x) => x._def.typeName === "ZodEnum")) return {
type: "string",
enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x2) => !acc.includes(x2))], [])
};
return asAnyOf(def, refs);
}
var asAnyOf = (def, refs) => {
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
`${i}`
]
})).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
return anyOf.length ? { anyOf } : void 0;
};
function parseNullableDef(def, refs) {
if ([
"ZodString",
"ZodNumber",
"ZodBigInt",
"ZodBoolean",
"ZodNull"
].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) return { type: [primitiveMappings[def.innerType._def.typeName], "null"] };
const base = parseDef(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
"0"
]
});
return base && { anyOf: [base, { type: "null" }] };
}
function parseNumberDef(def) {
const res = { type: "number" };
if (!def.checks) return res;
for (const check of def.checks) switch (check.kind) {
case "int":
res.type = "integer";
break;
case "min":
if (check.inclusive) res.minimum = check.value;
else res.exclusiveMinimum = check.value;
break;
case "max":
if (check.inclusive) res.maximum = check.value;
else res.exclusiveMaximum = check.value;
break;
case "multipleOf":
res.multipleOf = check.value;
break;
}
return res;
}
function parseObjectDef(def, refs) {
const result = {
type: "object",
properties: {}
};
const required = [];
const shape = def.shape();
for (const propName in shape) {
let propDef = shape[propName];
if (propDef === void 0 || propDef._def === void 0) continue;
const propOptional = safeIsOptional(propDef);
const parsedDef = parseDef(propDef._def, {
...refs,
currentPath: [
...refs.currentPath,
"properties",
propName
],
propertyPath: [
...refs.currentPath,
"properties",
propName
]
});
if (parsedDef === void 0) continue;
result.properties[propName] = parsedDef;
if (!propOptional) required.push(propName);
}
if (required.length) result.required = required;
const additionalProperties = decideAdditionalProperties(def, refs);
if (additionalProperties !== void 0) result.additionalProperties = additionalProperties;
return result;
}
function decideAdditionalProperties(def, refs) {
if (def.catchall._def.typeName !== "ZodNever") return parseDef(def.catchall._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
});
switch (def.unknownKeys) {
case "passthrough": return refs.allowedAdditionalProperties;
case "strict": return refs.rejectedAdditionalProperties;
case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
}
}
function safeIsOptional(schema) {
try {
return schema.isOptional();
} catch (e) {
return true;
}
}
var parseOptionalDef = (def, refs) => {
var _a2;
if (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) return parseDef(def.innerType._def, refs);
const innerSchema = parseDef(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
"1"
]
});
return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
};
var parsePipelineDef = (def, refs) => {
if (refs.pipeStrategy === "input") return parseDef(def.in._def, refs);
else if (refs.pipeStrategy === "output") return parseDef(def.out._def, refs);
const inputSchema = parseDef(def.in._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
});
return { allOf: [inputSchema, parseDef(def.out._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
inputSchema ? "1" : "0"
]
})].filter((schema) => schema !== void 0) };
};
function parsePromiseDef(def, refs) {
return parseDef(def.type._def, refs);
}
function parseSetDef(def, refs) {
const schema = {
type: "array",
uniqueItems: true,
items: parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
})
};
if (def.minSize) schema.minItems = def.minSize.value;
if (def.maxSize) schema.maxItems = def.maxSize.value;
return schema;
}
function parseTupleDef(def, refs) {
if (def.rest) return {
type: "array",
minItems: def.items.length,
items: def.items.map((x, i) => parseDef(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
`${i}`
]
})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
additionalItems: parseDef(def.rest._def, {
...refs,
currentPath: [...refs.currentPath, "additionalItems"]
})
};
else return {
type: "array",
minItems: def.items.length,
maxItems: def.items.length,
items: def.items.map((x, i) => parseDef(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
`${i}`
]
})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
};
}
function parseUndefinedDef() {
return { not: parseAnyDef() };
}
function parseUnknownDef() {
return parseAnyDef();
}
var parseReadonlyDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
var selectParser = (def, typeName, refs) => {
switch (typeName) {
case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs);
case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def);
case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs);
case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def);
case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef();
case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs);
case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef();
case ZodFirstPartyTypeKind.ZodNull: return parseNullDef();
case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs);
case ZodFirstPartyTypeKind.ZodUnion:
case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs);
case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs);
case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs);
case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs);
case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def);
case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def);
case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def);
case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs);
case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs);
case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs);
case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs);
case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;
case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs);
case ZodFirstPartyTypeKind.ZodNaN:
case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef();
case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs);
case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef();
case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef();
case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs);
case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs);
case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs);
case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs);
case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs);
case ZodFirstPartyTypeKind.ZodFunction:
case ZodFirstPartyTypeKind.ZodVoid:
case ZodFirstPartyTypeKind.ZodSymbol: return;
default: return /* @__PURE__ */ ((_) => void 0)(typeName);
}
};
var getRelativePath = (pathA, pathB) => {
let i = 0;
for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
};
function parseDef(def, refs, forceResolution = false) {
var _a2;
const seenItem = refs.seen.get(def);
if (refs.override) {
const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(refs, def, refs, seenItem, forceResolution);
if (overrideResult !== ignoreOverride) return overrideResult;
}
if (seenItem && !forceResolution) {
const seenSchema = get$ref(seenItem, refs);
if (seenSchema !== void 0) return seenSchema;
}
const newItem = {
def,
path: refs.currentPath,
jsonSchema: void 0
};
refs.seen.set(def, newItem);
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
if (jsonSchema2) addMeta(def, refs, jsonSchema2);
if (refs.postProcess) {
const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
newItem.jsonSchema = jsonSchema2;
return postProcessResult;
}
newItem.jsonSchema = jsonSchema2;
return jsonSchema2;
}
var get$ref = (item, refs) => {
switch (refs.$refStrategy) {
case "root": return { $ref: item.path.join("/") };
case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) };
case "none":
case "seen":
if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
return parseAnyDef();
}
return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
}
};
var addMeta = (def, refs, jsonSchema2) => {
if (def.description) jsonSchema2.description = def.description;
return jsonSchema2;
};
var getRefs = (options) => {
const _options = getDefaultOptions(options);
const currentPath = _options.name !== void 0 ? [
..._options.basePath,
_options.definitionPath,
_options.name
] : _options.basePath;
return {
..._options,
currentPath,
propertyPath: void 0,
seen: new Map(Object.entries(_options.definitions).map(([name2, def]) => [def._def, {
def: def._def,
path: [
..._options.basePath,
_options.definitionPath,
name2
],
jsonSchema: void 0
}]))
};
};
var zod3ToJsonSchema = (schema, options) => {
var _a2;
const refs = getRefs(options);
let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name3, schema2]) => {
var _a3;
return {
...acc,
[name3]: (_a3 = parseDef(schema2._def, {
...refs,
currentPath: [
...refs.basePath,
refs.definitionPath,
name3
]
}, true)) != null ? _a3 : parseAnyDef()
};
}, {}) : void 0;
const name2 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
const main = (_a2 = parseDef(schema._def, name2 === void 0 ? refs : {
...refs,
currentPath: [
...refs.basePath,
refs.definitionPath,
name2
]
}, false)) != null ? _a2 : parseAnyDef();
const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
if (title !== void 0) main.title = title;
const combined = name2 === void 0 ? definitions ? {
...main,
[refs.definitionPath]: definitions
} : main : {
$ref: [
...refs.$refStrategy === "relative" ? [] : refs.basePath,
refs.definitionPath,
name2
].join("/"),
[refs.definitionPath]: {
...definitions,
[name2]: main
}
};
combined.$schema = "http://json-schema.org/draft-07/schema#";
return combined;
};
var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
function lazySchema(createSchema) {
let schema;
return () => {
if (schema == null) schema = createSchema();
return schema;
};
}
function jsonSchema(jsonSchema2, { validate } = {}) {
return {
[schemaSymbol]: true,
_type: void 0,
get jsonSchema() {
if (typeof jsonSchema2 === "function") jsonSchema2 = jsonSchema2();
return jsonSchema2;
},
validate
};
}
function isSchema(value) {
return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
}
function asSchema(schema) {
return schema == null ? jsonSchema({
type: "object",
properties: {},
additionalProperties: false
}) : isSchema(schema) ? schema : "~standard" in schema ? schema["~standard"].vendor === "zod" ? zodSchema(schema) : standardSchema(schema) : schema();
}
function standardSchema(standardSchema2) {
return jsonSchema(() => {
if (!hasStandardJsonSchema(standardSchema2)) throw new Error(`Standard schema vendor '${standardSchema2["~standard"].vendor}' does not support JSON Schema conversion.`);
return addAdditionalPropertiesToJsonSchema(standardSchema2["~standard"].jsonSchema.input({ target: "draft-07" }));
}, { validate: async (value) => {
const result = await standardSchema2["~standard"].validate(value);
return "value" in result ? {
success: true,
value: result.value
} : {
success: false,
error: new TypeValidationError({
value,
cause: result.issues
})
};
} });
}
function hasStandardJsonSchema(schema) {
return schema["~standard"].jsonSchema != null;
}
function zod3Schema(zodSchema2, options) {
var _a2;
const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
return jsonSchema(() => zod3ToJsonSchema(zodSchema2, { $refStrategy: useReferences ? "root" : "none" }), { validate: async (value) => {
const result = await zodSchema2.safeParseAsync(value);
return result.success ? {
success: true,
value: result.data
} : {
success: false,
error: result.error
};
} });
}
function zod4Schema(zodSchema2, options) {
var _a2;
const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
return jsonSchema(() => addAdditionalPropertiesToJsonSchema(toJSONSchema(zodSchema2, {
target: "draft-7",
io: "input",
reused: useReferences ? "ref" : "inline"
})), { validate: async (value) => {
const result = await safeParseAsync(zodSchema2, value);
return result.success ? {
success: true,
value: result.data
} : {
success: false,
error: result.error
};
} });
}
function isZod4Schema(zodSchema2) {
return "_zod" in zodSchema2;
}
function zodSchema(zodSchema2, options) {
if (isZod4Schema(zodSchema2)) return zod4Schema(zodSchema2, options);
else return zod3Schema(zodSchema2, options);
}
async function validateTypes({ value, schema, context }) {
const result = await safeValidateTypes({
value,
schema,
context
});
if (!result.success) throw TypeValidationError.wrap({
value,
cause: result.error,
context
});
return result.value;
}
async function safeValidateTypes({ value, schema, context }) {
const actualSchema = asSchema(schema);
try {
if (actualSchema.validate == null) return {
success: true,
value,
rawValue: value
};
const result = await actualSchema.validate(value);
if (result.success) return {
success: true,
value: result.value,
rawValue: value
};
return {
success: false,
error: TypeValidationError.wrap({
value,
cause: result.error,
context
}),
rawValue: value
};
} catch (error) {
return {
success: false,
error: TypeValidationError.wrap({
value,
cause: error,
context
}),
rawValue: value
};
}
}
async function parseJSON({ text, schema }) {
try {
const value = secureJsonParse(text);
if (schema == null) return value;
return await validateTypes({
value,
schema
});
} catch (error) {
if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) throw error;
throw new JSONParseError({
text,
cause: error
});
}
}
async function safeParseJSON({ text, schema }) {
try {
const value = secureJsonParse(text);
if (schema == null) return {
success: true,
value,
rawValue: value
};
return await safeValidateTypes({
value,
schema
});
} catch (error) {
return {
success: false,
error: JSONParseError.isInstance(error) ? error : new JSONParseError({
text,
cause: error
}),
rawValue: void 0
};
}
}
function parseJsonEventStream({ stream, schema }) {
return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(new TransformStream({ async transform({ data }, controller) {
if (data === "[DONE]") return;
controller.enqueue(await safeParseJSON({
text: data,
schema
}));
} }));
}
var getOriginalFetch2 = () => globalThis.fetch;
var postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => await postToApi({
url,
headers: {
"Content-Type": "application/json",
...headers
},
body: {
content: JSON.stringify(body),
values: body
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
});
var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch2() }) => {
try {
const response = await fetch(url, {
method: "POST",
headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/5.0.10`, getRuntimeEnvironmentUserAgent()),
body: body.content,
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
throw new APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || APICallError.isInstance(error)) throw error;
}
throw new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
} catch (error) {
throw handleFetchError({
error,
url,
requestBodyValues: body.values
});
}
};
function tool(tool2) {
return tool2;
}
function createProviderExecutedToolFactory({ id, inputSchema, outputSchema, supportsDeferredResults }) {
return ({ onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({
type: "provider",
isProviderExecuted: true,
id,
args,
inputSchema,
outputSchema,
onInputStart,
onInputDelta,
onInputAvailable,
supportsDeferredResults
});
}
async function resolve(value) {
if (typeof value === "function") value = value();
return Promise.resolve(value);
}
var retryWithExponentialBackoff = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal, shouldRetry, getDelayInMs = ({ exponentialBackoffDelay }) => exponentialBackoffDelay, createRetryError = ({ message }) => new Error(message) }) => async (f) => retryWithExponentialBackoffInternal(f, {
maxRetries,
delayInMs: initialDelayInMs,
backoffFactor,
abortSignal,
shouldRetry,
getDelayInMs,
createRetryError
});
async function retryWithExponentialBackoffInternal(f, { maxRetries, delayInMs, backoffFactor, abortSignal, shouldRetry, getDelayInMs, createRetryError }, errors = []) {
try {
return await f();
} catch (error) {
if (isAbortError(error)) throw error;
if (maxRetries === 0) throw error;
const errorMessage = getErrorMessage(error);
const newErrors = [...errors, error];
const tryNumber = newErrors.length;
if (tryNumber > maxRetries) throw createRetryError({
message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
reason: "maxRetriesExceeded",
errors: newErrors
});
if (await shouldRetry(error) && tryNumber <= maxRetries) {
await delay(getDelayInMs({
error,
exponentialBackoffDelay: delayInMs
}), { abortSignal });
return retryWithExponentialBackoffInternal(f, {
maxRetries,
delayInMs: backoffFactor * delayInMs,
backoffFactor,
abortSignal,
shouldRetry,
getDelayInMs,
createRetryError
}, newErrors);
}
if (tryNumber === 1) throw error;
throw createRetryError({
message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
reason: "errorNotRetryable",
errors: newErrors
});
}
}
var textDecoder2 = new TextDecoder();
async function readResponseBodyAsText({ response, url }) {
return textDecoder2.decode(await readResponseWithSizeLimit({
response,
url
}));
}
var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {
const responseBody = await readResponseBodyAsText({
response,
url
});
const responseHeaders = extractResponseHeaders(response);
if (responseBody.trim() === "") return {
responseHeaders,
value: new APICallError({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
})
};
try {
const parsedError = await parseJSON({
text: responseBody,
schema: errorSchema
});
return {
responseHeaders,
value: new APICallError({
message: errorToMessage(parsedError),
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
data: parsedError,
isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
})
};
} catch (e) {
return {
responseHeaders,
value: new APICallError({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
})
};
}
};
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
const responseHeaders = extractResponseHeaders(response);
if (response.body == null) throw new EmptyResponseBodyError({});
return {
responseHeaders,
value: parseJsonEventStream({
stream: response.body,
schema: chunkSchema
})
};
};
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
const responseBody = await readResponseBodyAsText({
response,
url
});
const parsedResult = await safeParseJSON({
text: responseBody,
schema: responseSchema
});
const responseHeaders = extractResponseHeaders(response);
if (!parsedResult.success) throw new APICallError({
message: "Invalid JSON response",
cause: parsedResult.error,
statusCode: response.status,
responseHeaders,
responseBody,
url,
requestBodyValues
});
return {
responseHeaders,
value: parsedResult.value,
rawValue: parsedResult.rawValue
};
};
function isJSONSerializable(value) {
if (value === null || value === void 0) return true;
const type = typeof value;
if (type === "string" || type === "number" || type === "boolean") return true;
if (type === "function" || type === "symbol" || type === "bigint") return false;
if (Array.isArray(value)) return value.every(isJSONSerializable);
if (Object.getPrototypeOf(value) === Object.prototype) return Object.values(value).every(isJSONSerializable);
return false;
}
function serializeModelOptions(options) {
const serializableConfig = {};
for (const [key, value] of Object.entries(options.config)) if (key === "headers") {
const resolvedHeaders = resolveSync(value);
if (isJSONSerializable(resolvedHeaders)) serializableConfig[key] = resolvedHeaders;
} else if (isJSONSerializable(value)) serializableConfig[key] = value;
return {
modelId: options.modelId,
config: serializableConfig
};
}
function resolveSync(value) {
let next = value;
if (typeof value === "function") next = value();
if (next instanceof Promise) throw new Error("Promise returned from resolveSync");
return next;
}
function parseTranscriptionStreamPart(text) {
let value;
try {
value = secureJsonParse(text);
} catch (e) {
return;
}
if (value == null || typeof value !== "object" || Array.isArray(value)) return;
const part = value;
switch (part.type) {
case "stream-start": return Array.isArray(part.warnings) && part.warnings.every(isWarning) ? part : void 0;
case "transcript-delta": return isString(part.delta) && isOptional(part.id, isString) && isOptional(part.providerMetadata, isPlainObject) ? part : void 0;
case "transcript-partial": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isPlainObject) ? part : void 0;
case "transcript-final": return isString(part.text) && isOptional(part.id, isString) && isOptional(part.startSecond, isNumber) && isOptional(part.endSecond, isNumber) && isOptional(part.channelIndex, isNumber) && isOptional(part.providerMetadata, isPlainObject) ? part : void 0;
case "finish": return isString(part.text) && Array.isArray(part.segments) && part.segments.every(isSegment) && isOptional(part.language, isString) && isOptional(part.durationInSeconds, isNumber) && isOptional(part.providerMetadata, isPlainObject) ? part : void 0;
case "response-metadata": {
if (!(isOptional(part.modelId, isString) && isOptional(part.headers, isPlainObject))) return;
const timestamp = part.timestamp;
if (timestamp == null) return {
...part,
timestamp: void 0
};
if (typeof timestamp !== "string") return;
const revived = new Date(timestamp);
return Number.isNaN(revived.getTime()) ? void 0 : {
...part,
timestamp: revived
};
}
case "raw": return "rawValue" in part ? part : void 0;
case "error": return "error" in part ? part : void 0;
default: return;
}
}
function isString(value) {
return typeof value === "string";
}
function isNumber(value) {
return typeof value === "number";
}
function isOptional(value, check) {
return value === void 0 || check(value);
}
function isPlainObject(value) {
return typeof value === "object" && value != null && !Array.isArray(value);
}
function isWarning(value) {
return isPlainObject(value) && isString(value.type);
}
function isSegment(value) {
return isPlainObject(value) && isString(value.text) && isNumber(value.startSecond) && isNumber(value.endSecond);
}
function withoutTrailingSlash(url) {
return url == null ? void 0 : url.replace(/\/$/, "");
}
function isExecutableTool(tool2) {
return tool2 != null && typeof tool2.execute === "function";
}
function isAsyncIterable(obj) {
return obj != null && typeof obj[Symbol.asyncIterator] === "function";
}
async function* executeTool({ tool: tool2, input, options }) {
const result = tool2.execute(input, options);
if (isAsyncIterable(result)) {
let lastOutput;
for await (const output of result) {
lastOutput = output;
yield {
type: "preliminary",
output
};
}
yield {
type: "final",
output: lastOutput
};
} else yield {
type: "final",
output: await result
};
}
//#endregion
//#region node_modules/@vercel/oidc/dist/get-context.js
var require_get_context = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var get_context_exports = {};
__export(get_context_exports, {
SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
getContext: () => getContext
});
module.exports = __toCommonJS(get_context_exports);
const SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context");
function getContext() {
return globalThis[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
}
0 && (module.exports = {
SYMBOL_FOR_REQ_CONTEXT,
getContext
});
}));
//#endregion
//#region node_modules/@vercel/oidc/dist/token-error.js
var require_token_error = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var token_error_exports = {};
__export(token_error_exports, { VercelOidcTokenError: () => VercelOidcTokenError });
module.exports = __toCommonJS(token_error_exports);
var VercelOidcTokenError = class extends Error {
constructor(message, cause) {
super(message);
this.name = "VercelOidcTokenError";
this.cause = cause;
}
toString() {
if (this.cause) return `${this.name}: ${this.message}: ${this.cause}`;
return `${this.name}: ${this.message}`;
}
};
0 && (module.exports = { VercelOidcTokenError });
}));
//#endregion
//#region node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js
var require_get_vercel_oidc_token = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var get_vercel_oidc_token_exports = {};
__export(get_vercel_oidc_token_exports, {
getVercelOidcToken: () => getVercelOidcToken,
getVercelOidcTokenSync: () => getVercelOidcTokenSync
});
module.exports = __toCommonJS(get_vercel_oidc_token_exports);
var import_get_context = require_get_context();
var import_token_error = require_token_error();
async function getVercelOidcToken(options) {
let token = "";
let err;
try {
token = getVercelOidcTokenSync();
} catch (error) {
err = error;
}
try {
const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([await Promise.resolve().then(() => /* @__PURE__ */ __toESM(require_token_util())), await import("../vercel__oidc.mjs").then((n) => /* @__PURE__ */ __toESM(n.t()))]);
if (!token || isExpired(getTokenPayload(token), options?.expirationBufferMs)) {
await refreshToken(options);
token = getVercelOidcTokenSync();
}
} catch (error) {
let message = err instanceof Error ? err.message : "";
if (error instanceof Error) message = `${message}
${error.message}`;
if (message) throw new import_token_error.VercelOidcTokenError(message);
throw error;
}
return token;
}
function getVercelOidcTokenSync() {
const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
if (!token) throw new Error(`The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`);
return token;
}
0 && (module.exports = {
getVercelOidcToken,
getVercelOidcTokenSync
});
}));
//#endregion
//#region node_modules/@vercel/oidc/dist/auth-errors.js
var require_auth_errors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var auth_errors_exports = {};
__export(auth_errors_exports, {
AccessTokenMissingError: () => AccessTokenMissingError,
RefreshAccessTokenFailedError: () => RefreshAccessTokenFailedError
});
module.exports = __toCommonJS(auth_errors_exports);
var AccessTokenMissingError = class extends Error {
constructor() {
super("No authentication found. Please log in with the Vercel CLI (vercel login).");
this.name = "AccessTokenMissingError";
}
};
var RefreshAccessTokenFailedError = class extends Error {
constructor(cause) {
super("Failed to refresh authentication token.", { cause });
this.name = "RefreshAccessTokenFailedError";
}
};
0 && (module.exports = {
AccessTokenMissingError,
RefreshAccessTokenFailedError
});
}));
//#endregion
//#region node_modules/@vercel/oidc/dist/token-io.js
var require_token_io = /* @__PURE__ */ __commonJSMin(((exports, module) => {
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 __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || 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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var token_io_exports = {};
__export(token_io_exports, {
findRootDir: () => findRootDir,
getUserDataDir: () => getUserDataDir
});
module.exports = __toCommonJS(token_io_exports);
var import_path = __toESM(__require("path"));
var import_fs = __toESM(__require("fs"));
var import_os$1 = __toESM(__require("os"));
var import_token_error = require_token_error();
function findRootDir() {
try {
let dir = process.cwd();
while (dir !== import_path.default.dirname(dir)) {
const pkgPath = import_path.default.join(dir, ".vercel");
if (import_fs.default.existsSync(pkgPath)) return dir;
dir = import_path.default.dirname(dir);
}
} catch (e) {
throw new import_token_error.VercelOidcTokenError("Token refresh only supported in node server environments");
}
return null;
}
function getUserDataDir() {
if (process.env.XDG_DATA_HOME) return process.env.XDG_DATA_HOME;
switch (import_os$1.default.platform()) {
case "darwin": return import_path.default.join(import_os$1.default.homedir(), "Library/Application Support");
case "linux": return import_path.default.join(import_os$1.default.homedir(), ".local/share");
case "win32":
if (process.env.LOCALAPPDATA) return process.env.LOCALAPPDATA;
return null;
default: return null;
}
}
0 && (module.exports = {
findRootDir,
getUserDataDir
});
}));
//#endregion
//#region node_modules/@vercel/oidc/dist/auth-config.js
var require_auth_config = /* @__PURE__ */ __commonJSMin(((exports, module) => {
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 __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || 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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var auth_config_exports = {};
__export(auth_config_exports, {
isValidAccessToken: () => isValidAccessToken,
readAuthConfig: () => readAuthConfig,
writeAuthConfig: () => writeAuthConfig
});
module.exports = __toCommonJS(auth_config_exports);
var fs$1 = __toESM(__require("fs"));
var path$1 = __toESM(__require("path"));
var import_token_util = require_token_util();
function getAuthConfigPath() {
const dataDir = (0, import_token_util.getVercelDataDir)();
if (!dataDir) throw new Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);
return path$1.join(dataDir, "auth.json");
}
function readAuthConfig() {
try {
const authPath = getAuthConfigPath();
if (!fs$1.existsSync(authPath)) return null;
const content = fs$1.readFileSync(authPath, "utf8");
if (!content) return null;
return JSON.parse(content);
} catch (error) {
return null;
}
}
function writeAuthConfig(config) {
const authPath = getAuthConfigPath();
const authDir = path$1.dirname(authPath);
if (!fs$1.existsSync(authDir)) fs$1.mkdirSync(authDir, {
mode: 504,
recursive: true
});
fs$1.writeFileSync(authPath, JSON.stringify(config, null, 2), { mode: 384 });
}
function isValidAccessToken(authConfig, expirationBufferMs = 0) {
if (!authConfig.token) return false;
if (typeof authConfig.expiresAt !== "number") return true;
const nowInSeconds = Math.floor(Date.now() / 1e3);
const bufferInSeconds = expirationBufferMs / 1e3;
return authConfig.expiresAt >= nowInSeconds + bufferInSeconds;
}
0 && (module.exports = {
isValidAccessToken,
readAuthConfig,
writeAuthConfig
});
}));
//#endregion
//#region node_modules/@vercel/oidc/dist/oauth.js
var require_oauth = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var oauth_exports = {};
__export(oauth_exports, {
processTokenResponse: () => processTokenResponse,
refreshTokenRequest: () => refreshTokenRequest
});
module.exports = __toCommonJS(oauth_exports);
var import_os = __require("os");
const VERCEL_ISSUER = "https://vercel.com";
const VERCEL_CLI_CLIENT_ID = "cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp";
const userAgent = `@vercel/oidc node-${process.version} ${(0, import_os.platform)()} (${(0, import_os.arch)()}) ${(0, import_os.hostname)()}`;
let _tokenEndpoint = null;
async function getTokenEndpoint() {
if (_tokenEndpoint) return _tokenEndpoint;
const response = await fetch(`${VERCEL_ISSUER}/.well-known/openid-configuration`, { headers: { "user-agent": userAgent } });
if (!response.ok) throw new Error("Failed to discover OAuth endpoints");
const metadata = await response.json();
if (!metadata || typeof metadata.token_endpoint !== "string") throw new Error("Invalid OAuth discovery response");
const endpoint = metadata.token_endpoint;
_tokenEndpoint = endpoint;
return endpoint;
}
async function refreshTokenRequest(options) {
const tokenEndpoint = await getTokenEndpoint();
return await fetch(tokenEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"user-agent": userAgent
},
body: new URLSearchParams({
client_id: VERCEL_CLI_CLIENT_ID,
grant_type: "refresh_token",
...options
})
});
}
async function processTokenResponse(response) {
const json = await response.json();
if (!response.ok) {
const errorMsg = typeof json === "object" && json && "error" in json ? String(json.error) : "Token refresh failed";
return [new Error(errorMsg)];
}
if (typeof json !== "object" || json === null) return [/* @__PURE__ */ new Error("Invalid token response")];
if (typeof json.access_token !== "string") return [/* @__PURE__ */ new Error("Missing access_token in response")];
if (json.token_type !== "Bearer") return [/* @__PURE__ */ new Error("Invalid token_type in response")];
if (typeof json.expires_in !== "number") return [/* @__PURE__ */ new Error("Missing expires_in in response")];
return [null, json];
}
0 && (module.exports = {
processTokenResponse,
refreshTokenRequest
});
}));
//#endregion
//#region node_modules/@vercel/oidc/dist/token-util.js
var require_token_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
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 __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || 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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var token_util_exports = {};
__export(token_util_exports, {
assertVercelOidcTokenResponse: () => assertVercelOidcTokenResponse,
findProjectInfo: () => findProjectInfo,
getTokenPayload: () => getTokenPayload,
getVercelDataDir: () => getVercelDataDir,
getVercelOidcToken: () => getVercelOidcToken,
getVercelToken: () => getVercelToken,
isExpired: () => isExpired,
loadToken: () => loadToken,
saveToken: () => saveToken
});
module.exports = __toCommonJS(token_util_exports);
var path = __toESM(__require("path"));
var fs = __toESM(__require("fs"));
var import_token_error = require_token_error();
var import_token_io = require_token_io();
var import_auth_config = require_auth_config();
var import_oauth = require_oauth();
var import_auth_errors = require_auth_errors();
function getVercelDataDir() {
const vercelFolder = "com.vercel.cli";
const dataDir = (0, import_token_io.getUserDataDir)();
if (!dataDir) return null;
return path.join(dataDir, vercelFolder);
}
async function getVercelToken(options) {
const authConfig = (0, import_auth_config.readAuthConfig)();
if (!authConfig?.token) throw new import_auth_errors.AccessTokenMissingError();
if ((0, import_auth_config.isValidAccessToken)(authConfig, options?.expirationBufferMs)) return authConfig.token;
if (!authConfig.refreshToken) {
(0, import_auth_config.writeAuthConfig)({});
throw new import_auth_errors.RefreshAccessTokenFailedError("No refresh token available");
}
try {
const tokenResponse = await (0, import_oauth.refreshTokenRequest)({ refresh_token: authConfig.refreshToken });
const [tokensError, tokens] = await (0, import_oauth.processTokenResponse)(tokenResponse);
if (tokensError || !tokens) {
(0, import_auth_config.writeAuthConfig)({});
throw new import_auth_errors.RefreshAccessTokenFailedError(tokensError);
}
const updatedConfig = {
token: tokens.access_token,
expiresAt: Math.floor(Date.now() / 1e3) + tokens.expires_in
};
if (tokens.refresh_token) updatedConfig.refreshToken = tokens.refresh_token;
(0, import_auth_config.writeAuthConfig)(updatedConfig);
return updatedConfig.token;
} catch (error) {
(0, import_auth_config.writeAuthConfig)({});
if (error instanceof import_auth_errors.AccessTokenMissingError || error instanceof import_auth_errors.RefreshAccessTokenFailedError) throw error;
throw new import_auth_errors.RefreshAccessTokenFailedError(error);
}
}
async function getVercelOidcToken(authToken, projectId, teamId) {
const url = `https://api.vercel.com/v1/projects/${projectId}/token?source=vercel-oidc-refresh${teamId ? `&teamId=${teamId}` : ""}`;
const res = await fetch(url, {
method: "POST",
headers: { Authorization: `Bearer ${authToken}` }
});
if (!res.ok) throw new import_token_error.VercelOidcTokenError(`Failed to refresh OIDC token: ${res.statusText}`);
const tokenRes = await res.json();
assertVercelOidcTokenResponse(tokenRes);
return tokenRes;
}
function assertVercelOidcTokenResponse(res) {
if (!res || typeof res !== "object") throw new TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");
if (!("token" in res) || typeof res.token !== "string") throw new TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again");
}
function findProjectInfo() {
const dir = (0, import_token_io.findRootDir)();
if (!dir) throw new import_token_error.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");
const prjPath = path.join(dir, ".vercel", "project.json");
if (!fs.existsSync(prjPath)) throw new import_token_error.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");
const prj = JSON.parse(fs.readFileSync(prjPath, "utf8"));
if (typeof prj.projectId !== "string" && typeof prj.orgId !== "string") throw new TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");
return {
projectId: prj.projectId,
teamId: prj.orgId
};
}
function saveToken(token, projectId) {
const dir = (0, import_token_io.getUserDataDir)();
if (!dir) throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
const tokenPath = path.join(dir, "com.vercel.token", `${projectId}.json`);
const tokenJson = JSON.stringify(token);
fs.mkdirSync(path.dirname(tokenPath), {
mode: 504,
recursive: true
});
fs.writeFileSync(tokenPath, tokenJson);
fs.chmodSync(tokenPath, 432);
}
function loadToken(projectId) {
const dir = (0, import_token_io.getUserDataDir)();
if (!dir) throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
const tokenPath = path.join(dir, "com.vercel.token", `${projectId}.json`);
if (!fs.existsSync(tokenPath)) return null;
const token = JSON.parse(fs.readFileSync(tokenPath, "utf8"));
assertVercelOidcTokenResponse(token);
return token;
}
function getTokenPayload(token) {
const tokenParts = token.split(".");
if (tokenParts.length !== 3) throw new import_token_error.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");
const base64 = tokenParts[1].replace(/-/g, "+").replace(/_/g, "/");
const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "=");
return JSON.parse(Buffer.from(padded, "base64").toString("utf8"));
}
function isExpired(token, bufferMs = 0) {
return token.exp * 1e3 < Date.now() + bufferMs;
}
0 && (module.exports = {
assertVercelOidcTokenResponse,
findProjectInfo,
getTokenPayload,
getVercelDataDir,
getVercelOidcToken,
getVercelToken,
isExpired,
loadToken,
saveToken
});
}));
//#endregion
//#region node_modules/@ai-sdk/gateway/dist/index.js
var import_dist = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var src_exports = {};
__export(src_exports, {
AccessTokenMissingError: () => import_auth_errors.AccessTokenMissingError,
RefreshAccessTokenFailedError: () => import_auth_errors.RefreshAccessTokenFailedError,
getContext: () => import_get_context.getContext,
getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync,
getVercelToken: () => import_token_util.getVercelToken
});
module.exports = __toCommonJS(src_exports);
var import_get_vercel_oidc_token = require_get_vercel_oidc_token();
var import_get_context = require_get_context();
var import_auth_errors = require_auth_errors();
var import_token_util = require_token_util();
0 && (module.exports = {
AccessTokenMissingError,
RefreshAccessTokenFailedError,
getContext,
getVercelOidcToken,
getVercelOidcTokenSync,
getVercelToken
});
})))();
function getGatewayRealtimeProtocols(token, options) {
return buildGatewayProtocols("ai-gateway-realtime.v1", token, options);
}
function getGatewayTranscriptionProtocols(token, options) {
return buildGatewayProtocols("ai-gateway-transcription.v1", token, options);
}
function buildGatewayProtocols(marker11, token, options) {
const protocols = [marker11, `ai-gateway-auth.${token}`];
if (options == null ? void 0 : options.teamIdOrSlug) protocols.push(`ai-gateway-team.${encodeSubprotocolValue(options.teamIdOrSlug)}`);
return protocols;
}
function encodeSubprotocolValue(value) {
const bytes = new TextEncoder().encode(value);
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/u, "");
}
var symbol = Symbol.for("vercel.ai.gateway.error");
var _a;
var _b;
var GatewayError = class _GatewayError extends (_b = Error, _a = symbol, _b) {
constructor({ message, statusCode = 500, cause, generationId, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500) }) {
super(generationId ? `${message} [${generationId}]` : message);
this[_a] = true;
this.statusCode = statusCode;
this.cause = cause;
this.generationId = generationId;
this.isRetryable = isRetryable;
}
/**
* Checks if the given error is a Gateway Error.
* @param {unknown} error - The error to check.
* @returns {boolean} True if the error is a Gateway Error, false otherwise.
*/
static isInstance(error) {
return _GatewayError.hasMarker(error);
}
static hasMarker(error) {
return typeof error === "object" && error !== null && symbol in error && error[symbol] === true;
}
};
var name = "GatewayAuthenticationError";
var marker2 = `vercel.ai.gateway.error.${name}`;
var symbol2 = Symbol.for(marker2);
var _a2;
var _b2;
var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a2 = symbol2, _b2) {
constructor({ message = "Authentication failed", statusCode = 401, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[_a2] = true;
this.name = name;
this.type = "authentication_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol2 in error;
}
/**
* Creates a contextual error message when authentication fails
*/
static createContextualError({ apiKeyProvided, oidcTokenProvided, statusCode = 401, cause, generationId }) {
let contextualMessage;
if (apiKeyProvided) contextualMessage = `AI Gateway authentication failed: Invalid API key or token.
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
Provide an API key or Vercel access token via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;
else if (oidcTokenProvided) contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
or pass a Vercel access token via the 'apiKey' option.`;
else contextualMessage = `AI Gateway authentication failed: No authentication provided.
Option 1 - API key:
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
Option 2 - Vercel access token:
Pass a Vercel personal access token or Vercel app access token via the 'apiKey' option.
Option 3 - OIDC token:
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;
return new _GatewayAuthenticationError({
message: contextualMessage,
statusCode,
cause,
generationId
});
}
};
var name2 = "GatewayInvalidRequestError";
var marker3 = `vercel.ai.gateway.error.${name2}`;
var symbol3 = Symbol.for(marker3);
var _a3;
var _b3;
var GatewayInvalidRequestError = class extends (_b3 = GatewayError, _a3 = symbol3, _b3) {
constructor({ message = "Invalid request", statusCode = 400, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[_a3] = true;
this.name = name2;
this.type = "invalid_request_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol3 in error;
}
};
var name3 = "GatewayRateLimitError";
var marker4 = `vercel.ai.gateway.error.${name3}`;
var symbol4 = Symbol.for(marker4);
var _a4;
var _b4;
var GatewayRateLimitError = class extends (_b4 = GatewayError, _a4 = symbol4, _b4) {
constructor({ message = "Rate limit exceeded", statusCode = 429, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[_a4] = true;
this.name = name3;
this.type = "rate_limit_exceeded";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol4 in error;
}
};
var name4 = "GatewayModelNotFoundError";
var marker5 = `vercel.ai.gateway.error.${name4}`;
var symbol5 = Symbol.for(marker5);
var modelNotFoundParamSchema = lazySchema(() => zodSchema(object({ modelId: string() })));
var _a5;
var _b5;
var GatewayModelNotFoundError = class extends (_b5 = GatewayError, _a5 = symbol5, _b5) {
constructor({ message = "Model not found", statusCode = 404, modelId, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[_a5] = true;
this.name = name4;
this.type = "model_not_found";
this.modelId = modelId;
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol5 in error;
}
};
var name5 = "GatewayInternalServerError";
var marker6 = `vercel.ai.gateway.error.${name5}`;
var symbol6 = Symbol.for(marker6);
var _a6;
var _b6;
var GatewayInternalServerError = class extends (_b6 = GatewayError, _a6 = symbol6, _b6) {
constructor({ message = "Internal server error", statusCode = 500, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[_a6] = true;
this.name = name5;
this.type = "internal_server_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol6 in error;
}
};
var name6 = "GatewayFailedDependencyError";
var marker7 = `vercel.ai.gateway.error.${name6}`;
var symbol7 = Symbol.for(marker7);
var _a7;
var _b7;
var GatewayFailedDependencyError = class extends (_b7 = GatewayError, _a7 = symbol7, _b7) {
constructor({ message = "Failed dependency", statusCode = 424, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[_a7] = true;
this.name = name6;
this.type = "failed_dependency";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol7 in error;
}
};
var name7 = "GatewayForbiddenError";
var marker8 = `vercel.ai.gateway.error.${name7}`;
var symbol8 = Symbol.for(marker8);
var forbiddenParamSchema = lazySchema(() => zodSchema(object({ ruleId: string() })));
var _a8;
var _b8;
var GatewayForbiddenError = class extends (_b8 = GatewayError, _a8 = symbol8, _b8) {
constructor({ message = "Forbidden", statusCode = 403, cause, generationId, ruleId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[_a8] = true;
this.name = name7;
this.type = "forbidden";
this.ruleId = ruleId;
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol8 in error;
}
};
var name8 = "GatewayResponseError";
var marker9 = `vercel.ai.gateway.error.${name8}`;
var symbol9 = Symbol.for(marker9);
var _a9;
var _b9;
var GatewayResponseError = class extends (_b9 = GatewayError, _a9 = symbol9, _b9) {
constructor({ message = "Invalid response from Gateway", statusCode = 502, response, validationError, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[_a9] = true;
this.name = name8;
this.type = "response_error";
this.response = response;
this.validationError = validationError;
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol9 in error;
}
};
async function createGatewayErrorFromResponse({ response, statusCode, defaultMessage = "Gateway request failed", cause, authMethod }) {
var _a11;
const parseResult = await safeValidateTypes({
value: response,
schema: gatewayErrorResponseSchema
});
if (!parseResult.success) {
const rawGenerationId = typeof response === "object" && response !== null && "generationId" in response ? response.generationId : void 0;
return new GatewayResponseError({
message: `Invalid error response format: ${defaultMessage}`,
statusCode,
response,
validationError: parseResult.error,
cause,
generationId: rawGenerationId
});
}
const validatedResponse = parseResult.value;
const errorType = validatedResponse.error.type;
const message = validatedResponse.error.message;
const generationId = (_a11 = validatedResponse.generationId) != null ? _a11 : void 0;
switch (errorType) {
case "authentication_error": return GatewayAuthenticationError.createContextualError({
apiKeyProvided: authMethod === "api-key",
oidcTokenProvided: authMethod === "oidc",
statusCode,
cause,
generationId
});
case "invalid_request_error": return new GatewayInvalidRequestError({
message,
statusCode,
cause,
generationId
});
case "rate_limit_exceeded": return new GatewayRateLimitError({
message,
statusCode,
cause,
generationId
});
case "model_not_found": {
const modelResult = await safeValidateTypes({
value: validatedResponse.error.param,
schema: modelNotFoundParamSchema
});
return new GatewayModelNotFoundError({
message,
statusCode,
modelId: modelResult.success ? modelResult.value.modelId : void 0,
cause,
generationId
});
}
case "internal_server_error": return new GatewayInternalServerError({
message,
statusCode,
cause,
generationId
});
case "failed_dependency": return new GatewayFailedDependencyError({
message,
statusCode,
cause,
generationId
});
case "forbidden": {
const ruleResult = await safeValidateTypes({
value: validatedResponse.error.param,
schema: forbiddenParamSchema
});
return new GatewayForbiddenError({
message,
statusCode,
cause,
generationId,
ruleId: ruleResult.success ? ruleResult.value.ruleId : void 0
});
}
default: return new GatewayInternalServerError({
message,
statusCode,
cause,
generationId
});
}
}
var gatewayErrorResponseSchema = lazySchema(() => zodSchema(object({
error: object({
message: string(),
type: string().nullish(),
param: unknown().nullish(),
code: union([string(), number()]).nullish()
}),
generationId: string().nullish()
})));
function extractApiCallResponse(error) {
if (error.data !== void 0) return error.data;
if (error.responseBody != null) try {
return secureJsonParse(error.responseBody);
} catch (e) {
return error.responseBody;
}
return {};
}
var name9 = "GatewayTimeoutError";
var marker10 = `vercel.ai.gateway.error.${name9}`;
var symbol10 = Symbol.for(marker10);
var _a10;
var _b10;
var GatewayTimeoutError = class _GatewayTimeoutError extends (_b10 = GatewayError, _a10 = symbol10, _b10) {
constructor({ message = "Request timed out", statusCode = 408, cause, generationId } = {}) {
super({
message,
statusCode,
cause,
generationId
});
this[_a10] = true;
this.name = name9;
this.type = "timeout_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol10 in error;
}
/**
* Creates a helpful timeout error message with troubleshooting guidance
*/
static createTimeoutError({ originalMessage, statusCode = 408, cause, generationId }) {
const message = `Gateway request timed out: ${originalMessage}
This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;
return new _GatewayTimeoutError({
message,
statusCode,
cause,
generationId
});
}
};
function isTimeoutError(error) {
if (!(error instanceof Error)) return false;
const errorCode = error.code;
if (typeof errorCode === "string") return [
"UND_ERR_HEADERS_TIMEOUT",
"UND_ERR_BODY_TIMEOUT",
"UND_ERR_CONNECT_TIMEOUT"
].includes(errorCode);
return false;
}
async function asGatewayError(error, authMethod) {
var _a11;
if (GatewayError.isInstance(error)) return error;
if (isTimeoutError(error)) return GatewayTimeoutError.createTimeoutError({
originalMessage: error instanceof Error ? error.message : "Unknown error",
cause: error
});
if (APICallError.isInstance(error)) {
if (error.cause && isTimeoutError(error.cause)) return GatewayTimeoutError.createTimeoutError({
originalMessage: error.message,
cause: error
});
return await createGatewayErrorFromResponse({
response: extractApiCallResponse(error),
statusCode: (_a11 = error.statusCode) != null ? _a11 : 500,
defaultMessage: "Gateway request failed",
cause: error,
authMethod
});
}
return await createGatewayErrorFromResponse({
response: {},
statusCode: 500,
defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
cause: error,
authMethod
});
}
var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
var VERCEL_AI_GATEWAY_TEAM_HEADER = "x-vercel-ai-gateway-team";
async function parseAuthMethod(headers) {
const result = await safeValidateTypes({
value: headers[GATEWAY_AUTH_METHOD_HEADER],
schema: gatewayAuthMethodSchema
});
return result.success ? result.value : void 0;
}
var gatewayAuthMethodSchema = lazySchema(() => zodSchema(union([literal("api-key"), literal("oidc")])));
var KNOWN_MODEL_TYPES = [
"embedding",
"image",
"language",
"realtime",
"reranking",
"speech",
"transcription",
"video"
];
var GatewayFetchMetadata = class {
constructor(config) {
this.config = config;
}
async getAvailableModels() {
try {
const { value } = await getFromApi({
url: `${this.config.baseURL}/config`,
validateUrl: false,
headers: this.config.headers ? await resolve(this.config.headers) : void 0,
successfulResponseHandler: createJsonResponseHandler(gatewayAvailableModelsResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
async getCredits() {
try {
const { value } = await getFromApi({
url: `${new URL(this.config.baseURL).origin}/v1/credits`,
validateUrl: false,
headers: this.config.headers ? await resolve(this.config.headers) : void 0,
successfulResponseHandler: createJsonResponseHandler(gatewayCreditsResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
var gatewayAvailableModelsResponseSchema = lazySchema(() => zodSchema(object({ models: array(object({
id: string(),
name: string(),
description: string().nullish(),
pricing: object({
input: string(),
output: string(),
input_cache_read: string().nullish(),
input_cache_write: string().nullish()
}).transform(({ input, output, input_cache_read, input_cache_write }) => ({
input,
output,
...input_cache_read ? { cachedInputTokens: input_cache_read } : {},
...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}
})).nullish(),
specification: object({
specificationVersion: literal("v4"),
provider: string(),
modelId: string()
}),
modelType: string().nullish()
})).transform((models) => models.filter((m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType))) })));
var gatewayCreditsResponseSchema = lazySchema(() => zodSchema(object({
balance: string(),
total_used: string()
}).transform(({ balance, total_used }) => ({
balance,
totalUsed: total_used
}))));
var GatewaySpendReport = class {
constructor(config) {
this.config = config;
}
async getSpendReport(params) {
try {
const baseUrl = new URL(this.config.baseURL);
const searchParams = new URLSearchParams();
searchParams.set("start_date", params.startDate);
searchParams.set("end_date", params.endDate);
if (params.groupBy) searchParams.set("group_by", params.groupBy);
if (params.datePart) searchParams.set("date_part", params.datePart);
if (params.userId) searchParams.set("user_id", params.userId);
if (params.model) searchParams.set("model", params.model);
if (params.provider) searchParams.set("provider", params.provider);
if (params.credentialType) searchParams.set("credential_type", params.credentialType);
if (params.tags && params.tags.length > 0) searchParams.set("tags", params.tags.join(","));
const { value } = await getFromApi({
url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
validateUrl: false,
headers: this.config.headers ? await resolve(this.config.headers) : void 0,
successfulResponseHandler: createJsonResponseHandler(gatewaySpendReportResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
var gatewaySpendReportResponseSchema = lazySchema(() => zodSchema(object({ results: array(object({
day: string().optional(),
hour: string().optional(),
user: string().optional(),
model: string().optional(),
tag: string().optional(),
provider: string().optional(),
credential_type: _enum(["byok", "system"]).optional(),
total_cost: number(),
market_cost: number().optional(),
input_tokens: number().optional(),
output_tokens: number().optional(),
cached_input_tokens: number().optional(),
cache_creation_input_tokens: number().optional(),
reasoning_tokens: number().optional(),
request_count: number().optional()
}).transform(({ credential_type, total_cost, market_cost, input_tokens, output_tokens, cached_input_tokens, cache_creation_input_tokens, reasoning_tokens, request_count, ...rest }) => ({
...rest,
...credential_type !== void 0 ? { credentialType: credential_type } : {},
totalCost: total_cost,
...market_cost !== void 0 ? { marketCost: market_cost } : {},
...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
...request_count !== void 0 ? { requestCount: request_count } : {}
}))) })));
var GatewayGenerationInfoFetcher = class {
constructor(config) {
this.config = config;
}
async getGenerationInfo(params) {
try {
const { value } = await getFromApi({
url: `${new URL(this.config.baseURL).origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
validateUrl: false,
headers: this.config.headers ? await resolve(this.config.headers) : void 0,
successfulResponseHandler: createJsonResponseHandler(gatewayGenerationInfoResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
var gatewayGenerationInfoResponseSchema = lazySchema(() => zodSchema(object({ data: object({
id: string(),
total_cost: number(),
upstream_inference_cost: number(),
usage: number(),
created_at: string(),
model: string(),
is_byok: boolean(),
provider_name: string(),
streamed: boolean(),
finish_reason: string(),
latency: number(),
generation_time: number(),
native_tokens_prompt: number(),
native_tokens_completion: number(),
native_tokens_reasoning: number(),
native_tokens_cached: number(),
native_tokens_cache_creation: number(),
billable_web_search_calls: number()
}).transform(({ total_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest }) => ({
...rest,
totalCost: total_cost,
upstreamInferenceCost: upstream_inference_cost,
createdAt: created_at,
isByok: is_byok,
providerName: provider_name,
finishReason: finish_reason,
generationTime: generation_time,
promptTokens: native_tokens_prompt,
completionTokens: native_tokens_completion,
reasoningTokens: native_tokens_reasoning,
cachedTokens: native_tokens_cached,
cacheCreationTokens: native_tokens_cache_creation,
billableWebSearchCalls: billable_web_search_calls
})) }).transform(({ data }) => data)));
var GatewayLanguageModel = class _GatewayLanguageModel {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.supportedUrls = { "*/*": [/.*/] };
}
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new _GatewayLanguageModel(options.modelId, options.config);
}
get provider() {
return this.config.provider;
}
async getArgs(options) {
const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;
return {
args: this.maybeEncodeFileParts(optionsWithoutSignal),
warnings: []
};
}
async doGenerate(options) {
const { args, warnings } = await this.getArgs(options);
const { abortSignal } = options;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve(this.config.o11yHeaders)),
body: args,
successfulResponseHandler: createJsonResponseHandler(any()),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
...responseBody,
request: { body: args },
response: {
headers: responseHeaders,
body: rawResponse
},
warnings
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
}
}
async doStream(options) {
const { args, warnings } = await this.getArgs(options);
const { abortSignal } = options;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { value: response, responseHeaders } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve(this.config.o11yHeaders)),
body: args,
successfulResponseHandler: createEventSourceResponseHandler(any()),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
stream: response.pipeThrough(new TransformStream({
start(controller) {
if (warnings.length > 0) controller.enqueue({
type: "stream-start",
warnings
});
},
transform(chunk, controller) {
if (chunk.success) {
const streamPart = chunk.value;
if (streamPart.type === "raw" && !options.includeRawChunks) return;
if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") streamPart.timestamp = new Date(streamPart.timestamp);
controller.enqueue(streamPart);
} else controller.error(chunk.error);
}
})),
request: { body: args },
response: { headers: responseHeaders }
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
}
}
/**
* Encodes inline `Uint8Array` file data to a base64 string in place.
* @param options - The options to encode.
* @returns The options with the file data encoded.
*/
maybeEncodeFileParts(options) {
for (const message of options.prompt) {
if (!Array.isArray(message.content)) continue;
for (const part of message.content) if (part.type === "file" || part.type === "reasoning-file") part.data = maybeBase64EncodeFileData(part.data);
else if (part.type === "tool-result" && part.output.type === "content") {
for (const contentPart of part.output.value) if (contentPart.type === "file") contentPart.data = maybeBase64EncodeFileData(contentPart.data);
}
}
return options;
}
getUrl() {
return `${this.config.baseURL}/language-model`;
}
getModelConfigHeaders(modelId, streaming) {
return {
"ai-language-model-specification-version": "4",
"ai-language-model-id": modelId,
"ai-language-model-streaming": String(streaming)
};
}
};
function maybeBase64EncodeFileData(data) {
if (data.type === "data") {
const bytes = data.data;
if (bytes instanceof Uint8Array) return {
...data,
data: Buffer.from(bytes).toString("base64")
};
}
return data;
}
var GatewayEmbeddingModel = class _GatewayEmbeddingModel {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxEmbeddingsPerCall = 2048;
this.supportsParallelCalls = true;
}
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new _GatewayEmbeddingModel(options.modelId, options.config);
}
get provider() {
return this.config.provider;
}
async doEmbed({ values, headers, abortSignal, providerOptions }) {
var _a11, _b11;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: {
values,
...providerOptions ? { providerOptions } : {}
},
successfulResponseHandler: createJsonResponseHandler(gatewayEmbeddingResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
embeddings: responseBody.embeddings,
usage: (_a11 = responseBody.usage) != null ? _a11 : void 0,
providerMetadata: responseBody.providerMetadata,
response: {
headers: responseHeaders,
body: rawValue
},
warnings: (_b11 = responseBody.warnings) != null ? _b11 : []
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
}
}
getUrl() {
return `${this.config.baseURL}/embedding-model`;
}
getModelConfigHeaders() {
return {
"ai-embedding-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
var gatewayEmbeddingWarningSchema = discriminatedUnion("type", [
object({
type: literal("unsupported"),
feature: string(),
details: string().optional()
}),
object({
type: literal("compatibility"),
feature: string(),
details: string().optional()
}),
object({
type: literal("deprecated"),
setting: string(),
message: string()
}),
object({
type: literal("other"),
message: string()
})
]);
var gatewayEmbeddingResponseSchema = lazySchema(() => zodSchema(object({
embeddings: array(array(number())),
usage: object({ tokens: number() }).nullish(),
warnings: array(gatewayEmbeddingWarningSchema).optional(),
providerMetadata: record(string(), record(string(), unknown())).optional()
})));
var GatewayImageModel = class _GatewayImageModel {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxImagesPerCall = Number.MAX_SAFE_INTEGER;
}
static [WORKFLOW_SERIALIZE](model) {
return serializeModelOptions({
modelId: model.modelId,
config: model.config
});
}
static [WORKFLOW_DESERIALIZE](options) {
return new _GatewayImageModel(options.modelId, options.config);
}
get provider() {
return this.config.provider;
}
async doGenerate({ prompt, n, size, aspectRatio, seed, files, mask, providerOptions, headers, abortSignal }) {
var _a11, _b11, _c, _d;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: {
prompt,
n,
...size && { size },
...aspectRatio && { aspectRatio },
...seed && { seed },
...providerOptions && { providerOptions },
...files && { files: files.map((file) => maybeEncodeImageFile(file)) },
...mask && { mask: maybeEncodeImageFile(mask) }
},
successfulResponseHandler: createJsonResponseHandler(gatewayImageResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
images: responseBody.images,
warnings: (_a11 = responseBody.warnings) != null ? _a11 : [],
providerMetadata: responseBody.providerMetadata,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
},
...responseBody.usage != null && { usage: {
inputTokens: (_b11 = responseBody.usage.inputTokens) != null ? _b11 : void 0,
outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,
totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0
} }
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
}
}
getUrl() {
return `${this.config.baseURL}/image-model`;
}
getModelConfigHeaders() {
return {
"ai-image-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
function maybeEncodeImageFile(file) {
if (file.type === "file" && file.data instanceof Uint8Array) return {
...file,
data: convertUint8ArrayToBase64(file.data)
};
return file;
}
var providerMetadataEntrySchema = object({ images: array(unknown()).optional() }).catchall(unknown());
var gatewayImageWarningSchema = discriminatedUnion("type", [
object({
type: literal("unsupported"),
feature: string(),
details: string().optional()
}),
object({
type: literal("compatibility"),
feature: string(),
details: string().optional()
}),
object({
type: literal("deprecated"),
setting: string(),
message: string()
}),
object({
type: literal("other"),
message: string()
})
]);
var gatewayImageUsageSchema = object({
inputTokens: number().nullish(),
outputTokens: number().nullish(),
totalTokens: number().nullish()
});
var gatewayImageResponseSchema = object({
images: array(string()),
warnings: array(gatewayImageWarningSchema).optional(),
providerMetadata: record(string(), providerMetadataEntrySchema).optional(),
usage: gatewayImageUsageSchema.optional()
});
var GatewayVideoModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
this.maxVideosPerCall = Number.MAX_SAFE_INTEGER;
}
get provider() {
return this.config.provider;
}
async doGenerate({ prompt, n, aspectRatio, resolution, duration, fps, seed, generateAudio, image, frameImages, inputReferences, providerOptions, headers, abortSignal }) {
var _a11;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders), { accept: "text/event-stream" }),
body: {
prompt,
n,
...aspectRatio && { aspectRatio },
...resolution && { resolution },
...duration && { duration },
...fps && { fps },
...seed && { seed },
...generateAudio !== void 0 && { generateAudio },
...providerOptions && { providerOptions },
...image && { image: maybeEncodeVideoFile(image) },
...frameImages && { frameImages: frameImages.map((frame) => ({
...frame,
image: maybeEncodeVideoFile(frame.image)
})) },
...inputReferences && { inputReferences: inputReferences.map((reference) => maybeEncodeVideoFile(reference)) }
},
successfulResponseHandler: async ({ response, url, requestBodyValues }) => {
if (response.body == null) throw new APICallError({
message: "SSE response body is empty",
url,
requestBodyValues,
statusCode: response.status
});
const reader = parseJsonEventStream({
stream: response.body,
schema: gatewayVideoEventSchema
}).getReader();
const { done, value: parseResult } = await reader.read();
reader.releaseLock();
if (done || !parseResult) throw new APICallError({
message: "SSE stream ended without a data event",
url,
requestBodyValues,
statusCode: response.status
});
if (!parseResult.success) throw new APICallError({
message: "Failed to parse video SSE event",
cause: parseResult.error,
url,
requestBodyValues,
statusCode: response.status
});
const event = parseResult.value;
if (event.type === "error") throw new APICallError({
message: event.message,
statusCode: event.statusCode,
url,
requestBodyValues,
responseHeaders: Object.fromEntries([...response.headers]),
responseBody: JSON.stringify(event),
data: { error: {
message: event.message,
type: event.errorType,
param: event.param
} }
});
return {
value: {
videos: event.videos,
warnings: event.warnings,
providerMetadata: event.providerMetadata
},
responseHeaders: Object.fromEntries([...response.headers])
};
},
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
videos: responseBody.videos,
warnings: (_a11 = responseBody.warnings) != null ? _a11 : [],
providerMetadata: responseBody.providerMetadata,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
}
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
}
}
getUrl() {
return `${this.config.baseURL}/video-model`;
}
getModelConfigHeaders() {
return {
"ai-video-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
function maybeEncodeVideoFile(file) {
if (file.type === "file" && file.data instanceof Uint8Array) return {
...file,
data: convertUint8ArrayToBase64(file.data)
};
return file;
}
var providerMetadataEntrySchema2 = object({ videos: array(unknown()).optional() }).catchall(unknown());
var gatewayVideoDataSchema = union([object({
type: literal("url"),
url: string(),
mediaType: string()
}), object({
type: literal("base64"),
data: string(),
mediaType: string()
})]);
var gatewayVideoWarningSchema = discriminatedUnion("type", [
object({
type: literal("unsupported"),
feature: string(),
details: string().optional()
}),
object({
type: literal("compatibility"),
feature: string(),
details: string().optional()
}),
object({
type: literal("deprecated"),
setting: string(),
message: string()
}),
object({
type: literal("other"),
message: string()
})
]);
var gatewayVideoEventSchema = discriminatedUnion("type", [object({
type: literal("result"),
videos: array(gatewayVideoDataSchema),
warnings: array(gatewayVideoWarningSchema).optional(),
providerMetadata: record(string(), providerMetadataEntrySchema2).optional()
}), object({
type: literal("error"),
message: string(),
errorType: string(),
statusCode: number(),
param: unknown().nullable()
})]);
var GatewayRerankingModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
}
get provider() {
return this.config.provider;
}
async doRerank({ documents, query, topN, headers, abortSignal, providerOptions }) {
var _a11;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: {
documents,
query,
...topN != null ? { topN } : {},
...providerOptions ? { providerOptions } : {}
},
successfulResponseHandler: createJsonResponseHandler(gatewayRerankingResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
ranking: responseBody.ranking,
providerMetadata: responseBody.providerMetadata,
response: {
headers: responseHeaders,
body: rawValue
},
warnings: (_a11 = responseBody.warnings) != null ? _a11 : []
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
}
}
getUrl() {
return `${this.config.baseURL}/reranking-model`;
}
getModelConfigHeaders() {
return {
"ai-reranking-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
var gatewayRerankingWarningSchema = discriminatedUnion("type", [
object({
type: literal("unsupported"),
feature: string(),
details: string().optional()
}),
object({
type: literal("compatibility"),
feature: string(),
details: string().optional()
}),
object({
type: literal("deprecated"),
setting: string(),
message: string()
}),
object({
type: literal("other"),
message: string()
})
]);
var gatewayRerankingResponseSchema = lazySchema(() => zodSchema(object({
ranking: array(object({
index: number(),
relevanceScore: number()
})),
warnings: array(gatewayRerankingWarningSchema).optional(),
providerMetadata: record(string(), record(string(), unknown())).optional()
})));
var GatewaySpeechModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
}
get provider() {
return this.config.provider;
}
async doGenerate({ text, voice, outputFormat, instructions, speed, language, providerOptions, headers, abortSignal }) {
var _a11;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: {
text,
...voice && { voice },
...outputFormat && { outputFormat },
...instructions && { instructions },
...speed != null && { speed },
...language && { language },
...providerOptions && { providerOptions }
},
successfulResponseHandler: createJsonResponseHandler(gatewaySpeechResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
audio: responseBody.audio,
warnings: (_a11 = responseBody.warnings) != null ? _a11 : [],
providerMetadata: responseBody.providerMetadata,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders,
body: rawValue
}
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
}
}
getUrl() {
return `${this.config.baseURL}/speech-model`;
}
getModelConfigHeaders() {
return {
"ai-speech-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
var providerMetadataEntrySchema3 = object({}).catchall(unknown());
var gatewaySpeechWarningSchema = discriminatedUnion("type", [
object({
type: literal("unsupported"),
feature: string(),
details: string().optional()
}),
object({
type: literal("compatibility"),
feature: string(),
details: string().optional()
}),
object({
type: literal("deprecated"),
setting: string(),
message: string()
}),
object({
type: literal("other"),
message: string()
})
]);
var gatewaySpeechResponseSchema = object({
audio: string(),
warnings: array(gatewaySpeechWarningSchema).optional(),
providerMetadata: record(string(), providerMetadataEntrySchema3).optional()
});
var GatewayTranscriptionModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v4";
}
get provider() {
return this.config.provider;
}
async doGenerate({ audio, mediaType, providerOptions, headers, abortSignal }) {
var _a11, _b11, _c, _d;
const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
try {
const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({
url: this.getUrl(),
headers: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),
body: {
audio: audio instanceof Uint8Array ? convertUint8ArrayToBase64(audio) : audio,
mediaType,
...providerOptions && { providerOptions }
},
successfulResponseHandler: createJsonResponseHandler(gatewayTranscriptionResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
text: responseBody.text,
segments: (_a11 = responseBody.segments) != null ? _a11 : [],
language: (_b11 = responseBody.language) != null ? _b11 : void 0,
durationInSeconds: (_c = responseBody.durationInSeconds) != null ? _c : void 0,
warnings: (_d = responseBody.warnings) != null ? _d : [],
providerMetadata: responseBody.providerMetadata,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders,
body: rawValue
}
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders != null ? resolvedHeaders : {}));
}
}
async doStream(options) {
var _a11, _b11, _c, _d, _e;
const currentDate = (_c = (_b11 = (_a11 = this.config._internal) == null ? void 0 : _a11.currentDate) == null ? void 0 : _b11.call(_a11)) != null ? _c : /* @__PURE__ */ new Date();
const headers = combineHeaders(await resolve((_d = this.config.headers) != null ? _d : {}), (_e = options.headers) != null ? _e : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders));
const authMethod = await parseAuthMethod(headers);
const startFrame = {
type: "transcription-stream.start",
inputAudioFormat: options.inputAudioFormat,
...options.providerOptions != null && { providerOptions: options.providerOptions },
...options.includeRawChunks != null && { includeRawChunks: options.includeRawChunks }
};
return {
stream: createGatewayTranscriptionStream({
webSocket: this.config.webSocket,
url: toGatewayTranscriptionUrl(this.config.baseURL, this.modelId),
protocols: getProtocolsFromHeaders(headers),
headers,
startFrame,
audio: options.audio,
abortSignal: options.abortSignal,
authMethod
}),
request: { body: startFrame },
response: {
timestamp: currentDate,
modelId: this.modelId
}
};
}
getUrl() {
return `${this.config.baseURL}/transcription-model`;
}
getModelConfigHeaders() {
return {
"ai-transcription-model-specification-version": "4",
"ai-model-id": this.modelId
};
}
};
function toGatewayTranscriptionUrl(baseURL, modelId) {
const url = new URL(`${baseURL.replace(/^http/, "ws")}/transcription-model`);
url.searchParams.set("ai-model-id", modelId);
return url.toString();
}
function getProtocolsFromHeaders(headers) {
const normalizedHeaders = normalizeHeaders(headers);
const authorization = normalizedHeaders.authorization;
const token = (authorization == null ? void 0 : authorization.startsWith("Bearer ")) ? authorization.slice(7) : void 0;
return token == null ? ["ai-gateway-transcription.v1"] : getGatewayTranscriptionProtocols(token, { teamIdOrSlug: normalizedHeaders[VERCEL_AI_GATEWAY_TEAM_HEADER] });
}
var MAX_AUDIO_FRAME_BYTES = 64 * 1024;
function createGatewayTranscriptionStream({ webSocket, url, protocols, headers, startFrame, audio, abortSignal, authMethod }) {
let finished = false;
let cleanup = () => {};
return new ReadableStream({
start: (controller) => {
let audioReader;
let hasServerErrorPart = false;
let lastServerError;
let audioStopped = false;
let connection;
cleanup = (closeCode) => {
if (audioReader != null) audioReader.cancel().catch(() => {});
else audio.cancel().catch(() => {});
connection?.close(closeCode);
};
const stopAudio = () => {
audioStopped = true;
if (audioReader != null) {
audioReader.cancel().catch(() => {});
audioReader = void 0;
} else audio.cancel().catch(() => {});
};
const finishWithError = (error) => {
if (finished) return;
finished = true;
cleanup();
errorControllerWithGatewayError(controller, error, authMethod);
};
const sendAudio = async (socket) => {
const reader = audio.getReader();
audioReader = reader;
try {
while (true) {
const { done, value } = await reader.read();
if (done || finished) break;
const bytes = typeof value === "string" ? convertBase64ToUint8Array(value) : value;
for (let offset = 0; offset < bytes.length; offset += MAX_AUDIO_FRAME_BYTES) {
if (finished) break;
socket.send(bytes.subarray(offset, offset + MAX_AUDIO_FRAME_BYTES));
await waitForWebSocketBufferDrain(socket);
}
}
} finally {
reader.releaseLock();
if (audioReader === reader) audioReader = void 0;
}
if (!finished && !audioStopped) socket.send(JSON.stringify({ type: "transcription-stream.audio-done" }));
};
connection = connectToWebSocket({
url,
protocols,
headers,
webSocket,
abortSignal,
onAbort: (reason) => {
if (finished) return;
finished = true;
cleanup();
controller.error(reason);
},
onProcessingError: finishWithError,
onOpen: (socket) => {
socket.send(JSON.stringify(startFrame));
sendAudio(socket).catch(finishWithError);
},
onMessageText: (text) => {
if (finished) return;
const part = parseTranscriptionStreamPart(text);
if (part == null) return;
if (part.type === "finish") {
finished = true;
controller.enqueue(part);
controller.close();
cleanup(1e3);
return;
}
if (part.type === "error") {
hasServerErrorPart = true;
lastServerError = part.error;
stopAudio();
}
controller.enqueue(part);
},
onSocketError: () => {
finishWithError(/* @__PURE__ */ new Error("Connection error on AI Gateway transcription stream"));
},
onClose: () => {
if (hasServerErrorPart) {
if (finished) return;
createErrorFromServerErrorPart(lastServerError, authMethod).then(finishWithError);
return;
}
finishWithError(/* @__PURE__ */ new Error("AI Gateway transcription stream closed before a finish part was received"));
}
});
},
cancel: () => {
if (finished) return;
finished = true;
cleanup();
}
});
}
var providerMetadataEntrySchema4 = object({}).catchall(unknown());
var gatewayTranscriptionWarningSchema = discriminatedUnion("type", [
object({
type: literal("unsupported"),
feature: string(),
details: string().optional()
}),
object({
type: literal("compatibility"),
feature: string(),
details: string().optional()
}),
object({
type: literal("deprecated"),
setting: string(),
message: string()
}),
object({
type: literal("other"),
message: string()
})
]);
var gatewayTranscriptionResponseSchema = object({
text: string(),
segments: array(object({
text: string(),
startSecond: number(),
endSecond: number()
})).optional(),
language: string().nullish(),
durationInSeconds: number().nullish(),
warnings: array(gatewayTranscriptionWarningSchema).optional(),
providerMetadata: record(string(), providerMetadataEntrySchema4).optional()
});
async function errorControllerWithGatewayError(controller, error, authMethod) {
controller.error(await asGatewayError(error, authMethod));
}
function getServerErrorMessage(error) {
if (error != null && typeof error === "object" && "message" in error && typeof error.message === "string") return error.message;
return getErrorMessage(error);
}
var SERVER_ERROR_STATUS_CODES = {
authentication_error: 401,
failed_dependency: 424,
forbidden: 403,
internal_server_error: 500,
invalid_request_error: 400,
model_not_found: 404,
rate_limit_exceeded: 429
};
async function createErrorFromServerErrorPart(error, authMethod) {
if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string" && "type" in error && typeof error.type === "string" && error.type in SERVER_ERROR_STATUS_CODES) return createGatewayErrorFromResponse({
response: { error: {
message: error.message,
type: error.type
} },
statusCode: SERVER_ERROR_STATUS_CODES[error.type],
authMethod
});
return /* @__PURE__ */ new Error(`AI Gateway transcription stream failed: ${getServerErrorMessage(error)}`);
}
var GatewayRealtimeModel = class {
constructor(modelId, config) {
this.specificationVersion = "v4";
this.modelId = modelId;
this.provider = config.provider;
this.config = config;
}
/**
* Mints a single-use, short-lived client secret (`vcst_`) the browser uses to
* open the realtime WebSocket without ever holding the long-lived Gateway
* credential. The customer's server calls this (via
* `gateway.experimental_realtime.getToken`) and hands the returned token to
* the browser, which connects with it through the `ai-gateway-auth.<token>`
* subprotocol. `expiresAfterSeconds` is forwarded to the mint endpoint;
* `sessionConfig` is intentionally unused here — it is applied later via the
* normalized `session-update` event.
*/
async doCreateClientSecret(options) {
const secret = await this.config.createClientSecret({
modelId: this.modelId,
...(options == null ? void 0 : options.expiresAfterSeconds) != null && { expiresAfterSeconds: options.expiresAfterSeconds }
});
return {
token: secret.token,
url: toGatewayRealtimeUrl(this.config.baseURL, this.modelId),
...secret.expiresAt != null && { expiresAt: secret.expiresAt }
};
}
getWebSocketConfig(options) {
return {
url: options.url,
protocols: getGatewayRealtimeProtocols(options.token, { teamIdOrSlug: this.config.teamIdOrSlug })
};
}
parseServerEvent(raw) {
return raw;
}
serializeClientEvent(event) {
return event;
}
buildSessionConfig(config) {
return config;
}
};
function toGatewayRealtimeUrl(baseURL, modelId) {
const url = new URL(`${baseURL.replace(/^http/, "ws")}/realtime-model`);
url.searchParams.set("ai-model-id", modelId);
return url.toString();
}
var exaSearchToolFactory = createProviderExecutedToolFactory({
id: "gateway.exa_search",
inputSchema: lazySchema(() => zodSchema(object({
query: string().describe("Natural-language web search query. This is required."),
type: _enum([
"auto",
"fast",
"instant"
]).optional().describe("Search method. Use auto for the default balance of speed and quality."),
num_results: number().optional().describe("Maximum number of results to return (1-100, default: 10)."),
category: _enum([
"company",
"people",
"research paper",
"news",
"personal site",
"financial report"
]).optional().describe("Optional content category to focus results."),
user_location: string().optional().describe("Two-letter ISO country code such as 'US'."),
include_domains: array(string()).optional().describe("Only return results from these domains."),
exclude_domains: array(string()).optional().describe("Exclude results from these domains."),
start_published_date: string().optional().describe("Only return links published after this ISO 8601 date."),
end_published_date: string().optional().describe("Only return links published before this ISO 8601 date."),
contents: object({
text: union([boolean(), object({
max_characters: number().optional(),
include_html_tags: boolean().optional(),
verbosity: _enum([
"compact",
"standard",
"full"
]).optional(),
include_sections: array(_enum([
"header",
"navigation",
"banner",
"body",
"sidebar",
"footer",
"metadata"
])).optional(),
exclude_sections: array(_enum([
"header",
"navigation",
"banner",
"body",
"sidebar",
"footer",
"metadata"
])).optional()
})]).optional(),
highlights: union([boolean(), object({
query: string().optional(),
max_characters: number().optional()
})]).optional(),
max_age_hours: number().optional(),
livecrawl_timeout: number().optional(),
subpages: number().optional(),
subpage_target: union([string(), array(string())]).optional(),
extras: object({
links: number().optional(),
image_links: number().optional()
}).optional()
}).optional().describe("Controls extracted page content and freshness.")
}))),
outputSchema: lazySchema(() => zodSchema(union([object({
requestId: string(),
searchType: string().optional(),
resolvedSearchType: string().optional(),
results: array(object({
title: string(),
url: string(),
id: string(),
publishedDate: string().nullable().optional(),
author: string().nullable().optional(),
image: string().nullable().optional(),
favicon: string().nullable().optional(),
text: string().optional(),
highlights: array(string()).optional(),
highlightScores: array(number()).optional(),
summary: string().optional(),
subpages: array(any()).optional(),
extras: object({
links: array(string()).optional(),
imageLinks: array(string()).optional()
}).optional()
})),
costDollars: object({
total: number().optional(),
search: record(string(), number()).optional()
}).optional()
}), object({
error: _enum([
"api_error",
"rate_limit",
"timeout",
"invalid_input",
"configuration_error",
"execution_error",
"unknown"
]),
statusCode: number().optional(),
message: string()
})])))
});
var exaSearch = (config = {}) => exaSearchToolFactory(config);
var parallelSearchToolFactory = createProviderExecutedToolFactory({
id: "gateway.parallel_search",
inputSchema: lazySchema(() => zodSchema(object({
objective: string().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),
search_queries: array(string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),
mode: _enum(["one-shot", "agentic"]).optional().describe("Mode preset: \"one-shot\" for comprehensive results with longer excerpts (default), \"agentic\" for concise, token-efficient results for multi-step workflows."),
max_results: number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),
source_policy: object({
include_domains: array(string()).optional().describe("Limit results to these domains. Use plain domain names only — e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),
exclude_domains: array(string()).optional().describe("Exclude results from these domains. Use plain domain names only — e.g. example.com or sub.example.gov, or a bare extension like .edu. Do not include a scheme, path, or port (e.g. not https://example.com/page)."),
after_date: string().optional().describe("Only include results published after this date. Use an ISO 8601 calendar date formatted YYYY-MM-DD (e.g. 2025-01-01); do not include a time.")
}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),
excerpts: object({
max_chars_per_result: number().optional().describe("Maximum characters per result."),
max_chars_total: number().optional().describe("Maximum total characters across all results.")
}).optional().describe("Excerpt configuration for controlling result length."),
fetch_policy: object({ max_age_seconds: number().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.") }).optional().describe("Fetch policy for controlling content freshness.")
}))),
outputSchema: lazySchema(() => zodSchema(union([object({
searchId: string(),
results: array(object({
url: string(),
title: string(),
excerpt: string(),
publishDate: string().nullable().optional(),
relevanceScore: number().optional()
}))
}), object({
error: _enum([
"api_error",
"rate_limit",
"timeout",
"invalid_input",
"configuration_error",
"unknown"
]),
statusCode: number().optional(),
message: string()
})])))
});
var parallelSearch = (config = {}) => parallelSearchToolFactory(config);
var perplexitySearchToolFactory = createProviderExecutedToolFactory({
id: "gateway.perplexity_search",
inputSchema: lazySchema(() => zodSchema(object({
query: union([string(), array(string())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),
max_results: number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),
max_tokens_per_page: number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),
max_tokens: number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),
country: string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),
search_domain_filter: array(string()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),
search_language_filter: array(string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),
search_after_date: string().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),
search_before_date: string().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),
last_updated_after_filter: string().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),
last_updated_before_filter: string().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),
search_recency_filter: _enum([
"day",
"week",
"month",
"year"
]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")
}))),
outputSchema: lazySchema(() => zodSchema(union([object({
results: array(object({
title: string(),
url: string(),
snippet: string(),
date: string().optional(),
lastUpdated: string().optional()
})),
id: string()
}), object({
error: _enum([
"api_error",
"rate_limit",
"timeout",
"invalid_input",
"unknown"
]),
statusCode: number().optional(),
message: string()
})])))
});
var perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
var gatewayTools = {
/**
* Search the web using Exa for current information and token-efficient
* excerpts optimized for agent workflows.
*
* Supports search type, category, domain, date, location, and content
* extraction controls.
*/
exaSearch,
/**
* Search the web using Parallel AI's Search API for LLM-optimized excerpts.
*
* Takes a natural language objective and returns relevant excerpts,
* replacing multiple keyword searches with a single call for broad
* or complex queries. Supports different search types for depth vs
* breadth tradeoffs.
*/
parallelSearch,
/**
* Search the web using Perplexity's Search API for real-time information,
* news, research papers, and articles.
*
* Provides ranked search results with advanced filtering options including
* domain, language, date range, and recency filters.
*/
perplexitySearch
};
async function getVercelRequestId() {
var _a11;
return (_a11 = (0, import_dist.getContext)().headers) == null ? void 0 : _a11["x-vercel-id"];
}
var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
var gatewayClientSecretResponseSchema = object({
token: string(),
expiresAt: number().nullish()
});
function createGateway(options = {}) {
var _a11, _b11;
let pendingMetadata = null;
let metadataCache = null;
const cacheRefreshMillis = (_a11 = options.metadataCacheRefreshMillis) != null ? _a11 : 1e3 * 60 * 5;
let lastFetchTime = 0;
const baseURL = (_b11 = withoutTrailingSlash(options.baseURL)) != null ? _b11 : "https://ai-gateway.vercel.sh/v4/ai";
const createAuthHeaders = (auth) => withUserAgentSuffix({
Authorization: `Bearer ${auth.token}`,
"ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
[GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
...options.teamIdOrSlug != null ? { [VERCEL_AI_GATEWAY_TEAM_HEADER]: options.teamIdOrSlug } : {},
...options.headers
}, `ai-sdk/gateway/4.0.20`);
const getHeaders = async () => {
try {
return createAuthHeaders(await getGatewayAuthToken(options));
} catch (error) {
throw GatewayAuthenticationError.createContextualError({
apiKeyProvided: false,
oidcTokenProvided: false,
statusCode: 401,
cause: error
});
}
};
const getRealtimeAuthToken = async () => {
try {
return await getGatewayAuthToken(options);
} catch (error) {
throw GatewayAuthenticationError.createContextualError({
apiKeyProvided: false,
oidcTokenProvided: false,
statusCode: 401,
cause: error
});
}
};
const mintRealtimeClientSecret = async (params) => {
assertGatewayRealtimeServerEnvironment();
const auth = await getRealtimeAuthToken();
const headers = createAuthHeaders(auth);
const url = new URL("/v1/realtime/client-secrets", baseURL).toString();
try {
const { value } = await postJsonToApi({
url,
headers,
body: {
model: params.modelId,
...params.expiresAfterSeconds != null && { expiresIn: params.expiresAfterSeconds }
},
successfulResponseHandler: createJsonResponseHandler(gatewayClientSecretResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: any(),
errorToMessage: (data) => data
}),
fetch: options.fetch
});
return {
token: value.token,
...value.expiresAt != null && { expiresAt: value.expiresAt }
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(headers));
}
};
const createO11yHeaders = () => {
const deploymentId = loadOptionalSetting({
settingValue: void 0,
environmentVariableName: "VERCEL_DEPLOYMENT_ID"
});
const environment = loadOptionalSetting({
settingValue: void 0,
environmentVariableName: "VERCEL_ENV"
});
const region = loadOptionalSetting({
settingValue: void 0,
environmentVariableName: "VERCEL_REGION"
});
const projectId = loadOptionalSetting({
settingValue: void 0,
environmentVariableName: "VERCEL_PROJECT_ID"
});
return async () => {
const requestId = await getVercelRequestId();
return {
...deploymentId && { "ai-o11y-deployment-id": deploymentId },
...environment && { "ai-o11y-environment": environment },
...region && { "ai-o11y-region": region },
...requestId && { "ai-o11y-request-id": requestId },
...projectId && { "ai-o11y-project-id": projectId }
};
};
};
const createLanguageModel = (modelId) => {
return new GatewayLanguageModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
const getAvailableModels = async () => {
var _a12, _b12, _c;
const now = (_c = (_b12 = (_a12 = options._internal) == null ? void 0 : _a12.currentDate) == null ? void 0 : _b12.call(_a12).getTime()) != null ? _c : Date.now();
if (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {
lastFetchTime = now;
pendingMetadata = new GatewayFetchMetadata({
baseURL,
headers: getHeaders,
fetch: options.fetch
}).getAvailableModels().then((metadata) => {
metadataCache = metadata;
return metadata;
}).catch(async (error) => {
throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
});
}
return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;
};
const getCredits = async () => {
return new GatewayFetchMetadata({
baseURL,
headers: getHeaders,
fetch: options.fetch
}).getCredits().catch(async (error) => {
throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
});
};
const getSpendReport = async (params) => {
return new GatewaySpendReport({
baseURL,
headers: getHeaders,
fetch: options.fetch
}).getSpendReport(params).catch(async (error) => {
throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
});
};
const getGenerationInfo = async (params) => {
return new GatewayGenerationInfoFetcher({
baseURL,
headers: getHeaders,
fetch: options.fetch
}).getGenerationInfo(params).catch(async (error) => {
throw await asGatewayError(error, await parseAuthMethod(await getHeaders()));
});
};
const provider = function(modelId) {
if (new.target) throw new Error("The Gateway Provider model function cannot be called with the new keyword.");
return createLanguageModel(modelId);
};
provider.specificationVersion = "v4";
provider.getAvailableModels = getAvailableModels;
provider.getCredits = getCredits;
provider.getSpendReport = getSpendReport;
provider.getGenerationInfo = getGenerationInfo;
provider.imageModel = (modelId) => {
return new GatewayImageModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
provider.languageModel = createLanguageModel;
const createEmbeddingModel = (modelId) => {
return new GatewayEmbeddingModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
provider.embeddingModel = createEmbeddingModel;
provider.textEmbeddingModel = createEmbeddingModel;
provider.videoModel = (modelId) => {
return new GatewayVideoModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
const createRerankingModel = (modelId) => {
return new GatewayRerankingModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
provider.rerankingModel = createRerankingModel;
provider.reranking = createRerankingModel;
const createSpeechModel = (modelId) => {
return new GatewaySpeechModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
provider.speechModel = createSpeechModel;
provider.speech = createSpeechModel;
const createTranscriptionModel = (modelId) => {
return new GatewayTranscriptionModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders(),
webSocket: options.webSocket
});
};
provider.transcriptionModel = createTranscriptionModel;
provider.transcription = createTranscriptionModel;
const createRealtimeModel = (modelId) => new GatewayRealtimeModel(modelId, {
provider: "gateway.realtime",
baseURL,
teamIdOrSlug: options.teamIdOrSlug,
createClientSecret: mintRealtimeClientSecret
});
provider.experimental_realtime = Object.assign((modelId) => createRealtimeModel(modelId), { getToken: async (tokenOptions) => {
const { model: modelId, ...secretOptions } = tokenOptions;
const secret = await createRealtimeModel(modelId).doCreateClientSecret(secretOptions);
return {
token: secret.token,
url: secret.url,
...secret.expiresAt != null && { expiresAt: secret.expiresAt }
};
} });
provider.chat = provider.languageModel;
provider.embedding = provider.embeddingModel;
provider.image = provider.imageModel;
provider.video = provider.videoModel;
provider.tools = gatewayTools;
return provider;
}
var gateway = createGateway();
async function getGatewayAuthToken(options) {
const apiKey = loadOptionalSetting({
settingValue: options.apiKey,
environmentVariableName: "AI_GATEWAY_API_KEY"
});
if (apiKey) return {
token: apiKey,
authMethod: "api-key"
};
return {
token: await (0, import_dist.getVercelOidcToken)(),
authMethod: "oidc"
};
}
function assertGatewayRealtimeServerEnvironment() {
if (typeof globalThis.window !== "undefined") throw new Error("AI Gateway realtime client secrets must be minted server-side: minting needs your Gateway credential, which must never reach the browser. Call gateway.experimental_realtime.getToken() from your server and pass the returned token to the client.");
}
//#endregion
export { AISDKError as $, safeParseJSON as A, boolean as B, isProviderReference as C, readResponseWithSizeLimit as D, lazySchema as E, zodSchema as F, never as G, discriminatedUnion as H, _enum as I, record as J, number as K, _instanceof as L, tool as M, validateTypes as N, resolve as O, withUserAgentSuffix as P, unknown as Q, _null as R, isFullMediaType as S, jsonSchema as T, lazy as U, custom as V, literal as W, string as X, strictObject as Y, union as Z, filterNullable as _, require_token_error as a, isBuffer as b, asArray as c, convertBase64ToUint8Array as d, APICallError as et, convertUint8ArrayToBase64 as f, fetchWithValidatedRedirects as g, executeTool as h, require_token_util as i, getErrorMessage as it, safeValidateTypes as j, retryWithExponentialBackoff as k, asSchema as l, detectMediaType as m, GatewayError as n, TypeValidationError as nt, DelayedPromise as o, createIdGenerator as p, object as q, gateway as r, UnsupportedFunctionalityError as rt, DownloadError as s, GatewayAuthenticationError as t, InvalidPromptError as tt, cancelResponseBody as u, getRuntimeEnvironmentUserAgent as v, isUrlSupported as w, isExecutableTool as x, isAbortError as y, array as z };