@mastra/core
Version:
4,868 lines • 167 kB
JavaScript
const require_rolldown_runtime = require("./rolldown-runtime-BrhgMLW6.cjs");
let zod_v4 = require("zod/v4");
zod_v4 = require_rolldown_runtime.__toESM(zod_v4, 1);
let zod_v3 = require("zod/v3");
let zod = require("zod");
// ../_vendored/ai_v6/dist/dist-BoOIE3nE.js
var marker$1 = "vercel.ai.error";
var symbol$1 = Symbol.for(marker$1);
var _a$1;
var _b$1;
var AISDKError = class _AISDKError extends (_b$1 = Error, _a$1 = symbol$1, _b$1) {
/**
* 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: name14, message, cause }) {
super(message);
this[_a$1] = true;
this.name = name14;
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, marker15) {
const markerSymbol = Symbol.for(marker15);
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
}
};
var name$1 = "AI_APICallError";
var marker2$1 = `vercel.ai.error.${name$1}`;
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$1,
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$1(error) {
if (error == null) return "unknown error";
if (typeof error === "string") return error;
if (error instanceof Error) return error.message;
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;
var InvalidResponseDataError = 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$1(cause)}`,
cause
});
this[_a7$1] = true;
this.text = text;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker7$1);
}
};
var name12 = "AI_TypeValidationError";
var marker13 = `vercel.ai.error.${name12}`;
var symbol13 = Symbol.for(marker13);
var _a13;
var _b13;
var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
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: name12,
message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
Error message: ${getErrorMessage$1(cause)}`,
cause
});
this[_a13] = true;
this.value = value;
this.context = context;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker13);
}
/**
* 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 _a15, _b15, _c;
if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a15 = cause.context) == null ? void 0 : _a15.field) === (context == null ? void 0 : context.field) && ((_b15 = cause.context) == null ? void 0 : _b15.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 name13 = "AI_UnsupportedFunctionalityError";
var marker14 = `vercel.ai.error.${name13}`;
var symbol14 = Symbol.for(marker14);
var _a14;
var _b14;
var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
constructor({ functionality, message = `'${functionality}' functionality not supported.` }) {
super({
name: name13,
message
});
this[_a14] = true;
this.functionality = functionality;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker14);
}
};
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);
value2.includes("\0") || (id = 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":
value.includes("\0") || (id = 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
}));
}
}
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;
}
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);
}
});
}
};
function combineHeaders(...headers) {
return headers.reduce((combinedHeaders, currentHeaders) => ({
...combinedHeaders,
...currentHeaders
}), {});
}
async function delay(delayInMs, options) {
if (delayInMs == null) return;
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");
}
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";
}
};
function extractResponseHeaders(response) {
return Object.fromEntries([...response.headers]);
}
var { btoa, atob } = globalThis;
function convertBase64ToUint8Array(base64String) {
const latin1string = atob(base64String.replace(/-/g, "+").replace(/_/g, "/"));
const bytes = new Uint8Array(latin1string.length);
for (let i = 0; i < latin1string.length; i++) bytes[i] = latin1string.charCodeAt(i);
return bytes;
}
function convertUint8ArrayToBase64(array) {
var _a2;
if (typeof ((_a2 = globalThis.Buffer) == null ? void 0 : _a2.from) === "function") return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("base64");
const chunks = [];
const chunkSize = 4096;
for (let i = 0; i < array.length; i += chunkSize) chunks.push(String.fromCodePoint(...array.subarray(i, i + chunkSize)));
return btoa(chunks.join(""));
}
var typedArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
var arrayBufferByteLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
function isUint8Array(value) {
return ArrayBuffer.isView(value) && typedArrayTag.call(value) === "Uint8Array";
}
function isArrayBuffer(value) {
if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
try {
arrayBufferByteLength.call(value);
return true;
} catch (e) {
return false;
}
}
async function cancelResponseBody(response) {
var _a2;
try {
await ((_a2 = response.body) == null ? void 0 : _a2.cancel());
} catch (e) {}
}
var name$2 = "AI_DownloadError";
var marker = `vercel.ai.error.${name$2}`;
var symbol$2 = Symbol.for(marker);
var _a$2;
var _b$2;
var DownloadError = class extends (_b$2 = AISDKError, _a$2 = symbol$2, _b$2) {
constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {
super({
name: name$2,
message,
cause
});
this[_a$2] = 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;
}
}
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") || hostname.endsWith(".internal")) 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`
});
}
}
function validateDownloadAddress({ address, family, hostname }) {
if (family === 4 ? !isIPv4(address) || isPrivateIPv4(address) : family === 6 ? isPrivateIPv6(address) : true) throw new DownloadError({
url: hostname,
message: `Hostname ${hostname} resolved to disallowed IP address ${address}`
});
}
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 === 168) return true;
if (a === 198 && (b === 18 || b === 19)) return true;
if (a >= 240) 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 (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;
}
function createSafeLookup(lookup) {
return ((hostname, options, callback) => {
lookup(hostname, {
...options,
all: true
}, (error, addresses) => {
if (error) {
callback(error);
return;
}
try {
const [firstAddress] = addresses;
if (firstAddress == null) throw new Error(`Hostname ${hostname} did not resolve to an address`);
for (const { address, family } of addresses) validateDownloadAddress({
address,
family,
hostname
});
if (options.all === true) callback(null, addresses);
else callback(null, firstAddress.address, firstAddress.family);
} catch (error2) {
callback(error2 instanceof Error ? error2 : new Error(String(error2)));
}
});
});
}
var safeNodeFetchPromise;
function isNodeRuntime() {
var _a2, _b2, _c;
const runtimeProcess = globalThis.process;
return ((_a2 = runtimeProcess == null ? void 0 : runtimeProcess.release) == null ? void 0 : _a2.name) === "node" && ((_b2 = runtimeProcess.versions) == null ? void 0 : _b2.bun) == null && ((_c = runtimeProcess.versions) == null ? void 0 : _c.deno) == null && runtimeProcess.title !== "workerd" && globalThis.EdgeRuntime == null;
}
async function getDefaultDownloadFetch() {
if (!isNodeRuntime()) return globalThis.fetch;
return safeNodeFetchPromise != null ? safeNodeFetchPromise : safeNodeFetchPromise = createSafeNodeFetch();
}
async function createSafeNodeFetch() {
const [module, { lookup }] = await Promise.all([loadNodeModule("node:module"), loadNodeModule("node:dns")]);
const { Agent, fetch } = module.createRequire(getCurrentModulePath())("undici");
const dispatcher = new Agent({ connect: { lookup: createSafeLookup(lookup) } });
return ((input, init) => fetch(input, {
...init,
dispatcher
}));
}
async function loadNodeModule(id) {
var _a2;
const processWithBuiltins = globalThis.process;
const builtinModule = (_a2 = processWithBuiltins == null ? void 0 : processWithBuiltins.getBuiltinModule) == null ? void 0 : _a2.call(processWithBuiltins, id);
if (builtinModule == null) throw new Error(`Node.js built-in module ${id} is unavailable`);
return builtinModule;
}
function getCurrentModulePath() {
const originalPrepareStackTrace = Error.prepareStackTrace;
try {
Error.prepareStackTrace = (_error, callSites) => callSites;
const error = /* @__PURE__ */ new Error("Capture current module path");
Error.captureStackTrace(error, getCurrentModulePath);
const [caller] = error.stack;
const fileName = caller == null ? void 0 : caller.getFileName();
if (fileName == null) throw new Error("Unable to determine the current module path");
return fileName;
} finally {
Error.prepareStackTrace = originalPrepareStackTrace;
}
}
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;
}
var MAX_DOWNLOAD_REDIRECTS = 10;
var REDIRECT_STATUS_CODES = /* @__PURE__ */ new Set([
301,
302,
303,
307,
308
]);
async function getValidatedFetch(customFetch) {
return customFetch == null || customFetch === globalThis.fetch ? await getDefaultDownloadFetch() : customFetch;
}
async function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects = MAX_DOWNLOAD_REDIRECTS, fetch: customFetch, trustedOrigin }) {
var _a2;
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++) {
const isTrustedHop = trustedOrigin !== void 0 && isSameOrigin(currentUrl, trustedOrigin);
if (!isTrustedHop) validateDownloadUrl(currentUrl);
const fetch = isTrustedHop && customFetch != null ? customFetch : isTrustedHop ? globalThis.fetch : await getValidatedFetch(customFetch);
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 = (_a2 = response.headers) == null ? void 0 : _a2.get("location");
if (REDIRECT_STATUS_CODES.has(response.status) && location) {
cancelResponseBody(response);
const nextUrl = new URL(location, currentUrl).toString();
if (new URL(currentUrl).protocol === "https:" && new URL(nextUrl).protocol === "http:") throw new DownloadError({
url,
message: "Redirect from HTTPS to HTTP was blocked"
});
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})`
});
}
var DEFAULT_MAX_DOWNLOAD_SIZE = 2147483648;
async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) {
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();
} catch (e) {} 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;
}
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 getErrorMessage(error) {
if (error == null) return "unknown error";
if (typeof error === "string") return error;
if (error instanceof Error) return error.message;
return JSON.stringify(error);
}
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 RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
"ConnectionRefused",
"ConnectionClosed",
"FailedToOpenSocket",
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"EPIPE",
"UND_ERR_SOCKET",
"UND_ERR_HEADERS_TIMEOUT",
"UND_ERR_BODY_TIMEOUT",
"UND_ERR_CONNECT_TIMEOUT"
]);
function findNetworkError(error) {
const visited = /* @__PURE__ */ new Set();
let current = error;
while (current instanceof Error && !visited.has(current)) {
visited.add(current);
const errorWithCode = current;
if (typeof errorWithCode.code === "string" && RETRYABLE_NETWORK_ERROR_CODES.has(errorWithCode.code)) return errorWithCode;
current = current.cause;
}
}
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
});
}
const networkError = findNetworkError(error);
if (networkError != null) {
if (APICallError.isInstance(error)) return new APICallError({
message: error.message,
cause: error.cause,
url: error.url,
requestBodyValues: error.requestBodyValues,
statusCode: error.statusCode,
responseHeaders: error.responseHeaders,
responseBody: error.responseBody,
data: error.data,
isRetryable: true
});
return new APICallError({
message: `Cannot connect to API: ${error instanceof Error ? error.message : networkError.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 VERSION$1 = "4.0.66";
var getOriginalFetch = () => globalThis.fetch;
var getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin }) => {
try {
const requestFetch = fetch != null ? fetch : getOriginalFetch();
const requestHeaders = withUserAgentSuffix(credentialedOrigin !== void 0 && !isSameOrigin(url, credentialedOrigin) ? {} : headers, `ai-sdk/provider-utils/${VERSION$1}`, getRuntimeEnvironmentUserAgent());
const response = validateUrl ? await fetchWithValidatedRedirects({
url,
headers: requestHeaders,
abortSignal,
fetch,
trustedOrigin
}) : await requestFetch(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 isUrlSupported({ mediaType, url, supportedUrls }) {
mediaType = mediaType.toLowerCase();
return Object.entries(supportedUrls).map(([key, value]) => {
const mediaType2 = key.toLowerCase();
return mediaType2 === "*" || mediaType2 === "*/*" ? {
mediaTypePrefix: "",
regexes: value
} : {
mediaTypePrefix: mediaType2.replace(/\*/, ""),
regexes: value
};
}).filter(({ mediaTypePrefix }) => mediaTypePrefix === "" || mediaTypePrefix.endsWith("/") ? mediaType.startsWith(mediaTypePrefix) : mediaType === 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")) {
const { additionalProperties } = jsonSchema2;
jsonSchema2.additionalProperties = additionalProperties != null && typeof additionalProperties !== "boolean" ? visit(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) !== zod_v3.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;
}
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, i) => 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;
}
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, ...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;
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;
case "nanoid": addPattern(res, zodPatterns.nanoid, check.message, refs);
}
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) === zod_v3.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === zod_v3.ZodFirstPartyTypeKind.ZodEnum) return {
...schema,
propertyNames: { enum: def.keyType._def.values }
};
else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === zod_v3.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === zod_v3.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
const { 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;
}
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 a = parseDef(def.in._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
});
return { allOf: [a, parseDef(def.out._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
a ? "1" : "0"
]
})].filter((x) => x !== 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 zod_v3.ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def);
case zod_v3.ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def);
case zod_v3.ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef();
case zod_v3.ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef();
case zod_v3.ZodFirstPartyTypeKind.ZodNull: return parseNullDef();
case zod_v3.ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodUnion:
case zod_v3.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def);
case zod_v3.ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def);
case zod_v3.ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def);
case zod_v3.ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;
case zod_v3.ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodNaN:
case zod_v3.ZodFirstPartyTypeKind.ZodNever: return parseNeverDef();
case zod_v3.ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodAny: return parseAnyDef();
case zod_v3.ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef();
case zod_v3.ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs);
case zod_v3.ZodFirstPartyTypeKind.ZodFunction:
case zod_v3.ZodFirstPartyTypeKind.ZodVoid:
case zod_v3.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(zod_v4.toJSONSchema(zodSchema2, {
target: "draft-7",
io: "input",
reused: useReferences ? "ref" : "inline"
})), { validate: async (value) => {
const result = await zod_v4.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 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 }) => 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/${VERSION$1}`, 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 createProviderToolFactoryWithOutputSchema({ id, inputSchema, outputSchema, supportsDeferredResults }) {
return ({ execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({
type: "provider",
id,
args,
inputSchema,
outputSchema,
execute,
needsApproval,
toModelOutput,
onInputStart,
onInputDelta,
onInputAvailable,
supportsDeferredResults
});
}
async function resolve(value) {
if (typeof value === "function") value = value();
return 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 textDecoder = new TextDecoder();
function wrapResponseBodyStream({ stream, url, requestBodyValues, statusCode, responseHeaders }) {
const reader = stream.getReader();
let readerReleased = false;
const releaseReader = () => {
if (!readerReleased) {
reader.releaseLock();
readerReleased = true;
}
};
return new ReadableStream({
async pull(controller) {
try {
const { done, value } = await reader.read();
if (done) {
releaseReader();
controller.close();
} else controller.enqueue(value);
} catch (error) {
releaseReader();
if (isAbortError(error)) {
controller.error(error);
return;
}
controller.error(handleFetchError({
error: new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode,
url,
responseHeaders,
requestBodyValues
}),
url,
requestBodyValues
}));
}
},
async cancel(reason) {
try {
await reader.cancel(reason);
} finally {
releaseReader();
}
}
});
}
async function readResponseBodyAsText({ response, url }) {
return textDecoder.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 (parseError) {
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, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders(response);
if (response.body == null) throw new EmptyResponseBodyError({});
return {
responseHeaders,
value: parseJsonEventStream({
stream: wrapResponseBodyStream({
stream: response.body,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders
}),
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 withoutTrailingSlash(url) {
return url == null ? void 0 : url.replace(/\/$/, "");
}
function isAsyncIterable(obj) {
return obj != null && typeof obj[Symbol.asyncIterator] === "function";
}
async function* executeTool({ execute, input, options }) {
const result = 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
};
}
// ../_vendored/ai_v6/dist/dist-ByO0vuJJ.js
function getContext() {
return { headers: {} };
}
async function getVercelOidcToken() {
if (process.env.VERCEL_OIDC_TOKEN) return process.env.VERCEL_OIDC_TOKEN ?? "";
throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
}
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, message = "Authentication failed", statusCode = 401, cause, generationId }) {
let contextualMessage;
if (apiKeyProvided) contextualMessage = `AI Gateway authentication failed: Invalid API key.
Create a new 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.`;
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`;
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 - 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(zod_v4.z.object({ modelId: zod_v4.z.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(zod_v4.z.object({ ruleId: zod_v4.z.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, isRetryable } = {}) {
super({
message,
statusCode,
cause,
generationId,
isRetryable
});
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, isRetryable }) {
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,
isRetryable
});
}
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(zod_v4.z.object({
error: zod_v4.z.object({
message: zod_v4.z.string(),
type: zod_v4.z.string().nullish(),
param: zod_v4.z.unknown().nullish(),
code: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.number()]).nullish()
}),
generationId: zod_v4.z.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 ((error instanceof Error || typeof DOMException === "function" && error instanceof DOMException) && (error.name === "AbortError" || error.name === "TimeoutError")) throw error;
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,
isRetryable: error.isRetryable && (error.statusCode == null || error.statusCode < 400) ? true : void 0
});
}
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";
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(zod_v4.z.union([zod_v4.z.literal("api-key"), zod_v4.z.literal("oidc")])));
var KNOWN_MODEL_TYPES = [
"embedding",
"image",
"language",
"reranking",
"speech",
"transcription",
"video"
];
var GatewayFetchMetadata = class {
constructor(config) {
this.config = config;
}
async getAvailableModels() {
try {
const { value } = await getFromApi({
url: `${this.config.baseURL}/config`,
headers: await resolve(this.config.headers()),
successfulResponseHandler: createJsonResponseHandler(gatewayAvailableModelsResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: zod_v4.z.any(),
errorToMessage: (data) => {
var _a11;
return (_a11 = getErrorMessage(data)) != null ? _a11 : "unknown error";
}
}),
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`,
headers: await resolve(this.config.headers()),
successfulResponseHandler: createJsonResponseHandler(gatewayCreditsResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: zod_v4.z.any(),
errorToMessage: (data) => {
var _a11;
return (_a11 = getErrorMessage(data)) != null ? _a11 : "unknown error";
}
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
var gatewayAvailableModelsResponseSchema = lazySchema(() => zodSchema(zod_v4.z.object({ models: zod_v4.z.array(zod_v4.z.object({
id: zod_v4.z.string(),
name: zod_v4.z.string(),
description: zod_v4.z.string().nullish(),
pricing: zod_v4.z.object({
input: zod_v4.z.string(),
output: zod_v4.z.string(),
input_cache_read: zod_v4.z.string().nullish(),
input_cache_write: zod_v4.z.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: zod_v4.z.object({
specificationVersion: zod_v4.z.literal("v3"),
provider: zod_v4.z.string(),
modelId: zod_v4.z.string()
}),
modelType: zod_v4.z.string().nullish()
})).transform((models) => models.filter((m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType))) })));
var gatewayCreditsResponseSchema = lazySchema(() => zodSchema(zod_v4.z.object({
balance: zod_v4.z.string(),
total_used: zod_v4.z.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()}`,
headers: await resolve(this.config.headers()),
successfulResponseHandler: createJsonResponseHandler(gatewaySpendReportResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: zod_v4.z.any(),
errorToMessage: (data) => {
var _a11;
return (_a11 = getErrorMessage(data)) != null ? _a11 : "unknown error";
}
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
var gatewaySpendReportResponseSchema = lazySchema(() => zodSchema(zod_v4.z.object({ results: zod_v4.z.array(zod_v4.z.object({
day: zod_v4.z.string().optional(),
hour: zod_v4.z.string().optional(),
user: zod_v4.z.string().optional(),
model: zod_v4.z.string().optional(),
tag: zod_v4.z.string().optional(),
provider: zod_v4.z.string().optional(),
credential_type: zod_v4.z.enum(["byok", "system"]).optional(),
total_cost: zod_v4.z.number(),
market_cost: zod_v4.z.number().optional(),
input_tokens: zod_v4.z.number().optional(),
output_tokens: zod_v4.z.number().optional(),
cached_input_tokens: zod_v4.z.number().optional(),
cache_creation_input_tokens: zod_v4.z.number().optional(),
reasoning_tokens: zod_v4.z.number().optional(),
request_count: zod_v4.z.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)}`,
headers: await resolve(this.config.headers()),
successfulResponseHandler: createJsonResponseHandler(gatewayGenerationInfoResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: zod_v4.z.any(),
errorToMessage: (data) => {
var _a11;
return (_a11 = getErrorMessage(data)) != null ? _a11 : "unknown error";
}
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
var gatewayGenerationInfoResponseSchema = lazySchema(() => zodSchema(zod_v4.z.object({ data: zod_v4.z.object({
id: zod_v4.z.string(),
total_cost: zod_v4.z.number(),
upstream_inference_cost: zod_v4.z.number(),
usage: zod_v4.z.number(),
created_at: zod_v4.z.string(),
model: zod_v4.z.string(),
is_byok: zod_v4.z.boolean(),
provider_name: zod_v4.z.string(),
streamed: zod_v4.z.boolean(),
finish_reason: zod_v4.z.string(),
latency: zod_v4.z.number(),
generation_time: zod_v4.z.number(),
native_tokens_prompt: zod_v4.z.number(),
native_tokens_completion: zod_v4.z.number(),
native_tokens_reasoning: zod_v4.z.number(),
native_tokens_cached: zod_v4.z.number(),
native_tokens_cache_creation: zod_v4.z.number(),
billable_web_search_calls: zod_v4.z.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 {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
this.supportedUrls = { "*/*": [/.*/] };
}
get provider() {
return this.config.provider;
}
async getArgs(options) {
const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;
return {
args: this.maybeEncodeFileParts(optionsWithoutSignal),
warnings: []
};
}
async doGenerate(options) {
var _a11;
const { args, warnings } = await this.getArgs(options);
const { abortSignal } = options;
const resolvedHeaders = await resolve(this.config.headers());
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(zod_v4.z.any()),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: zod_v4.z.any(),
errorToMessage: (data) => {
var _a12;
return (_a12 = getErrorMessage(data)) != null ? _a12 : "unknown error";
}
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
...responseBody,
request: { body: args },
response: {
headers: responseHeaders,
body: rawResponse
},
warnings: [...(_a11 = responseBody.warnings) != null ? _a11 : [], ...warnings]
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
}
}
async doStream(options) {
const { args, warnings } = await this.getArgs(options);
const { abortSignal } = options;
const resolvedHeaders = await resolve(this.config.headers());
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(zod_v4.z.any()),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: zod_v4.z.any(),
errorToMessage: (data) => {
var _a11;
return (_a11 = getErrorMessage(data)) != null ? _a11 : "unknown error";
}
}),
...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));
}
}
isFilePart(part) {
return part && typeof part === "object" && "type" in part && part.type === "file";
}
/**
* Encodes file parts in the prompt to base64. Mutates the passed options
* instance directly to avoid copying the file data.
* @param options - The options to encode.
* @returns The options with the file parts encoded.
*/
maybeEncodeFileParts(options) {
for (const message of options.prompt) for (const part of message.content) if (this.isFilePart(part)) {
const filePart = part;
if (filePart.data instanceof Uint8Array) {
const buffer = Uint8Array.from(filePart.data);
const base64Data = Buffer.from(buffer).toString("base64");
filePart.data = new URL(`data:${filePart.mediaType || "application/octet-stream"};base64,${base64Data}`);
}
}
return options;
}
getUrl() {
return `${this.config.baseURL}/language-model`;
}
getModelConfigHeaders(modelId, streaming) {
return {
"ai-language-model-specification-version": "3",
"ai-language-model-id": modelId,
"ai-language-model-streaming": String(streaming)
};
}
};
var GatewayEmbeddingModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
this.maxEmbeddingsPerCall = 2048;
this.supportsParallelCalls = true;
}
get provider() {
return this.config.provider;
}
async doEmbed({ values, headers, abortSignal, providerOptions }) {
var _a11, _b11;
const resolvedHeaders = await resolve(this.config.headers());
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: zod_v4.z.any(),
errorToMessage: (data) => {
var _a12;
return (_a12 = getErrorMessage(data)) != null ? _a12 : "unknown error";
}
}),
...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));
}
}
getUrl() {
return `${this.config.baseURL}/embedding-model`;
}
getModelConfigHeaders() {
return {
"ai-embedding-model-specification-version": "3",
"ai-model-id": this.modelId
};
}
};
var gatewayEmbeddingWarningSchema = () => zod_v4.z.discriminatedUnion("type", [
zod_v4.z.object({
type: zod_v4.z.literal("unsupported"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("compatibility"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("other"),
message: zod_v4.z.string()
})
]);
var gatewayEmbeddingResponseSchema = lazySchema(() => zodSchema(zod_v4.z.object({
embeddings: zod_v4.z.array(zod_v4.z.array(zod_v4.z.number())),
usage: zod_v4.z.object({ tokens: zod_v4.z.number() }).nullish(),
warnings: zod_v4.z.array(gatewayEmbeddingWarningSchema()).optional(),
providerMetadata: zod_v4.z.record(zod_v4.z.string(), zod_v4.z.record(zod_v4.z.string(), zod_v4.z.unknown())).optional()
})));
function mapGatewayWarnings(warnings) {
return (warnings != null ? warnings : []).map((warning) => warning.type === "deprecated" ? {
type: "other",
message: warning.message
} : warning);
}
var GatewayImageModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
this.maxImagesPerCall = Number.MAX_SAFE_INTEGER;
}
get provider() {
return this.config.provider;
}
async doGenerate({ prompt, n, size, aspectRatio, seed, files, mask, providerOptions, headers, abortSignal }) {
var _a11, _b11, _c;
const resolvedHeaders = await resolve(this.config.headers());
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: {
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: zod_v4.z.any(),
errorToMessage: (data) => {
var _a12;
return (_a12 = getErrorMessage(data)) != null ? _a12 : "unknown error";
}
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
images: responseBody.images,
...responseBody.isRetryable != null && { isRetryable: responseBody.isRetryable },
warnings: mapGatewayWarnings(responseBody.warnings),
providerMetadata: responseBody.providerMetadata,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
},
...responseBody.usage != null && { usage: {
inputTokens: (_a11 = responseBody.usage.inputTokens) != null ? _a11 : void 0,
outputTokens: (_b11 = responseBody.usage.outputTokens) != null ? _b11 : void 0,
totalTokens: (_c = responseBody.usage.totalTokens) != null ? _c : void 0
} }
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
}
}
getUrl() {
return `${this.config.baseURL}/image-model`;
}
getModelConfigHeaders() {
return {
"ai-image-model-specification-version": "3",
"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 = () => zod_v4.z.object({ images: zod_v4.z.array(zod_v4.z.unknown()).optional() }).catchall(zod_v4.z.unknown());
var gatewayImageWarningSchema = () => zod_v4.z.discriminatedUnion("type", [
zod_v4.z.object({
type: zod_v4.z.literal("unsupported"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("compatibility"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("deprecated"),
setting: zod_v4.z.string(),
message: zod_v4.z.string()
}),
zod_v4.z.object({
type: zod_v4.z.literal("other"),
message: zod_v4.z.string()
})
]);
var gatewayImageUsageSchema = () => zod_v4.z.object({
inputTokens: zod_v4.z.number().nullish(),
outputTokens: zod_v4.z.number().nullish(),
totalTokens: zod_v4.z.number().nullish()
});
var gatewayImageResponseSchema = lazySchema(() => zodSchema(zod_v4.z.object({
images: zod_v4.z.array(zod_v4.z.string()),
isRetryable: zod_v4.z.boolean().optional(),
warnings: zod_v4.z.array(gatewayImageWarningSchema()).optional(),
providerMetadata: zod_v4.z.record(zod_v4.z.string(), providerMetadataEntrySchema()).optional(),
usage: gatewayImageUsageSchema().optional()
})));
var GatewayVideoModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
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 }) {
const resolvedHeaders = await resolve(this.config.headers());
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: zod_v4.z.any(),
errorToMessage: (data) => {
var _a11;
return (_a11 = getErrorMessage(data)) != null ? _a11 : "unknown error";
}
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
videos: responseBody.videos,
warnings: mapGatewayWarnings(responseBody.warnings),
providerMetadata: responseBody.providerMetadata,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
}
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
}
}
getUrl() {
return `${this.config.baseURL}/video-model`;
}
getModelConfigHeaders() {
return {
"ai-video-model-specification-version": "3",
"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 = () => zod_v4.z.object({ videos: zod_v4.z.array(zod_v4.z.unknown()).optional() }).catchall(zod_v4.z.unknown());
var gatewayVideoDataSchema = () => zod_v4.z.union([zod_v4.z.object({
type: zod_v4.z.literal("url"),
url: zod_v4.z.string(),
mediaType: zod_v4.z.string()
}), zod_v4.z.object({
type: zod_v4.z.literal("base64"),
data: zod_v4.z.string(),
mediaType: zod_v4.z.string()
})]);
var gatewayVideoWarningSchema = () => zod_v4.z.discriminatedUnion("type", [
zod_v4.z.object({
type: zod_v4.z.literal("unsupported"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("compatibility"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("deprecated"),
setting: zod_v4.z.string(),
message: zod_v4.z.string()
}),
zod_v4.z.object({
type: zod_v4.z.literal("other"),
message: zod_v4.z.string()
})
]);
var gatewayVideoEventSchema = lazySchema(() => zodSchema(zod_v4.z.discriminatedUnion("type", [zod_v4.z.object({
type: zod_v4.z.literal("result"),
videos: zod_v4.z.array(gatewayVideoDataSchema()),
warnings: zod_v4.z.array(gatewayVideoWarningSchema()).optional(),
providerMetadata: zod_v4.z.record(zod_v4.z.string(), providerMetadataEntrySchema2()).optional()
}), zod_v4.z.object({
type: zod_v4.z.literal("error"),
message: zod_v4.z.string(),
errorType: zod_v4.z.string(),
statusCode: zod_v4.z.number(),
param: zod_v4.z.unknown().nullable()
})])));
var GatewayRerankingModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
}
get provider() {
return this.config.provider;
}
async doRerank({ documents, query, topN, headers, abortSignal, providerOptions }) {
var _a11;
const resolvedHeaders = await resolve(this.config.headers());
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: zod_v4.z.any(),
errorToMessage: (data) => {
var _a12;
return (_a12 = getErrorMessage(data)) != null ? _a12 : "unknown error";
}
}),
...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));
}
}
getUrl() {
return `${this.config.baseURL}/reranking-model`;
}
getModelConfigHeaders() {
return {
"ai-reranking-model-specification-version": "3",
"ai-model-id": this.modelId
};
}
};
var gatewayRerankingWarningSchema = () => zod_v4.z.discriminatedUnion("type", [
zod_v4.z.object({
type: zod_v4.z.literal("unsupported"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("compatibility"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("other"),
message: zod_v4.z.string()
})
]);
var gatewayRerankingResponseSchema = lazySchema(() => zodSchema(zod_v4.z.object({
ranking: zod_v4.z.array(zod_v4.z.object({
index: zod_v4.z.number(),
relevanceScore: zod_v4.z.number()
})),
warnings: zod_v4.z.array(gatewayRerankingWarningSchema()).optional(),
providerMetadata: zod_v4.z.record(zod_v4.z.string(), zod_v4.z.record(zod_v4.z.string(), zod_v4.z.unknown())).optional()
})));
var GatewaySpeechModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
}
get provider() {
return this.config.provider;
}
async doGenerate({ text, voice, outputFormat, instructions, speed, language, providerOptions, headers, abortSignal }) {
const resolvedHeaders = await resolve(this.config.headers());
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: zod_v4.z.any(),
errorToMessage: (data) => {
var _a11;
return (_a11 = getErrorMessage(data)) != null ? _a11 : "unknown error";
}
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
audio: responseBody.audio,
warnings: mapGatewayWarnings(responseBody.warnings),
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": "3",
"ai-model-id": this.modelId
};
}
};
var providerMetadataEntrySchema3 = () => zod_v4.z.object({}).catchall(zod_v4.z.unknown());
var gatewaySpeechWarningSchema = () => zod_v4.z.discriminatedUnion("type", [
zod_v4.z.object({
type: zod_v4.z.literal("unsupported"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("compatibility"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("deprecated"),
setting: zod_v4.z.string(),
message: zod_v4.z.string()
}),
zod_v4.z.object({
type: zod_v4.z.literal("other"),
message: zod_v4.z.string()
})
]);
var gatewaySpeechResponseSchema = lazySchema(() => zodSchema(zod_v4.z.object({
audio: zod_v4.z.string(),
warnings: zod_v4.z.array(gatewaySpeechWarningSchema()).optional(),
providerMetadata: zod_v4.z.record(zod_v4.z.string(), providerMetadataEntrySchema3()).optional()
})));
var GatewayTranscriptionModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v3";
}
get provider() {
return this.config.provider;
}
async doGenerate({ audio, mediaType, providerOptions, headers, abortSignal }) {
var _a11, _b11, _c;
const resolvedHeaders = await resolve(this.config.headers());
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: zod_v4.z.any(),
errorToMessage: (data) => {
var _a12;
return (_a12 = getErrorMessage(data)) != null ? _a12 : "unknown error";
}
}),
...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: mapGatewayWarnings(responseBody.warnings),
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}/transcription-model`;
}
getModelConfigHeaders() {
return {
"ai-transcription-model-specification-version": "3",
"ai-model-id": this.modelId
};
}
};
var providerMetadataEntrySchema4 = () => zod_v4.z.object({}).catchall(zod_v4.z.unknown());
var gatewayTranscriptionWarningSchema = () => zod_v4.z.discriminatedUnion("type", [
zod_v4.z.object({
type: zod_v4.z.literal("unsupported"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("compatibility"),
feature: zod_v4.z.string(),
details: zod_v4.z.string().optional()
}),
zod_v4.z.object({
type: zod_v4.z.literal("deprecated"),
setting: zod_v4.z.string(),
message: zod_v4.z.string()
}),
zod_v4.z.object({
type: zod_v4.z.literal("other"),
message: zod_v4.z.string()
})
]);
var gatewayTranscriptionResponseSchema = lazySchema(() => zodSchema(zod_v4.z.object({
text: zod_v4.z.string(),
segments: zod_v4.z.array(zod_v4.z.object({
text: zod_v4.z.string(),
startSecond: zod_v4.z.number(),
endSecond: zod_v4.z.number()
})).optional(),
language: zod_v4.z.string().nullish(),
durationInSeconds: zod_v4.z.number().nullish(),
warnings: zod_v4.z.array(gatewayTranscriptionWarningSchema()).optional(),
providerMetadata: zod_v4.z.record(zod_v4.z.string(), providerMetadataEntrySchema4()).optional()
})));
var jsonObjectSchema = () => zod.z.record(zod.z.string(), zod.z.unknown());
var browserbaseFetchToolFactory = createProviderToolFactoryWithOutputSchema({
id: "gateway.browserbase_fetch",
inputSchema: lazySchema(() => zodSchema(zod.z.object({
url: zod.z.string().url().describe("URL of the page to fetch."),
allow_redirects: zod.z.boolean().optional().describe("Whether to follow HTTP redirects (default: false)."),
allow_insecure_ssl: zod.z.boolean().optional().describe("Whether to bypass TLS certificate verification (default: false). Only use for trusted hosts."),
proxies: zod.z.boolean().optional().describe("Whether to route the request through Browserbase proxies (default: false)."),
format: zod.z.enum([
"raw",
"json",
"markdown"
]).optional().describe("Output format. raw returns the response body unchanged, markdown returns page content as Markdown, and json returns structured content using schema."),
schema: jsonObjectSchema().optional().describe("JSON Schema for structured extraction. Only use with format set to json.")
}))),
outputSchema: lazySchema(() => zodSchema(zod.z.union([zod.z.object({
id: zod.z.string(),
content: zod.z.union([zod.z.string(), jsonObjectSchema()]),
contentType: zod.z.string(),
encoding: zod.z.string(),
headers: zod.z.record(zod.z.string(), zod.z.string()),
statusCode: zod.z.number()
}), zod.z.object({
error: zod.z.enum([
"api_error",
"configuration_error",
"execution_error",
"invalid_input",
"rate_limit",
"timeout",
"unknown"
]),
statusCode: zod.z.number().optional(),
message: zod.z.string()
})])))
});
var browserbaseFetch = (config = {}) => browserbaseFetchToolFactory(config);
var browserbaseSearchToolFactory = createProviderToolFactoryWithOutputSchema({
id: "gateway.browserbase_search",
inputSchema: lazySchema(() => zodSchema(zod.z.object({
query: zod.z.string().min(1).max(200).describe("Web search query. Must be between 1 and 200 characters."),
num_results: zod.z.number().int().min(1).max(25).optional().describe("Maximum number of results to return (1-25, default: 10).")
}))),
outputSchema: lazySchema(() => zodSchema(zod.z.union([zod.z.object({
query: zod.z.string(),
requestId: zod.z.string(),
results: zod.z.array(zod.z.object({
id: zod.z.string(),
title: zod.z.string(),
url: zod.z.string(),
author: zod.z.string().optional(),
favicon: zod.z.string().optional(),
image: zod.z.string().optional(),
publishedDate: zod.z.string().optional()
}))
}), zod.z.object({
error: zod.z.enum([
"api_error",
"configuration_error",
"execution_error",
"invalid_input",
"rate_limit",
"timeout",
"unknown"
]),
statusCode: zod.z.number().optional(),
message: zod.z.string()
})])))
});
var browserbaseSearch = (config = {}) => browserbaseSearchToolFactory(config);
var gatewayToolErrorSchema = () => zod.z.object({
error: zod.z.enum([
"api_error",
"configuration_error",
"execution_error",
"gateway_rate_limit",
"invalid_input",
"rate_limit",
"timeout",
"unknown",
"unknown_tool"
]),
message: zod.z.string(),
statusCode: zod.z.number().optional(),
retryAfter: zod.z.string().optional(),
statusText: zod.z.string().optional()
}).passthrough();
var deepseekFetchToolFactory = createProviderToolFactoryWithOutputSchema({
id: "gateway.deepseek_fetch",
inputSchema: lazySchema(() => zodSchema(zod.z.object({ url: zod.z.string().describe("URL to fetch, at most 8192 characters; HTTP(S) only, without a username or password.") }))),
outputSchema: lazySchema(() => zodSchema(zod.z.union([zod.z.object({
title: zod.z.string().nullish(),
content: zod.z.string()
}).passthrough(), gatewayToolErrorSchema()])))
});
var deepseekFetch = (config = {}) => deepseekFetchToolFactory(config);
var deepseekSearchToolFactory = createProviderToolFactoryWithOutputSchema({
id: "gateway.deepseek_search",
inputSchema: lazySchema(() => zodSchema(zod.z.object({
query: zod.z.string().describe("Web search query, 1 to 128 Unicode characters. Supports site:, -site:, lang:, after:, before:, and quoted phrases."),
count: zod.z.number().int().optional().describe("Number of results, 1 to 50 (default: 10)."),
need_content: zod.z.boolean().optional().describe("Include available page content (default: false)."),
ori_question: zod.z.string().nullable().optional().describe("Original user question, 1 to 128 Unicode characters.")
}))),
outputSchema: lazySchema(() => zodSchema(zod.z.union([zod.z.object({ results: zod.z.array(zod.z.object({
authority: zod.z.number().nullish(),
content: zod.z.string().nullish(),
date: zod.z.string().nullish(),
rerank_score: zod.z.number().nullish(),
site_icon: zod.z.string().nullish(),
site_name: zod.z.string().nullish(),
snippet: zod.z.string().nullish(),
summary: zod.z.string().nullish(),
title: zod.z.string().nullish(),
url: zod.z.string().nullish()
}).passthrough()) }).passthrough(), gatewayToolErrorSchema()])))
});
var deepseekSearch = (config = {}) => deepseekSearchToolFactory(config);
var exaSearchToolFactory = createProviderToolFactoryWithOutputSchema({
id: "gateway.exa_search",
inputSchema: lazySchema(() => zodSchema(zod.z.object({
query: zod.z.string().describe("Natural-language web search query. This is required."),
type: zod.z.enum([
"auto",
"fast",
"instant"
]).optional().describe("Search method. Use auto for the default balance of speed and quality."),
num_results: zod.z.number().optional().describe("Maximum number of results to return (1-100, default: 10)."),
category: zod.z.enum([
"company",
"people",
"research paper",
"news",
"personal site",
"financial report"
]).optional().describe("Optional content category to focus results."),
user_location: zod.z.string().optional().describe("Two-letter ISO country code such as 'US'."),
include_domains: zod.z.array(zod.z.string()).optional().describe("Only return results from these domains."),
exclude_domains: zod.z.array(zod.z.string()).optional().describe("Exclude results from these domains."),
start_published_date: zod.z.string().optional().describe("Only return links published after this ISO 8601 date."),
end_published_date: zod.z.string().optional().describe("Only return links published before this ISO 8601 date."),
contents: zod.z.object({
text: zod.z.union([zod.z.boolean(), zod.z.object({
max_characters: zod.z.number().optional(),
include_html_tags: zod.z.boolean().optional(),
verbosity: zod.z.enum([
"compact",
"standard",
"full"
]).optional(),
include_sections: zod.z.array(zod.z.enum([
"header",
"navigation",
"banner",
"body",
"sidebar",
"footer",
"metadata"
])).optional(),
exclude_sections: zod.z.array(zod.z.enum([
"header",
"navigation",
"banner",
"body",
"sidebar",
"footer",
"metadata"
])).optional()
})]).optional(),
highlights: zod.z.union([zod.z.boolean(), zod.z.object({
query: zod.z.string().optional(),
max_characters: zod.z.number().optional()
})]).optional(),
max_age_hours: zod.z.number().optional(),
livecrawl_timeout: zod.z.number().optional(),
subpages: zod.z.number().optional(),
subpage_target: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]).optional(),
extras: zod.z.object({
links: zod.z.number().optional(),
image_links: zod.z.number().optional()
}).optional()
}).optional().describe("Controls extracted page content and freshness.")
}))),
outputSchema: lazySchema(() => zodSchema(zod.z.union([zod.z.object({
requestId: zod.z.string(),
searchType: zod.z.string().optional(),
resolvedSearchType: zod.z.string().optional(),
results: zod.z.array(zod.z.object({
title: zod.z.string(),
url: zod.z.string(),
id: zod.z.string(),
publishedDate: zod.z.string().nullable().optional(),
author: zod.z.string().nullable().optional(),
image: zod.z.string().nullable().optional(),
favicon: zod.z.string().nullable().optional(),
text: zod.z.string().optional(),
highlights: zod.z.array(zod.z.string()).optional(),
highlightScores: zod.z.array(zod.z.number()).optional(),
summary: zod.z.string().optional(),
subpages: zod.z.array(zod.z.any()).optional(),
extras: zod.z.object({
links: zod.z.array(zod.z.string()).optional(),
imageLinks: zod.z.array(zod.z.string()).optional()
}).optional()
})),
costDollars: zod.z.object({
total: zod.z.number().optional(),
search: zod.z.record(zod.z.number()).optional()
}).optional()
}), zod.z.object({
error: zod.z.enum([
"api_error",
"rate_limit",
"timeout",
"invalid_input",
"configuration_error",
"execution_error",
"unknown"
]),
statusCode: zod.z.number().optional(),
message: zod.z.string()
})])))
});
var exaSearch = (config = {}) => exaSearchToolFactory(config);
var parallelSearchModes = [
"turbo",
"fast",
"basic",
"advanced",
"one-shot",
"agentic"
];
var parallelSearchToolFactory = createProviderToolFactoryWithOutputSchema({
id: "gateway.parallel_search",
inputSchema: lazySchema(() => zodSchema(zod.z.object({
objective: zod.z.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: zod.z.array(zod.z.string()).optional().describe("Provide 2-3 concise keyword queries, 3-6 words each (max 5, 200 chars each). Strongly recommended; the search runs on these queries."),
mode: zod.z.enum(parallelSearchModes).optional().describe("Search mode: \"turbo\" and \"fast\" return quickly with shorter excerpts, \"basic\" is balanced (default), \"advanced\" is the most thorough. \"turbo\" supports English and Japanese only. \"one-shot\" and \"agentic\" are deprecated aliases of \"basic\" and \"advanced\"."),
max_results: zod.z.number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),
source_policy: zod.z.object({
include_domains: zod.z.array(zod.z.string()).optional().describe("Domains or domain/path prefixes to restrict results to, without scheme or port. Example: ['wikipedia.org', 'docs.python.org/3']."),
exclude_domains: zod.z.array(zod.z.string()).optional().describe("Domains or domain/path prefixes to exclude, without scheme or port. Example: ['reddit.com']."),
after_date: zod.z.string().optional().describe("Only include results published on or 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: zod.z.object({
max_chars_per_result: zod.z.number().optional().describe("Maximum characters per result."),
max_chars_total: zod.z.number().optional().describe("Deprecated: use the top-level max_chars_total.")
}).optional().describe("Excerpt configuration for controlling result length."),
max_chars_total: zod.z.number().optional().describe("Maximum total characters across all result excerpts."),
fetch_policy: zod.z.object({
max_age_seconds: zod.z.number().optional().describe("Maximum age of cached content in seconds before a live fetch, minimum 600."),
timeout_seconds: zod.z.number().optional().describe("Timeout in seconds for a live fetch when content is not cached. Capped by the gateway tool timeout."),
disable_cache_fallback: zod.z.boolean().optional().describe("Return an error instead of older cached content when a live fetch fails.")
}).optional().describe("Fetch policy for controlling content freshness."),
location: zod.z.string().optional().describe("ISO 3166-1 alpha-2 country code to localize results, e.g. \"us\".")
}))),
outputSchema: lazySchema(() => zodSchema(zod.z.union([zod.z.object({
search_id: zod.z.string(),
results: zod.z.array(zod.z.object({
url: zod.z.string(),
title: zod.z.string().nullable().optional(),
publish_date: zod.z.string().nullable().optional(),
excerpts: zod.z.array(zod.z.string())
})),
warnings: zod.z.array(zod.z.object({
type: zod.z.string(),
message: zod.z.string(),
detail: zod.z.record(zod.z.string(), zod.z.unknown()).nullable().optional()
})).nullable().optional(),
usage: zod.z.array(zod.z.object({
name: zod.z.string(),
count: zod.z.number().optional()
})).nullable().optional(),
session_id: zod.z.string().optional()
}), gatewayToolErrorSchema()])))
});
var parallelSearch = (config = {}) => parallelSearchToolFactory(config);
var perplexitySearchToolFactory = createProviderToolFactoryWithOutputSchema({
id: "gateway.perplexity_search",
inputSchema: lazySchema(() => zodSchema(zod.z.object({
query: zod.z.union([zod.z.string(), zod.z.array(zod.z.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: zod.z.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),
max_tokens_per_page: zod.z.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),
max_tokens: zod.z.number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),
country: zod.z.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),
search_domain_filter: zod.z.array(zod.z.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: zod.z.array(zod.z.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),
search_after_date: zod.z.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: zod.z.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: zod.z.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: zod.z.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: zod.z.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(zod.z.union([zod.z.object({
results: zod.z.array(zod.z.object({
title: zod.z.string(),
url: zod.z.string(),
snippet: zod.z.string(),
date: zod.z.string().optional(),
lastUpdated: zod.z.string().optional()
})),
id: zod.z.string()
}), zod.z.object({
error: zod.z.enum([
"api_error",
"rate_limit",
"timeout",
"invalid_input",
"unknown"
]),
statusCode: zod.z.number().optional(),
message: zod.z.string()
})])))
});
var perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
var takoDataSourceInputSchema = () => zod.z.object({
count: zod.z.number().optional().describe("Maximum number of data results to return (1-20). When include_contents is true, each additional result adds its own data surcharge."),
include_contents: zod.z.boolean().optional().describe("Inline rows for each data result. This adds a data surcharge based on row count and dataset source. To estimate cost, search with include_contents disabled and inspect cards.content.export_pricing. This applies to every returned card; limit sources.data.count and sources.data.max_rows to control cost."),
mode: zod.z.enum(["inline", "url"]).optional().describe("Requested data delivery mode. Search card data is always inline."),
content_format: zod.z.enum([
"card_json",
"csv",
"json_compact",
"json_records"
]).optional().describe("Serialization for inlined card data."),
max_rows: zod.z.number().optional().describe("Maximum rows to inline per result. Omit to use the allowance in cards.content.export_pricing. A data surcharge applies per 1,000 exported rows; lower values reduce cost."),
node_ids: zod.z.array(zod.z.string()).optional().describe("Data Graph node IDs to prioritize. Maximum 20."),
strict: zod.z.boolean().optional().describe("Only return cards matching node_ids. Requires a non-empty node_ids.")
});
var takoWebSourceInputSchema = () => zod.z.object({
count: zod.z.number().optional().describe("Maximum number of web results to return (1-20)."),
include_contents: zod.z.boolean().optional().describe("Inline extracted web page text. This can add a data charge."),
category: zod.z.enum([
"finance",
"news",
"sports"
]).optional().describe("Optional web-result category filter."),
include_domains: zod.z.array(zod.z.string()).optional().describe("Only return results from these bare domains."),
exclude_domains: zod.z.array(zod.z.string()).optional().describe("Exclude results from these bare domains."),
snippet_max_chars: zod.z.number().optional().describe("Maximum characters in each web-result snippet."),
highlights: zod.z.boolean().optional().describe("Include highlighted passages in web results. Defaults to true in AI Gateway."),
article_content_max_chars: zod.z.number().optional().describe("Maximum extracted characters per web page when including contents."),
published_after: zod.z.string().optional().describe("Keep results published on or after this ISO date (YYYY-MM-DD)."),
published_before: zod.z.string().optional().describe("Keep results published on or before this ISO date (YYYY-MM-DD).")
});
var takoSearchInputSchema = lazySchema(() => zodSchema(zod.z.object({
query: zod.z.string().describe("Natural-language search query. Include the entity, metric, and time period. Quote a phrase to force it to one entity, for example \"Tesla\":PRODUCT price."),
effort: zod.z.enum([
"deep",
"fast",
"instant"
]).optional().describe("Search effort. fast is the balanced default, instant favors cached results and low latency, and deep broadens retrieval with reranking at higher cost and latency."),
sources: zod.z.object({
data: takoDataSourceInputSchema().optional(),
web: takoWebSourceInputSchema().optional()
}).optional().describe("Sources to search. Omit to search both curated data and the web. When provided, only keys present are searched."),
location: zod.z.object({
latitude: zod.z.number().describe("Latitude between -90 and 90."),
longitude: zod.z.number().describe("Longitude between -180 and 180.")
}).optional().describe("End-user coordinates for localized results."),
country_code: zod.z.string().optional().describe("Two-letter ISO 3166-1 country code, such as 'US'."),
locale: zod.z.string().optional().describe("BCP-47 locale, such as 'en-US'."),
timezone: zod.z.string().optional().describe("IANA timezone, such as 'America/New_York'."),
output_settings: zod.z.object({
image_dark_mode: zod.z.boolean().optional().describe("Render card preview images in dark mode."),
force_refresh: zod.z.boolean().optional().describe("Instant-effort only. Request a refreshed instant result.")
}).optional().describe("Controls card rendering in the search response."),
include_related: zod.z.number().optional().describe("Maximum related search suggestions to include (1-20).")
})));
var takoDatasetCellSchema = () => zod.z.union([
zod.z.boolean(),
zod.z.number(),
zod.z.string()
]).nullable();
var takoResultContentSchema = () => zod.z.object({
content_format: zod.z.enum([
"card_json",
"csv",
"json_compact",
"json_records"
]).nullish(),
cost: zod.z.number().optional(),
data: zod.z.string().nullish(),
records: zod.z.array(zod.z.record(zod.z.string(), takoDatasetCellSchema())).nullish(),
dataset: zod.z.object({
columns: zod.z.array(zod.z.object({
name: zod.z.string(),
type: zod.z.enum([
"boolean",
"date",
"datetime",
"number",
"string"
]),
unit: zod.z.string().nullish()
})),
rows: zod.z.array(zod.z.array(takoDatasetCellSchema())),
total_rows: zod.z.number(),
truncated: zod.z.boolean(),
ref: zod.z.string(),
sources: zod.z.array(zod.z.object({
name: zod.z.string(),
index: zod.z.enum(["data", "web"]).optional()
})),
provenance: zod.z.enum(["query", "web_extraction"]).optional()
}).nullish(),
card_data: zod.z.object({}).passthrough().nullish(),
card_data_schema: zod.z.object({}).passthrough().nullish(),
url: zod.z.string().nullish(),
expires_at: zod.z.string().nullish(),
total_rows: zod.z.number().nullish(),
truncated: zod.z.boolean().optional(),
export_pricing: zod.z.object({
baseline_usd: zod.z.number(),
free_rows: zod.z.number(),
max_rows_ceiling: zod.z.number(),
row_cpm_usd: zod.z.number()
}).nullish(),
manifest: zod.z.array(zod.z.object({
dtype: zod.z.enum([
"boolean",
"date",
"datetime",
"number",
"string"
]).nullish(),
entity: zod.z.string().nullish(),
metric: zod.z.string().nullish(),
name: zod.z.string().nullish(),
unit: zod.z.string().nullish()
})).nullish()
}).passthrough();
var takoCardSchema = () => zod.z.object({
card_id: zod.z.string().nullish(),
title: zod.z.string().nullish(),
description: zod.z.string().nullish(),
semantic_description: zod.z.string().nullish(),
webpage_url: zod.z.string().nullish(),
image_url: zod.z.string().nullish(),
embed_url: zod.z.string().nullish(),
sources: zod.z.array(zod.z.object({
source_name: zod.z.string().nullish(),
source_description: zod.z.string().nullish(),
source_index: zod.z.enum(["data", "web"]),
source_text: zod.z.string().nullish(),
url: zod.z.string().nullish()
})).nullish(),
methodologies: zod.z.array(zod.z.object({
methodology_name: zod.z.string().nullable(),
methodology_description: zod.z.string().nullable()
})).nullish(),
source_indexes: zod.z.array(zod.z.enum(["data", "web"])).nullish(),
card_type: zod.z.string().nullish(),
relevance: zod.z.enum([
"High",
"Low",
"Medium"
]).nullish(),
content: takoResultContentSchema().nullish(),
exportable: zod.z.boolean().optional(),
nodes: zod.z.array(zod.z.object({
id: zod.z.string(),
type: zod.z.enum(["entity", "metric"]),
name: zod.z.string(),
description: zod.z.string().nullish()
})).nullish(),
metric_definitions: zod.z.array(zod.z.object({
name: zod.z.string(),
definition: zod.z.string()
})).nullish(),
data_freshness: zod.z.object({
coverage_end: zod.z.string().nullish(),
data_as_of: zod.z.string().nullish(),
last_updated: zod.z.string().nullish()
}).nullish()
}).passthrough();
var takoWebResultSchema = () => zod.z.object({
title: zod.z.string(),
url: zod.z.string(),
snippet: zod.z.string().nullish(),
source_name: zod.z.string().nullish(),
publish_date: zod.z.string().nullish(),
content: takoResultContentSchema().nullish()
}).passthrough();
var takoSearchToolFactory = createProviderToolFactoryWithOutputSchema({
id: "gateway.tako_search",
inputSchema: takoSearchInputSchema,
outputSchema: lazySchema(() => zodSchema(zod.z.union([zod.z.object({
request_id: zod.z.string(),
cards: zod.z.array(takoCardSchema()).optional(),
web_results: zod.z.array(takoWebResultSchema()).optional(),
usage: zod.z.object({
total_cost_usd: zod.z.number(),
compute: zod.z.object({ cost_usd: zod.z.number() }).nullish(),
data: zod.z.object({
cost_usd: zod.z.number(),
datasets: zod.z.number()
}).nullish()
}).nullish(),
related: zod.z.array(zod.z.object({}).passthrough()).nullish()
}).passthrough(), gatewayToolErrorSchema()])))
});
var takoSearch = (config = {}) => takoSearchToolFactory(config);
var gatewayTools = {
/**
* Fetch page content using Browserbase's lightweight Fetch API.
*
* Supports raw, Markdown, and schema-driven JSON output as well as redirects,
* proxy routing, and TLS controls.
*/
browserbaseFetch,
/**
* Search the web using Browserbase's Search API for fast, structured results.
*
* Returns titles, URLs, and available publication metadata without requiring
* a browser session.
*/
browserbaseSearch,
/**
* Fetch a page as Markdown through DeepSeek's standalone Fetch API.
* Executed by AI Gateway for any model, separate from native model web search.
*/
deepseekFetch,
/**
* Search the web through DeepSeek's standalone Search API.
* Executed by AI Gateway for any model, separate from native model web search.
*/
deepseekSearch,
/**
* 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,
/**
* Search the web and Tako's curated knowledge graph in one call for
* token-efficient web excerpts and structured data results grounded in
* premium sources, each with an embed-ready visualization.
*
* Supports effort, per-source web and data controls, localization, and inline
* contents for agents that need to reason over underlying data.
*/
takoSearch
};
async function getVercelRequestId() {
var _a11;
return (_a11 = getContext().headers) == null ? void 0 : _a11["x-vercel-id"];
}
var VERSION = "3.0.228";
var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
function createGatewayProvider(options = {}) {
var _a11, _b11;
let pendingMetadata = null;
let metadataCache = null;
const cacheRefreshMillis = (_a11 = options.metadataCacheRefreshMillis) != null ? _a11 : 3e5;
let lastFetchTime = 0;
const baseURL = (_b11 = withoutTrailingSlash(options.baseURL)) != null ? _b11 : "https://ai-gateway.vercel.sh/v3/ai";
const getHeaders = async () => {
try {
const auth = await getGatewayAuthToken(options);
return withUserAgentSuffix({
Authorization: `Bearer ${auth.token}`,
"ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
[GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
...options.headers
}, `ai-sdk/gateway/${VERSION}`);
} catch (error) {
throw GatewayAuthenticationError.createContextualError({
apiKeyProvided: false,
oidcTokenProvided: false,
statusCode: 401,
cause: error
});
}
};
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 = "v3";
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()
});
};
provider.transcriptionModel = createTranscriptionModel;
provider.transcription = createTranscriptionModel;
provider.chat = provider.languageModel;
provider.embedding = provider.embeddingModel;
provider.image = provider.imageModel;
provider.video = provider.videoModel;
provider.tools = gatewayTools;
return provider;
}
var gateway = createGatewayProvider();
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 getVercelOidcToken(),
authMethod: "oidc"
};
}
Object.defineProperty(exports, "AISDKError", {
enumerable: true,
get: function() {
return AISDKError;
}
});
Object.defineProperty(exports, "APICallError", {
enumerable: true,
get: function() {
return APICallError;
}
});
Object.defineProperty(exports, "DEFAULT_MAX_DOWNLOAD_SIZE", {
enumerable: true,
get: function() {
return DEFAULT_MAX_DOWNLOAD_SIZE;
}
});
Object.defineProperty(exports, "DelayedPromise", {
enumerable: true,
get: function() {
return DelayedPromise;
}
});
Object.defineProperty(exports, "DownloadError", {
enumerable: true,
get: function() {
return DownloadError;
}
});
Object.defineProperty(exports, "GatewayAuthenticationError", {
enumerable: true,
get: function() {
return GatewayAuthenticationError;
}
});
Object.defineProperty(exports, "GatewayError", {
enumerable: true,
get: function() {
return GatewayError;
}
});
Object.defineProperty(exports, "InvalidPromptError", {
enumerable: true,
get: function() {
return InvalidPromptError;
}
});
Object.defineProperty(exports, "InvalidResponseDataError", {
enumerable: true,
get: function() {
return InvalidResponseDataError;
}
});
Object.defineProperty(exports, "TypeValidationError", {
enumerable: true,
get: function() {
return TypeValidationError;
}
});
Object.defineProperty(exports, "UnsupportedFunctionalityError", {
enumerable: true,
get: function() {
return UnsupportedFunctionalityError;
}
});
Object.defineProperty(exports, "asSchema", {
enumerable: true,
get: function() {
return asSchema;
}
});
Object.defineProperty(exports, "cancelResponseBody", {
enumerable: true,
get: function() {
return cancelResponseBody;
}
});
Object.defineProperty(exports, "convertBase64ToUint8Array", {
enumerable: true,
get: function() {
return convertBase64ToUint8Array;
}
});
Object.defineProperty(exports, "convertUint8ArrayToBase64", {
enumerable: true,
get: function() {
return convertUint8ArrayToBase64;
}
});
Object.defineProperty(exports, "createGatewayProvider", {
enumerable: true,
get: function() {
return createGatewayProvider;
}
});
Object.defineProperty(exports, "createIdGenerator", {
enumerable: true,
get: function() {
return createIdGenerator;
}
});
Object.defineProperty(exports, "executeTool", {
enumerable: true,
get: function() {
return executeTool;
}
});
Object.defineProperty(exports, "fetchWithValidatedRedirects", {
enumerable: true,
get: function() {
return fetchWithValidatedRedirects;
}
});
Object.defineProperty(exports, "gateway", {
enumerable: true,
get: function() {
return gateway;
}
});
Object.defineProperty(exports, "getErrorMessage", {
enumerable: true,
get: function() {
return getErrorMessage;
}
});
Object.defineProperty(exports, "getErrorMessage$1", {
enumerable: true,
get: function() {
return getErrorMessage$1;
}
});
Object.defineProperty(exports, "getRuntimeEnvironmentUserAgent", {
enumerable: true,
get: function() {
return getRuntimeEnvironmentUserAgent;
}
});
Object.defineProperty(exports, "isAbortError", {
enumerable: true,
get: function() {
return isAbortError;
}
});
Object.defineProperty(exports, "isArrayBuffer", {
enumerable: true,
get: function() {
return isArrayBuffer;
}
});
Object.defineProperty(exports, "isUint8Array", {
enumerable: true,
get: function() {
return isUint8Array;
}
});
Object.defineProperty(exports, "isUrlSupported", {
enumerable: true,
get: function() {
return isUrlSupported;
}
});
Object.defineProperty(exports, "lazySchema", {
enumerable: true,
get: function() {
return lazySchema;
}
});
Object.defineProperty(exports, "readResponseWithSizeLimit", {
enumerable: true,
get: function() {
return readResponseWithSizeLimit;
}
});
Object.defineProperty(exports, "resolve", {
enumerable: true,
get: function() {
return resolve;
}
});
Object.defineProperty(exports, "retryWithExponentialBackoff", {
enumerable: true,
get: function() {
return retryWithExponentialBackoff;
}
});
Object.defineProperty(exports, "safeParseJSON", {
enumerable: true,
get: function() {
return safeParseJSON;
}
});
Object.defineProperty(exports, "safeValidateTypes", {
enumerable: true,
get: function() {
return safeValidateTypes;
}
});
Object.defineProperty(exports, "validateTypes", {
enumerable: true,
get: function() {
return validateTypes;
}
});
Object.defineProperty(exports, "withUserAgentSuffix", {
enumerable: true,
get: function() {
return withUserAgentSuffix;
}
});
Object.defineProperty(exports, "zodSchema", {
enumerable: true,
get: function() {
return zodSchema;
}
});
//# sourceMappingURL=dist-ByO0vuJJ-BjMue5_p.cjs.map