@mastra/core
Version:
5,719 lines • 189 kB
JavaScript
import * as z4 from "zod/v4";
import { z } from "zod/v4";
import { ZodFirstPartyTypeKind } from "zod/v3";
import { z as z$1 } from "zod";
// ../_vendored/ai_v5/dist/dist-DIfsHMRS.js
var marker$1 = "vercel.ai.error";
var symbol$1$1 = Symbol.for(marker$1);
var _a$1$1;
var _b$1;
var AISDKError = class _AISDKError extends (_b$1 = Error, _a$1$1 = symbol$1$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$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$1 = "AI_APICallError";
var marker2$2 = `vercel.ai.error.${name$1$1}`;
var symbol2$2 = Symbol.for(marker2$2);
var _a2$2;
var _b2$1;
var APICallError = class extends (_b2$1 = AISDKError, _a2$2 = symbol2$2, _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$1,
message,
cause
});
this[_a2$2] = 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$2);
}
};
var name2$2 = "AI_EmptyResponseBodyError";
var marker3$2 = `vercel.ai.error.${name2$2}`;
var symbol3$2 = Symbol.for(marker3$2);
var _a3$2;
var _b3$1;
var EmptyResponseBodyError = class extends (_b3$1 = AISDKError, _a3$2 = symbol3$2, _b3$1) {
constructor({ message = "Empty response body" } = {}) {
super({
name: name2$2,
message
});
this[_a3$2] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker3$2);
}
};
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$2 = "AI_InvalidArgumentError";
var marker4$2 = `vercel.ai.error.${name3$2}`;
var symbol4$2 = Symbol.for(marker4$2);
var _a4$2;
var _b4$1;
var InvalidArgumentError$1 = class extends (_b4$1 = AISDKError, _a4$2 = symbol4$2, _b4$1) {
constructor({ message, cause, argument }) {
super({
name: name3$2,
message,
cause
});
this[_a4$2] = true;
this.argument = argument;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker4$2);
}
};
var name5$2 = "AI_InvalidResponseDataError";
var marker6$2 = `vercel.ai.error.${name5$2}`;
var symbol6$2 = Symbol.for(marker6$2);
var _a6$2;
var _b6$1;
var InvalidResponseDataError = class extends (_b6$1 = AISDKError, _a6$2 = symbol6$2, _b6$1) {
constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {
super({
name: name5$2,
message
});
this[_a6$2] = true;
this.data = data;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker6$2);
}
};
var name6$2 = "AI_JSONParseError";
var marker7$2 = `vercel.ai.error.${name6$2}`;
var symbol7$2 = Symbol.for(marker7$2);
var _a7$2;
var _b7$1;
var JSONParseError = class extends (_b7$1 = AISDKError, _a7$2 = symbol7$2, _b7$1) {
constructor({ text, cause }) {
super({
name: name6$2,
message: `JSON parsing failed: Text: ${text}.
Error message: ${getErrorMessage$1(cause)}`,
cause
});
this[_a7$2] = true;
this.text = text;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker7$2);
}
};
var name12$1 = "AI_TypeValidationError";
var marker13$1 = `vercel.ai.error.${name12$1}`;
var symbol13$1 = Symbol.for(marker13$1);
var _a13$1;
var _b13;
var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13$1 = symbol13$1, _b13) {
constructor({ value, cause }) {
super({
name: name12$1,
message: `Type validation failed: Value: ${JSON.stringify(value)}.
Error message: ${getErrorMessage$1(cause)}`,
cause
});
this[_a13$1] = true;
this.value = value;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker13$1);
}
/**
* Wraps an error into a TypeValidationError.
* If the cause is already a TypeValidationError with the same value, 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.
* @returns {TypeValidationError} A TypeValidationError instance.
*/
static wrap({ value, cause }) {
return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({
value,
cause
});
}
};
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 Promise.resolve();
const signal = options == null ? void 0 : options.abortSignal;
return new Promise((resolve2, reject) => {
if (signal == null ? void 0 : signal.aborted) {
reject(createAbortError());
return;
}
const timeoutId = setTimeout(() => {
cleanup();
resolve2();
}, delayInMs);
const cleanup = () => {
clearTimeout(timeoutId);
signal?.removeEventListener("abort", onAbort);
};
const onAbort = () => {
cleanup();
reject(createAbortError());
};
signal?.addEventListener("abort", onAbort);
});
}
function createAbortError() {
return new DOMException("Delay was aborted", "AbortError");
}
function extractResponseHeaders(response) {
return Object.fromEntries([...response.headers]);
}
var name$2 = "AI_DownloadError";
var marker$2 = `vercel.ai.error.${name$2}`;
var symbol$2 = Symbol.for(marker$2);
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$2);
}
};
async function cancelResponseBody(response) {
var _a2;
try {
await ((_a2 = response.body) == null ? void 0 : _a2.cancel());
} catch (e) {}
}
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);
return builtinModule == null ? await importNodeModule(id) : builtinModule;
}
function importNodeModule(id) {
return import(id);
}
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 MAX_DOWNLOAD_REDIRECTS = 10;
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 : new Headers(headers);
const perHopInit = (redirect) => ({
signal: abortSignal,
redirect,
...currentHeaders === void 0 ? {} : { headers: new Headers(currentHeaders) }
});
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 (response.status >= 300 && response.status < 400 && 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$1({
argument: "separator",
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
});
return () => `${prefix}${separator}${generator()}`;
};
var generateId = 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$3 = "3.0.46";
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$3}`, 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 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;
}
}
var validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
function validator(validate) {
return {
[validatorSymbol]: true,
validate
};
}
function isValidator(value) {
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
}
function lazyValidator(createValidator) {
let validator2;
return () => {
if (validator2 == null) validator2 = createValidator();
return validator2;
};
}
function asValidator(value) {
return isValidator(value) ? value : "~standard" in value ? standardSchemaValidator(value) : value();
}
function standardSchemaValidator(standardSchema) {
return validator(async (value) => {
const result = await standardSchema["~standard"].validate(value);
return result.issues == null ? {
success: true,
value: result.value
} : {
success: false,
error: new TypeValidationError({
value,
cause: result.issues
})
};
});
}
async function validateTypes({ value, schema }) {
const result = await safeValidateTypes({
value,
schema
});
if (!result.success) throw TypeValidationError.wrap({
value,
cause: result.error
});
return result.value;
}
async function safeValidateTypes({ value, schema }) {
const validator2 = asValidator(schema);
try {
if (validator2.validate == null) return {
success: true,
value,
rawValue: value
};
const result = await validator2.validate(value);
if (result.success) return {
success: true,
value: result.value,
rawValue: value
};
return {
success: false,
error: TypeValidationError.wrap({
value,
cause: result.error
}),
rawValue: value
};
} catch (error) {
return {
success: false,
error: TypeValidationError.wrap({
value,
cause: error
}),
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$3}`, 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 createProviderDefinedToolFactoryWithOutputSchema({ id, name: name2, inputSchema, outputSchema }) {
return ({ execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({
type: "provider-defined",
id,
name: name2,
args,
inputSchema,
outputSchema,
execute,
toModelOutput,
onInputStart,
onInputDelta,
onInputAvailable
});
}
async function resolve(value) {
if (typeof value === "function") value = value();
return Promise.resolve(value);
}
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
};
};
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,
[validatorSymbol]: true,
get jsonSchema() {
if (typeof jsonSchema2 === "function") jsonSchema2 = jsonSchema2();
return jsonSchema2;
},
validate
};
}
function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
if (jsonSchema2.type === "object") {
const { additionalProperties } = jsonSchema2;
jsonSchema2.additionalProperties = additionalProperties != null && typeof additionalProperties !== "boolean" ? addAdditionalPropertiesToJsonSchema(additionalProperties) : false;
const properties = jsonSchema2.properties;
if (properties != null) for (const property in properties) properties[property] = addAdditionalPropertiesToJsonSchema(properties[property]);
}
if (jsonSchema2.type === "array" && jsonSchema2.items != null) {
if (Array.isArray(jsonSchema2.items)) jsonSchema2.items = jsonSchema2.items.map((item) => addAdditionalPropertiesToJsonSchema(item));
else jsonSchema2.items = addAdditionalPropertiesToJsonSchema(jsonSchema2.items);
}
return jsonSchema2;
}
var ignoreOverride = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions = {
name: void 0,
$refStrategy: "root",
basePath: ["#"],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: true,
rejectedAdditionalProperties: false,
definitionPath: "definitions",
strictUnions: false,
definitions: {},
errorMessages: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref"
};
var getDefaultOptions = (options) => typeof options === "string" ? {
...defaultOptions,
name: options
} : {
...defaultOptions,
...options
};
function parseAnyDef() {
return {};
}
function parseArrayDef(def, refs) {
var _a2, _b2, _c;
const res = { type: "array" };
if (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
});
if (def.minLength) res.minItems = def.minLength.value;
if (def.maxLength) res.maxItems = def.maxLength.value;
if (def.exactLength) {
res.minItems = def.exactLength.value;
res.maxItems = def.exactLength.value;
}
return res;
}
function parseBigintDef(def) {
const res = {
type: "integer",
format: "int64"
};
if (!def.checks) return res;
for (const check of def.checks) switch (check.kind) {
case "min":
if (check.inclusive) res.minimum = check.value;
else res.exclusiveMinimum = check.value;
break;
case "max":
if (check.inclusive) res.maximum = check.value;
else res.exclusiveMaximum = check.value;
break;
case "multipleOf": res.multipleOf = check.value;
}
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) === 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) === ZodFirstPartyTypeKind.ZodEnum) return {
...schema,
propertyNames: { enum: def.keyType._def.values }
};
else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
const { type, ...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 ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs);
case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def);
case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs);
case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def);
case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef();
case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs);
case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef();
case ZodFirstPartyTypeKind.ZodNull: return parseNullDef();
case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs);
case ZodFirstPartyTypeKind.ZodUnion:
case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs);
case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs);
case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs);
case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs);
case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def);
case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def);
case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def);
case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs);
case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs);
case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs);
case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs);
case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;
case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs);
case ZodFirstPartyTypeKind.ZodNaN:
case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef();
case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs);
case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef();
case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef();
case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs);
case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs);
case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs);
case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs);
case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs);
case ZodFirstPartyTypeKind.ZodFunction:
case ZodFirstPartyTypeKind.ZodVoid:
case ZodFirstPartyTypeKind.ZodSymbol: return;
default: return /* @__PURE__ */ ((_) => void 0)(typeName);
}
};
var getRelativePath = (pathA, pathB) => {
let i = 0;
for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
};
function parseDef(def, refs, forceResolution = false) {
var _a2;
const seenItem = refs.seen.get(def);
if (refs.override) {
const overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(refs, def, refs, seenItem, forceResolution);
if (overrideResult !== ignoreOverride) return overrideResult;
}
if (seenItem && !forceResolution) {
const seenSchema = get$ref(seenItem, refs);
if (seenSchema !== void 0) return seenSchema;
}
const newItem = {
def,
path: refs.currentPath,
jsonSchema: void 0
};
refs.seen.set(def, newItem);
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
if (jsonSchema2) addMeta(def, refs, jsonSchema2);
if (refs.postProcess) {
const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
newItem.jsonSchema = jsonSchema2;
return postProcessResult;
}
newItem.jsonSchema = jsonSchema2;
return jsonSchema2;
}
var get$ref = (item, refs) => {
switch (refs.$refStrategy) {
case "root": return { $ref: item.path.join("/") };
case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) };
case "none":
case "seen":
if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
return parseAnyDef();
}
return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
}
};
var addMeta = (def, refs, jsonSchema2) => {
if (def.description) jsonSchema2.description = def.description;
return jsonSchema2;
};
var getRefs = (options) => {
const _options = getDefaultOptions(options);
const currentPath = _options.name !== void 0 ? [
..._options.basePath,
_options.definitionPath,
_options.name
] : _options.basePath;
return {
..._options,
currentPath,
propertyPath: void 0,
seen: new Map(Object.entries(_options.definitions).map(([name2, def]) => [def._def, {
def: def._def,
path: [
..._options.basePath,
_options.definitionPath,
name2
],
jsonSchema: void 0
}]))
};
};
var zodToJsonSchema = (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 zod_to_json_schema_default = zodToJsonSchema;
function zod3Schema(zodSchema2, options) {
var _a2;
const useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;
return jsonSchema(() => zod_to_json_schema_default(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(z4.toJSONSchema(zodSchema2, {
target: "draft-7",
io: "input",
reused: useReferences ? "ref" : "inline"
})), { validate: async (value) => {
const result = await z4.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);
}
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({
properties: {},
additionalProperties: false
}) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
}
var { btoa, atob: atob$1 } = globalThis;
function convertBase64ToUint8Array(base64String) {
const latin1string = atob$1(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;
}
}
function withoutTrailingSlash(url) {
return url == null ? void 0 : url.replace(/\/$/, "");
}
// ../_vendored/ai_v5/dist/dist-Ds6WOguF.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$1 = Symbol.for("vercel.ai.gateway.error");
var _a$1;
var _b;
var GatewayError = class _GatewayError extends (_b = Error, _a$1 = symbol$1, _b) {
constructor({ message, statusCode = 500, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500) }) {
super(message);
this[_a$1] = true;
this.statusCode = statusCode;
this.cause = cause;
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$1 in error && error[symbol$1] === true;
}
};
var name$1 = "GatewayAuthenticationError";
var marker2$1 = `vercel.ai.gateway.error.${name$1}`;
var symbol2$1 = Symbol.for(marker2$1);
var _a2$1;
var _b2;
var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a2$1 = symbol2$1, _b2) {
constructor({ message = "Authentication failed", statusCode = 401, cause } = {}) {
super({
message,
statusCode,
cause
});
this[_a2$1] = true;
this.name = name$1;
this.type = "authentication_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol2$1 in error;
}
/**
* Creates a contextual error message when authentication fails
*/
static createContextualError({ apiKeyProvided, oidcTokenProvided, message = "Authentication failed", statusCode = 401, cause }) {
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
});
}
};
var name2$1 = "GatewayForbiddenError";
var marker3$1 = `vercel.ai.gateway.error.${name2$1}`;
var symbol3$1 = Symbol.for(marker3$1);
var forbiddenParamSchema = lazyValidator(() => zodSchema(z.object({ ruleId: z.string() })));
var _a3$1;
var _b3;
var GatewayForbiddenError = class extends (_b3 = GatewayError, _a3$1 = symbol3$1, _b3) {
constructor({ message = "Forbidden", statusCode = 403, cause, ruleId } = {}) {
super({
message,
statusCode,
cause
});
this[_a3$1] = true;
this.name = name2$1;
this.type = "forbidden";
this.ruleId = ruleId;
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol3$1 in error;
}
};
var name3$1 = "GatewayInvalidRequestError";
var marker4$1 = `vercel.ai.gateway.error.${name3$1}`;
var symbol4$1 = Symbol.for(marker4$1);
var _a4$1;
var _b4;
var GatewayInvalidRequestError = class extends (_b4 = GatewayError, _a4$1 = symbol4$1, _b4) {
constructor({ message = "Invalid request", statusCode = 400, cause } = {}) {
super({
message,
statusCode,
cause
});
this[_a4$1] = true;
this.name = name3$1;
this.type = "invalid_request_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol4$1 in error;
}
};
var name4$1 = "GatewayRateLimitError";
var marker5$1 = `vercel.ai.gateway.error.${name4$1}`;
var symbol5$1 = Symbol.for(marker5$1);
var _a5$1;
var _b5;
var GatewayRateLimitError = class extends (_b5 = GatewayError, _a5$1 = symbol5$1, _b5) {
constructor({ message = "Rate limit exceeded", statusCode = 429, cause } = {}) {
super({
message,
statusCode,
cause
});
this[_a5$1] = true;
this.name = name4$1;
this.type = "rate_limit_exceeded";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol5$1 in error;
}
};
var name5$1 = "GatewayModelNotFoundError";
var marker6$1 = `vercel.ai.gateway.error.${name5$1}`;
var symbol6$1 = Symbol.for(marker6$1);
var modelNotFoundParamSchema = lazyValidator(() => zodSchema(z.object({ modelId: z.string() })));
var _a6$1;
var _b6;
var GatewayModelNotFoundError = class extends (_b6 = GatewayError, _a6$1 = symbol6$1, _b6) {
constructor({ message = "Model not found", statusCode = 404, modelId, cause } = {}) {
super({
message,
statusCode,
cause
});
this[_a6$1] = true;
this.name = name5$1;
this.type = "model_not_found";
this.modelId = modelId;
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol6$1 in error;
}
};
var name6$1 = "GatewayInternalServerError";
var marker7$1 = `vercel.ai.gateway.error.${name6$1}`;
var symbol7$1 = Symbol.for(marker7$1);
var _a7$1;
var _b7;
var GatewayInternalServerError = class extends (_b7 = GatewayError, _a7$1 = symbol7$1, _b7) {
constructor({ message = "Internal server error", statusCode = 500, cause } = {}) {
super({
message,
statusCode,
cause
});
this[_a7$1] = true;
this.name = name6$1;
this.type = "internal_server_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol7$1 in error;
}
};
var name7$1 = "GatewayResponseError";
var marker8$1 = `vercel.ai.gateway.error.${name7$1}`;
var symbol8$1 = Symbol.for(marker8$1);
var _a8$1;
var _b8;
var GatewayResponseError = class extends (_b8 = GatewayError, _a8$1 = symbol8$1, _b8) {
constructor({ message = "Invalid response from Gateway", statusCode = 502, response, validationError, cause, isRetryable } = {}) {
super({
message,
statusCode,
cause,
isRetryable
});
this[_a8$1] = true;
this.name = name7$1;
this.type = "response_error";
this.response = response;
this.validationError = validationError;
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol8$1 in error;
}
};
async function createGatewayErrorFromResponse({ response, statusCode, defaultMessage = "Gateway request failed", cause, authMethod, isRetryable }) {
const parseResult = await safeValidateTypes({
value: response,
schema: gatewayErrorResponseSchema
});
if (!parseResult.success) return new GatewayResponseError({
message: `Invalid error response format: ${defaultMessage}`,
statusCode,
response,
validationError: parseResult.error,
cause,
isRetryable
});
const validatedResponse = parseResult.value;
const errorType = validatedResponse.error.type;
const message = validatedResponse.error.message;
switch (errorType) {
case "authentication_error": return GatewayAuthenticationError.createContextualError({
apiKeyProvided: authMethod === "api-key",
oidcTokenProvided: authMethod === "oidc",
statusCode,
cause
});
case "invalid_request_error": return new GatewayInvalidRequestError({
message,
statusCode,
cause
});
case "rate_limit_exceeded": return new GatewayRateLimitError({
message,
statusCode,
cause
});
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
});
}
case "internal_server_error": return new GatewayInternalServerError({
message,
statusCode,
cause
});
case "forbidden": {
const ruleResult = await safeValidateTypes({
value: validatedResponse.error.param,
schema: forbiddenParamSchema
});
return new GatewayForbiddenError({
message,
statusCode,
cause,
ruleId: ruleResult.success ? ruleResult.value.ruleId : void 0
});
}
default: return new GatewayInternalServerError({
message,
statusCode,
cause
});
}
}
var gatewayErrorResponseSchema = lazyValidator(() => zodSchema(z.object({ error: z.object({
message: z.string(),
type: z.string().nullish(),
param: z.unknown().nullish(),
code: z.union([z.string(), z.number()]).nullish()
}) })));
function extractApiCallResponse(error) {
if (error.data !== void 0) return error.data;
if (error.responseBody != null) try {
return JSON.parse(error.responseBody);
} catch (e) {
return error.responseBody;
}
return {};
}
var name8$1 = "GatewayTimeoutError";
var marker9$1 = `vercel.ai.gateway.error.${name8$1}`;
var symbol9$1 = Symbol.for(marker9$1);
var _a9$1;
var _b9;
var GatewayTimeoutError = class _GatewayTimeoutError extends (_b9 = GatewayError, _a9$1 = symbol9$1, _b9) {
constructor({ message = "Request timed out", statusCode = 408, cause } = {}) {
super({
message,
statusCode,
cause
});
this[_a9$1] = true;
this.name = name8$1;
this.type = "timeout_error";
}
static isInstance(error) {
return GatewayError.hasMarker(error) && symbol9$1 in error;
}
/**
* Creates a helpful timeout error message with troubleshooting guidance
*/
static createTimeoutError({ originalMessage, statusCode = 408, cause }) {
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
});
}
};
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 _a10;
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: (_a10 = error.statusCode) != null ? _a10 : 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 = lazyValidator(() => zodSchema(z.union([z.literal("api-key"), z.literal("oidc")])));
var KNOWN_MODEL_TYPES = [
"embedding",
"image",
"language"
];
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: z.any(),
errorToMessage: (data) => {
var _a10;
return (_a10 = getErrorMessage(data)) != null ? _a10 : "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: z.any(),
errorToMessage: (data) => {
var _a10;
return (_a10 = getErrorMessage(data)) != null ? _a10 : "unknown error";
}
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
var gatewayAvailableModelsResponseSchema = lazyValidator(() => zodSchema(z.object({ models: z.array(z.object({
id: z.string(),
name: z.string(),
description: z.string().nullish(),
pricing: z.object({
input: z.string(),
output: z.string(),
input_cache_read: z.string().nullish(),
input_cache_write: 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: z.object({
specificationVersion: z.literal("v2"),
provider: z.string(),
modelId: z.string()
}),
modelType: z.string().nullish()
})).transform((models) => models.filter((m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType))) })));
var gatewayCreditsResponseSchema = lazyValidator(() => zodSchema(z.object({
balance: z.string(),
total_used: 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: z.any(),
errorToMessage: (data) => {
var _a10;
return (_a10 = getErrorMessage(data)) != null ? _a10 : "unknown error";
}
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
var gatewaySpendReportResponseSchema = lazySchema(() => zodSchema(z.object({ results: z.array(z.object({
day: z.string().optional(),
hour: z.string().optional(),
user: z.string().optional(),
model: z.string().optional(),
tag: z.string().optional(),
provider: z.string().optional(),
credential_type: z.enum(["byok", "system"]).optional(),
total_cost: z.number(),
market_cost: z.number().optional(),
input_tokens: z.number().optional(),
output_tokens: z.number().optional(),
cached_input_tokens: z.number().optional(),
cache_creation_input_tokens: z.number().optional(),
reasoning_tokens: z.number().optional(),
request_count: 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: z.any(),
errorToMessage: (data) => {
var _a10;
return (_a10 = getErrorMessage(data)) != null ? _a10 : "unknown error";
}
}),
fetch: this.config.fetch
});
return value;
} catch (error) {
throw await asGatewayError(error);
}
}
};
var gatewayGenerationInfoResponseSchema = lazySchema(() => zodSchema(z.object({ data: z.object({
id: z.string(),
total_cost: z.number(),
upstream_inference_cost: z.number(),
usage: z.number(),
created_at: z.string(),
model: z.string(),
is_byok: z.boolean(),
provider_name: z.string(),
streamed: z.boolean(),
finish_reason: z.string(),
latency: z.number(),
generation_time: z.number(),
native_tokens_prompt: z.number(),
native_tokens_completion: z.number(),
native_tokens_reasoning: z.number(),
native_tokens_cached: z.number(),
native_tokens_cache_creation: z.number(),
billable_web_search_calls: 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 = "v2";
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 _a10;
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(z.any()),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => {
var _a11;
return (_a11 = getErrorMessage(data)) != null ? _a11 : "unknown error";
}
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
...responseBody,
request: { body: args },
response: {
headers: responseHeaders,
body: rawResponse
},
warnings: [...(_a10 = responseBody.warnings) != null ? _a10 : [], ...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(z.any()),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => {
var _a10;
return (_a10 = getErrorMessage(data)) != null ? _a10 : "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": "2",
"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 = "v2";
this.maxEmbeddingsPerCall = 2048;
this.supportsParallelCalls = true;
}
get provider() {
return this.config.provider;
}
async doEmbed({ values, headers, abortSignal, providerOptions }) {
var _a10;
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: {
input: values.length === 1 ? values[0] : values,
...providerOptions ? { providerOptions } : {}
},
successfulResponseHandler: createJsonResponseHandler(gatewayEmbeddingResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => {
var _a11;
return (_a11 = getErrorMessage(data)) != null ? _a11 : "unknown error";
}
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
embeddings: responseBody.embeddings,
usage: (_a10 = responseBody.usage) != null ? _a10 : void 0,
providerMetadata: responseBody.providerMetadata,
response: {
headers: responseHeaders,
body: rawValue
}
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
}
}
getUrl() {
return `${this.config.baseURL}/embedding-model`;
}
getModelConfigHeaders() {
return {
"ai-embedding-model-specification-version": "2",
"ai-model-id": this.modelId
};
}
};
var gatewayEmbeddingResponseSchema = lazyValidator(() => zodSchema(z.object({
embeddings: z.array(z.array(z.number())),
usage: z.object({ tokens: z.number() }).nullish(),
providerMetadata: z.record(z.string(), z.record(z.string(), z.unknown())).optional()
})));
var GatewayImageModel = class {
constructor(modelId, config) {
this.modelId = modelId;
this.config = config;
this.specificationVersion = "v2";
this.maxImagesPerCall = Number.MAX_SAFE_INTEGER;
}
get provider() {
return this.config.provider;
}
async doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) {
var _a10, _b10, _c, _d;
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 }
},
successfulResponseHandler: createJsonResponseHandler(gatewayImageResponseSchema),
failedResponseHandler: createJsonErrorResponseHandler({
errorSchema: z.any(),
errorToMessage: (data) => {
var _a11;
return (_a11 = getErrorMessage(data)) != null ? _a11 : "unknown error";
}
}),
...abortSignal && { abortSignal },
fetch: this.config.fetch
});
return {
images: responseBody.images,
...responseBody.isRetryable != null && { isRetryable: responseBody.isRetryable },
warnings: (_a10 = responseBody.warnings) != null ? _a10 : [],
providerMetadata: responseBody.providerMetadata,
response: {
timestamp: /* @__PURE__ */ new Date(),
modelId: this.modelId,
headers: responseHeaders
},
...responseBody.usage != null && { usage: {
inputTokens: (_b10 = responseBody.usage.inputTokens) != null ? _b10 : void 0,
outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,
totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0
} }
};
} catch (error) {
throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
}
}
getUrl() {
return `${this.config.baseURL}/image-model`;
}
getModelConfigHeaders() {
return {
"ai-image-model-specification-version": "2",
"ai-model-id": this.modelId
};
}
};
var providerMetadataEntrySchema = () => z.object({ images: z.array(z.unknown()).optional() }).catchall(z.unknown());
var gatewayImageUsageSchema = () => z.object({
inputTokens: z.number().nullish(),
outputTokens: z.number().nullish(),
totalTokens: z.number().nullish()
});
var gatewayImageResponseSchema = lazySchema(() => zodSchema(z.object({
images: z.array(z.string()),
isRetryable: z.boolean().optional(),
warnings: z.array(z.object({
type: z.literal("other"),
message: z.string()
})).optional(),
providerMetadata: z.record(z.string(), providerMetadataEntrySchema()).optional(),
usage: gatewayImageUsageSchema().optional()
})));
var parallelSearchModes = [
"turbo",
"fast",
"basic",
"advanced",
"one-shot",
"agentic"
];
var parallelSearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
id: "gateway.parallel_search",
name: "parallel_search",
inputSchema: lazySchema(() => zodSchema(z$1.object({
objective: z$1.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: z$1.array(z$1.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: z$1.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: z$1.number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),
source_policy: z$1.object({
include_domains: z$1.array(z$1.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: z$1.array(z$1.string()).optional().describe("Domains or domain/path prefixes to exclude, without scheme or port. Example: ['reddit.com']."),
after_date: z$1.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: z$1.object({
max_chars_per_result: z$1.number().optional().describe("Maximum characters per result."),
max_chars_total: z$1.number().optional().describe("Deprecated: use the top-level max_chars_total.")
}).optional().describe("Excerpt configuration for controlling result length."),
max_chars_total: z$1.number().optional().describe("Maximum total characters across all result excerpts."),
fetch_policy: z$1.object({
max_age_seconds: z$1.number().optional().describe("Maximum age of cached content in seconds before a live fetch, minimum 600."),
timeout_seconds: z$1.number().optional().describe("Timeout in seconds for a live fetch when content is not cached. Capped by the gateway tool timeout."),
disable_cache_fallback: z$1.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: z$1.string().optional().describe("ISO 3166-1 alpha-2 country code to localize results, e.g. \"us\".")
}))),
outputSchema: lazySchema(() => zodSchema(z$1.union([z$1.object({
search_id: z$1.string(),
results: z$1.array(z$1.object({
url: z$1.string(),
title: z$1.string().nullable().optional(),
publish_date: z$1.string().nullable().optional(),
excerpts: z$1.array(z$1.string())
})),
warnings: z$1.array(z$1.object({
type: z$1.string(),
message: z$1.string(),
detail: z$1.record(z$1.string(), z$1.unknown()).nullable().optional()
})).nullable().optional(),
usage: z$1.array(z$1.object({
name: z$1.string(),
count: z$1.number().optional()
})).nullable().optional(),
session_id: z$1.string().optional()
}), z$1.object({
error: z$1.enum([
"api_error",
"configuration_error",
"execution_error",
"gateway_rate_limit",
"invalid_input",
"rate_limit",
"timeout",
"unknown",
"unknown_tool"
]),
statusCode: z$1.number().optional(),
message: z$1.string()
})])))
});
var parallelSearch = (config = {}) => parallelSearchToolFactory(config);
var perplexitySearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({
id: "gateway.perplexity_search",
name: "perplexity_search",
inputSchema: lazySchema(() => zodSchema(z$1.object({
query: z$1.union([z$1.string(), z$1.array(z$1.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: z$1.number().optional().describe("Maximum number of search results to return (1-20, default: 10)"),
max_tokens_per_page: z$1.number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),
max_tokens: z$1.number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),
country: z$1.string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),
search_domain_filter: z$1.array(z$1.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: z$1.array(z$1.string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),
search_after_date: z$1.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: z$1.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: z$1.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: z$1.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: z$1.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(z$1.union([z$1.object({
results: z$1.array(z$1.object({
title: z$1.string(),
url: z$1.string(),
snippet: z$1.string(),
date: z$1.string().optional(),
lastUpdated: z$1.string().optional()
})),
id: z$1.string()
}), z$1.object({
error: z$1.enum([
"api_error",
"rate_limit",
"timeout",
"invalid_input",
"unknown"
]),
statusCode: z$1.number().optional(),
message: z$1.string()
})])))
});
var perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
var gatewayTools = {
/**
* Search the web using Parallel AI's Search API for LLM-optimized excerpts.
*
* Takes a natural language objective and returns relevant excerpts,
* replacing multiple keyword searches with a single call for broad
* or complex queries. Supports different search types for depth vs
* breadth tradeoffs.
*/
parallelSearch,
/**
* Search the web using Perplexity's Search API for real-time information,
* news, research papers, and articles.
*
* Provides ranked search results with advanced filtering options including
* domain, language, date range, and recency filters.
*/
perplexitySearch
};
async function getVercelRequestId() {
var _a10;
return (_a10 = getContext().headers) == null ? void 0 : _a10["x-vercel-id"];
}
var VERSION$2 = "2.0.176";
var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
function createGatewayProvider(options = {}) {
var _a10, _b10;
let pendingMetadata = null;
let metadataCache = null;
const cacheRefreshMillis = (_a10 = options.metadataCacheRefreshMillis) != null ? _a10 : 3e5;
let lastFetchTime = 0;
const baseURL = (_b10 = withoutTrailingSlash(options.baseURL)) != null ? _b10 : "https://ai-gateway.vercel.sh/v1/ai";
const getHeaders = async () => {
const auth = await getGatewayAuthToken(options);
if (auth) 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$2}`);
throw GatewayAuthenticationError.createContextualError({
apiKeyProvided: false,
oidcTokenProvided: false,
statusCode: 401
});
};
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 _a11, _b11, _c;
const now = (_c = (_b11 = (_a11 = options._internal) == null ? void 0 : _a11.currentDate) == null ? void 0 : _b11.call(_a11).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.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;
provider.textEmbeddingModel = (modelId) => {
return new GatewayEmbeddingModel(modelId, {
provider: "gateway",
baseURL,
headers: getHeaders,
fetch: options.fetch,
o11yHeaders: createO11yHeaders()
});
};
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"
};
try {
return {
token: await getVercelOidcToken(),
authMethod: "oidc"
};
} catch (e) {
return null;
}
}
// ../_vendored/ai_v5/dist/index.js
/** only globals that common to node and browsers are allowed */
var _globalThis = typeof globalThis === "object" ? globalThis : global;
var VERSION$1 = "1.9.0";
var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
/**
* Create a function to test an API version to see if it is compatible with the provided ownVersion.
*
* The returned function has the following semantics:
* - Exact match is always compatible
* - Major versions must match exactly
* - 1.x package cannot use global 2.x package
* - 2.x package cannot use global 1.x package
* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API
* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects
* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3
* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor
* - Patch and build tag differences are not considered at this time
*
* @param ownVersion version which should be checked against
*/
function _makeCompatibilityCheck(ownVersion) {
var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
var rejectedVersions = /* @__PURE__ */ new Set();
var myVersionMatch = ownVersion.match(re);
if (!myVersionMatch) return function() {
return false;
};
var ownVersionParsed = {
major: +myVersionMatch[1],
minor: +myVersionMatch[2],
patch: +myVersionMatch[3],
prerelease: myVersionMatch[4]
};
if (ownVersionParsed.prerelease != null) return function isExactmatch(globalVersion) {
return globalVersion === ownVersion;
};
function _reject(v) {
rejectedVersions.add(v);
return false;
}
function _accept(v) {
acceptedVersions.add(v);
return true;
}
return function isCompatible(globalVersion) {
if (acceptedVersions.has(globalVersion)) return true;
if (rejectedVersions.has(globalVersion)) return false;
var globalVersionMatch = globalVersion.match(re);
if (!globalVersionMatch) return _reject(globalVersion);
var globalVersionParsed = {
major: +globalVersionMatch[1],
minor: +globalVersionMatch[2],
patch: +globalVersionMatch[3],
prerelease: globalVersionMatch[4]
};
if (globalVersionParsed.prerelease != null) return _reject(globalVersion);
if (ownVersionParsed.major !== globalVersionParsed.major) return _reject(globalVersion);
if (ownVersionParsed.major === 0) {
if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) return _accept(globalVersion);
return _reject(globalVersion);
}
if (ownVersionParsed.minor <= globalVersionParsed.minor) return _accept(globalVersion);
return _reject(globalVersion);
};
}
/**
* Test an API version to see if it is compatible with this API.
*
* - Exact match is always compatible
* - Major versions must match exactly
* - 1.x package cannot use global 2.x package
* - 2.x package cannot use global 1.x package
* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API
* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects
* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3
* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor
* - Patch and build tag differences are not considered at this time
*
* @param version version of the API requesting an instance of the global API
*/
var isCompatible = _makeCompatibilityCheck(VERSION$1);
var major = VERSION$1.split(".")[0];
var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
var _global = _globalThis;
function registerGlobal(type, instance, diag, allowOverride) {
var _a;
if (allowOverride === void 0) allowOverride = false;
var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: VERSION$1 };
if (!allowOverride && api[type]) {
var err = /* @__PURE__ */ new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
diag.error(err.stack || err.message);
return false;
}
if (api.version !== "1.9.0") {
var err = /* @__PURE__ */ new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION$1);
diag.error(err.stack || err.message);
return false;
}
api[type] = instance;
diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION$1 + ".");
return true;
}
function getGlobal(type) {
var _a, _b;
var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
if (!globalVersion || !isCompatible(globalVersion)) return;
return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
}
function unregisterGlobal(type, diag) {
diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION$1 + ".");
var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
if (api) delete api[type];
}
var __read$3 = function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray$3 = function(to, from, pack) {
if (pack || arguments.length === 2) {
for (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
/**
* Component Logger which is meant to be used as part of any component which
* will add automatically additional namespace in front of the log message.
* It will then forward all message to global diag logger
* @example
* const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });
* cLogger.debug('test');
* // @opentelemetry/instrumentation-http test
*/
var DiagComponentLogger = function() {
function DiagComponentLogger(props) {
this._namespace = props.namespace || "DiagComponentLogger";
}
DiagComponentLogger.prototype.debug = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];
return logProxy("debug", this._namespace, args);
};
DiagComponentLogger.prototype.error = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];
return logProxy("error", this._namespace, args);
};
DiagComponentLogger.prototype.info = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];
return logProxy("info", this._namespace, args);
};
DiagComponentLogger.prototype.warn = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];
return logProxy("warn", this._namespace, args);
};
DiagComponentLogger.prototype.verbose = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];
return logProxy("verbose", this._namespace, args);
};
return DiagComponentLogger;
}();
function logProxy(funcName, namespace, args) {
var logger = getGlobal("diag");
if (!logger) return;
args.unshift(namespace);
return logger[funcName].apply(logger, __spreadArray$3([], __read$3(args), false));
}
/**
* Defines the available internal logging levels for the diagnostic logger, the numeric values
* of the levels are defined to match the original values from the initial LogLevel to avoid
* compatibility/migration issues for any implementation that assume the numeric ordering.
*/
var DiagLogLevel;
(function(DiagLogLevel) {
/** Diagnostic Logging level setting to disable all logging (except and forced logs) */
DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE";
/** Identifies an error scenario */
DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR";
/** Identifies a warning scenario */
DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN";
/** General informational log message */
DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO";
/** General debug log message */
DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG";
/**
* Detailed trace level logging should only be used for development, should only be set
* in a development environment.
*/
DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE";
/** Used to set the logging level to include all logging */
DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL";
})(DiagLogLevel || (DiagLogLevel = {}));
function createLogLevelDiagLogger(maxLevel, logger) {
if (maxLevel < DiagLogLevel.NONE) maxLevel = DiagLogLevel.NONE;
else if (maxLevel > DiagLogLevel.ALL) maxLevel = DiagLogLevel.ALL;
logger = logger || {};
function _filterFunc(funcName, theLevel) {
var theFunc = logger[funcName];
if (typeof theFunc === "function" && maxLevel >= theLevel) return theFunc.bind(logger);
return function() {};
}
return {
error: _filterFunc("error", DiagLogLevel.ERROR),
warn: _filterFunc("warn", DiagLogLevel.WARN),
info: _filterFunc("info", DiagLogLevel.INFO),
debug: _filterFunc("debug", DiagLogLevel.DEBUG),
verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
};
}
var __read$2 = function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray$2 = function(to, from, pack) {
if (pack || arguments.length === 2) {
for (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var API_NAME$2 = "diag";
/**
* Singleton object which represents the entry point to the OpenTelemetry internal
* diagnostic API
*/
var DiagAPI = function() {
/**
* Private internal constructor
* @private
*/
function DiagAPI() {
function _logProxy(funcName) {
return function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];
var logger = getGlobal("diag");
if (!logger) return;
return logger[funcName].apply(logger, __spreadArray$2([], __read$2(args), false));
};
}
var self = this;
var setLogger = function(logger, optionsOrLogLevel) {
var _a, _b, _c;
if (optionsOrLogLevel === void 0) optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
if (logger === self) {
var err = /* @__PURE__ */ new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
return false;
}
if (typeof optionsOrLogLevel === "number") optionsOrLogLevel = { logLevel: optionsOrLogLevel };
var oldLogger = getGlobal("diag");
var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
var stack = (_c = (/* @__PURE__ */ new Error()).stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
oldLogger.warn("Current logger will be overwritten from " + stack);
newLogger.warn("Current logger will overwrite one already registered from " + stack);
}
return registerGlobal("diag", newLogger, self, true);
};
self.setLogger = setLogger;
self.disable = function() {
unregisterGlobal(API_NAME$2, self);
};
self.createComponentLogger = function(options) {
return new DiagComponentLogger(options);
};
self.verbose = _logProxy("verbose");
self.debug = _logProxy("debug");
self.info = _logProxy("info");
self.warn = _logProxy("warn");
self.error = _logProxy("error");
}
/** Get the singleton instance of the DiagAPI API */
DiagAPI.instance = function() {
if (!this._instance) this._instance = new DiagAPI();
return this._instance;
};
return DiagAPI;
}();
/** Get a key to uniquely identify a context value */
function createContextKey(description) {
return Symbol.for(description);
}
/** The root context is used as the default parent context when there is no active context */
var ROOT_CONTEXT = new (function() {
/**
* Construct a new context which inherits values from an optional parent context.
*
* @param parentContext a context from which to inherit values
*/
function BaseContext(parentContext) {
var self = this;
self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
self.getValue = function(key) {
return self._currentContext.get(key);
};
self.setValue = function(key, value) {
var context = new BaseContext(self._currentContext);
context._currentContext.set(key, value);
return context;
};
self.deleteValue = function(key) {
var context = new BaseContext(self._currentContext);
context._currentContext.delete(key);
return context;
};
}
return BaseContext;
}())();
var __read$1 = function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray$1 = function(to, from, pack) {
if (pack || arguments.length === 2) {
for (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var NoopContextManager = function() {
function NoopContextManager() {}
NoopContextManager.prototype.active = function() {
return ROOT_CONTEXT;
};
NoopContextManager.prototype.with = function(_context, fn, thisArg) {
var args = [];
for (var _i = 3; _i < arguments.length; _i++) args[_i - 3] = arguments[_i];
return fn.call.apply(fn, __spreadArray$1([thisArg], __read$1(args), false));
};
NoopContextManager.prototype.bind = function(_context, target) {
return target;
};
NoopContextManager.prototype.enable = function() {
return this;
};
NoopContextManager.prototype.disable = function() {
return this;
};
return NoopContextManager;
}();
var __read = function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray = function(to, from, pack) {
if (pack || arguments.length === 2) {
for (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var API_NAME$1 = "context";
var NOOP_CONTEXT_MANAGER = new NoopContextManager();
/**
* Singleton object which represents the entry point to the OpenTelemetry Context API
*/
var ContextAPI = function() {
/** Empty private constructor prevents end users from constructing a new instance of the API */
function ContextAPI() {}
/** Get the singleton instance of the Context API */
ContextAPI.getInstance = function() {
if (!this._instance) this._instance = new ContextAPI();
return this._instance;
};
/**
* Set the current context manager.
*
* @returns true if the context manager was successfully registered, else false
*/
ContextAPI.prototype.setGlobalContextManager = function(contextManager) {
return registerGlobal(API_NAME$1, contextManager, DiagAPI.instance());
};
/**
* Get the currently active context
*/
ContextAPI.prototype.active = function() {
return this._getContextManager().active();
};
/**
* Execute a function with an active context
*
* @param context context to be active during function execution
* @param fn function to execute in a context
* @param thisArg optional receiver to be used for calling fn
* @param args optional arguments forwarded to fn
*/
ContextAPI.prototype.with = function(context, fn, thisArg) {
var _a;
var args = [];
for (var _i = 3; _i < arguments.length; _i++) args[_i - 3] = arguments[_i];
return (_a = this._getContextManager()).with.apply(_a, __spreadArray([
context,
fn,
thisArg
], __read(args), false));
};
/**
* Bind a context to a target function or event emitter
*
* @param context context to bind to the event emitter or function. Defaults to the currently active context
* @param target function or event emitter to bind
*/
ContextAPI.prototype.bind = function(context, target) {
return this._getContextManager().bind(context, target);
};
ContextAPI.prototype._getContextManager = function() {
return getGlobal(API_NAME$1) || NOOP_CONTEXT_MANAGER;
};
/** Disable and remove the global context manager */
ContextAPI.prototype.disable = function() {
this._getContextManager().disable();
unregisterGlobal(API_NAME$1, DiagAPI.instance());
};
return ContextAPI;
}();
var TraceFlags;
(function(TraceFlags) {
/** Represents no flag set. */
TraceFlags[TraceFlags["NONE"] = 0] = "NONE";
/** Bit to represent whether trace is sampled in trace flags. */
TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED";
})(TraceFlags || (TraceFlags = {}));
var INVALID_SPAN_CONTEXT = {
traceId: "00000000000000000000000000000000",
spanId: "0000000000000000",
traceFlags: TraceFlags.NONE
};
/**
* The NonRecordingSpan is the default {@link Span} that is used when no Span
* implementation is available. All operations are no-op including context
* propagation.
*/
var NonRecordingSpan = function() {
function NonRecordingSpan(_spanContext) {
if (_spanContext === void 0) _spanContext = INVALID_SPAN_CONTEXT;
this._spanContext = _spanContext;
}
NonRecordingSpan.prototype.spanContext = function() {
return this._spanContext;
};
NonRecordingSpan.prototype.setAttribute = function(_key, _value) {
return this;
};
NonRecordingSpan.prototype.setAttributes = function(_attributes) {
return this;
};
NonRecordingSpan.prototype.addEvent = function(_name, _attributes) {
return this;
};
NonRecordingSpan.prototype.addLink = function(_link) {
return this;
};
NonRecordingSpan.prototype.addLinks = function(_links) {
return this;
};
NonRecordingSpan.prototype.setStatus = function(_status) {
return this;
};
NonRecordingSpan.prototype.updateName = function(_name) {
return this;
};
NonRecordingSpan.prototype.end = function(_endTime) {};
NonRecordingSpan.prototype.isRecording = function() {
return false;
};
NonRecordingSpan.prototype.recordException = function(_exception, _time) {};
return NonRecordingSpan;
}();
/**
* span key
*/
var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
/**
* Return the span if one exists
*
* @param context context to get span from
*/
function getSpan(context) {
return context.getValue(SPAN_KEY) || void 0;
}
/**
* Gets the span from the current context, if one exists.
*/
function getActiveSpan() {
return getSpan(ContextAPI.getInstance().active());
}
/**
* Set the span on a context
*
* @param context context to use as parent
* @param span span to set active
*/
function setSpan(context, span) {
return context.setValue(SPAN_KEY, span);
}
/**
* Remove current span stored in the context
*
* @param context context to delete span from
*/
function deleteSpan(context) {
return context.deleteValue(SPAN_KEY);
}
/**
* Wrap span context in a NoopSpan and set as span in a new
* context
*
* @param context context to set active span on
* @param spanContext span context to be wrapped
*/
function setSpanContext(context, spanContext) {
return setSpan(context, new NonRecordingSpan(spanContext));
}
/**
* Get the span context of the span if it exists.
*
* @param context context to get values from
*/
function getSpanContext(context) {
var _a;
return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();
}
var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
function isValidTraceId(traceId) {
return VALID_TRACEID_REGEX.test(traceId) && traceId !== "00000000000000000000000000000000";
}
function isValidSpanId(spanId) {
return VALID_SPANID_REGEX.test(spanId) && spanId !== "0000000000000000";
}
/**
* Returns true if this {@link SpanContext} is valid.
* @return true if this {@link SpanContext} is valid.
*/
function isSpanContextValid(spanContext) {
return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
}
/**
* Wrap the given {@link SpanContext} in a new non-recording {@link Span}
*
* @param spanContext span context to be wrapped
* @returns a new non-recording {@link Span} with the provided context
*/
function wrapSpanContext(spanContext) {
return new NonRecordingSpan(spanContext);
}
var contextApi = ContextAPI.getInstance();
/**
* No-op implementations of {@link Tracer}.
*/
var NoopTracer = function() {
function NoopTracer() {}
NoopTracer.prototype.startSpan = function(name, options, context) {
if (context === void 0) context = contextApi.active();
if (Boolean(options === null || options === void 0 ? void 0 : options.root)) return new NonRecordingSpan();
var parentFromContext = context && getSpanContext(context);
if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) return new NonRecordingSpan(parentFromContext);
else return new NonRecordingSpan();
};
NoopTracer.prototype.startActiveSpan = function(name, arg2, arg3, arg4) {
var opts;
var ctx;
var fn;
if (arguments.length < 2) return;
else if (arguments.length === 2) fn = arg2;
else if (arguments.length === 3) {
opts = arg2;
fn = arg3;
} else {
opts = arg2;
ctx = arg3;
fn = arg4;
}
var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
var span = this.startSpan(name, opts, parentContext);
var contextWithSpanSet = setSpan(parentContext, span);
return contextApi.with(contextWithSpanSet, fn, void 0, span);
};
return NoopTracer;
}();
function isSpanContext(spanContext) {
return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
}
var NOOP_TRACER = new NoopTracer();
/**
* Proxy tracer provided by the proxy tracer provider
*/
var ProxyTracer = function() {
function ProxyTracer(_provider, name, version, options) {
this._provider = _provider;
this.name = name;
this.version = version;
this.options = options;
}
ProxyTracer.prototype.startSpan = function(name, options, context) {
return this._getTracer().startSpan(name, options, context);
};
ProxyTracer.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
var tracer = this._getTracer();
return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
};
/**
* Try to get a tracer from the proxy tracer provider.
* If the proxy tracer provider has no delegate, return a noop tracer.
*/
ProxyTracer.prototype._getTracer = function() {
if (this._delegate) return this._delegate;
var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
if (!tracer) return NOOP_TRACER;
this._delegate = tracer;
return this._delegate;
};
return ProxyTracer;
}();
var NOOP_TRACER_PROVIDER = new (function() {
function NoopTracerProvider() {}
NoopTracerProvider.prototype.getTracer = function(_name, _version, _options) {
return new NoopTracer();
};
return NoopTracerProvider;
}())();
/**
* Tracer provider which provides {@link ProxyTracer}s.
*
* Before a delegate is set, tracers provided are NoOp.
* When a delegate is set, traces are provided from the delegate.
* When a delegate is set after tracers have already been provided,
* all tracers already provided will use the provided delegate implementation.
*/
var ProxyTracerProvider = function() {
function ProxyTracerProvider() {}
/**
* Get a {@link ProxyTracer}
*/
ProxyTracerProvider.prototype.getTracer = function(name, version, options) {
var _a;
return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);
};
ProxyTracerProvider.prototype.getDelegate = function() {
var _a;
return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
};
/**
* Set the delegate tracer provider
*/
ProxyTracerProvider.prototype.setDelegate = function(delegate) {
this._delegate = delegate;
};
ProxyTracerProvider.prototype.getDelegateTracer = function(name, version, options) {
var _a;
return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
};
return ProxyTracerProvider;
}();
/**
* An enumeration of status codes.
*/
var SpanStatusCode;
(function(SpanStatusCode) {
/**
* The default status.
*/
SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET";
/**
* The operation has been validated by an Application developer or
* Operator to have completed successfully.
*/
SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK";
/**
* The operation contains an error.
*/
SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR";
})(SpanStatusCode || (SpanStatusCode = {}));
var API_NAME = "trace";
/** Entrypoint for trace API */
var trace = function() {
/** Empty private constructor prevents end users from constructing a new instance of the API */
function TraceAPI() {
this._proxyTracerProvider = new ProxyTracerProvider();
this.wrapSpanContext = wrapSpanContext;
this.isSpanContextValid = isSpanContextValid;
this.deleteSpan = deleteSpan;
this.getSpan = getSpan;
this.getActiveSpan = getActiveSpan;
this.getSpanContext = getSpanContext;
this.setSpan = setSpan;
this.setSpanContext = setSpanContext;
}
/** Get the singleton instance of the Trace API */
TraceAPI.getInstance = function() {
if (!this._instance) this._instance = new TraceAPI();
return this._instance;
};
/**
* Set the current global tracer.
*
* @returns true if the tracer provider was successfully registered, else false
*/
TraceAPI.prototype.setGlobalTracerProvider = function(provider) {
var success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance());
if (success) this._proxyTracerProvider.setDelegate(provider);
return success;
};
/**
* Returns the global tracer provider.
*/
TraceAPI.prototype.getTracerProvider = function() {
return getGlobal(API_NAME) || this._proxyTracerProvider;
};
/**
* Returns a tracer from the global tracer provider.
*/
TraceAPI.prototype.getTracer = function(name, version) {
return this.getTracerProvider().getTracer(name, version);
};
/** Remove the global tracer provider */
TraceAPI.prototype.disable = function() {
unregisterGlobal(API_NAME, DiagAPI.instance());
this._proxyTracerProvider = new ProxyTracerProvider();
};
return TraceAPI;
}().getInstance();
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name17 in all) __defProp(target, name17, {
get: all[name17],
enumerable: true
});
};
function formatWarning(warning) {
const prefix = "AI SDK Warning:";
switch (warning.type) {
case "unsupported-setting": {
let message = `${prefix} The "${warning.setting}" setting is not supported by this model`;
if (warning.details) message += ` - ${warning.details}`;
return message;
}
case "unsupported-tool": {
let message = `${prefix} The tool "${"name" in warning.tool ? warning.tool.name : "unknown tool"}" is not supported by this model`;
if (warning.details) message += ` - ${warning.details}`;
return message;
}
case "other": return `${prefix} ${warning.message}`;
default: return `${prefix} ${JSON.stringify(warning, null, 2)}`;
}
}
var FIRST_WARNING_INFO_MESSAGE = "AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.";
var hasLoggedBefore = false;
function emitWarning({ message, type }) {
if (typeof process !== "undefined" && typeof process.emitWarning === "function") process.emitWarning(message, { type });
else console.warn(message);
}
var logWarnings = (warnings) => {
if (warnings.length === 0) return;
const logger = globalThis.AI_SDK_LOG_WARNINGS;
if (logger === false) return;
if (typeof logger === "function") {
logger(warnings);
return;
}
if (!hasLoggedBefore) {
hasLoggedBefore = true;
emitWarning({
message: FIRST_WARNING_INFO_MESSAGE,
type: "Warning"
});
}
for (const warning of warnings) emitWarning({
message: formatWarning(warning),
type: "Warning"
});
};
var name3 = "AI_InvalidArgumentError";
var marker3 = `vercel.ai.error.${name3}`;
var symbol3 = Symbol.for(marker3);
var _a3;
var InvalidArgumentError = class extends AISDKError {
constructor({ parameter, value, message }) {
super({
name: name3,
message: `Invalid argument for parameter ${parameter}: ${message}`
});
this[_a3] = true;
this.parameter = parameter;
this.value = value;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker3);
}
};
_a3 = symbol3;
var name7 = "AI_NoObjectGeneratedError";
var marker7 = `vercel.ai.error.${name7}`;
var symbol7 = Symbol.for(marker7);
var _a7;
var NoObjectGeneratedError = class extends AISDKError {
constructor({ message = "No object generated.", cause, text: text2, response, usage, finishReason }) {
super({
name: name7,
message,
cause
});
this[_a7] = true;
this.text = text2;
this.response = response;
this.usage = usage;
this.finishReason = finishReason;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker7);
}
};
_a7 = symbol7;
var NoSpeechGeneratedError = class extends AISDKError {
constructor(options) {
super({
name: "AI_NoSpeechGeneratedError",
message: "No speech audio generated."
});
this.responses = options.responses;
}
};
var UnsupportedModelVersionError = class extends AISDKError {
constructor(options) {
super({
name: "AI_UnsupportedModelVersionError",
message: `Unsupported model version ${options.version} for provider "${options.provider}" and model "${options.modelId}". AI SDK 5 only supports models that implement specification version "v2".`
});
this.version = options.version;
this.provider = options.provider;
this.modelId = options.modelId;
}
};
var name11 = "AI_InvalidDataContentError";
var marker11 = `vercel.ai.error.${name11}`;
var symbol11 = Symbol.for(marker11);
var _a11;
var InvalidDataContentError = class extends AISDKError {
constructor({ content, cause, message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.` }) {
super({
name: name11,
message,
cause
});
this[_a11] = true;
this.content = content;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker11);
}
};
_a11 = symbol11;
var name13 = "AI_MessageConversionError";
var marker13 = `vercel.ai.error.${name13}`;
var symbol13 = Symbol.for(marker13);
var _a13;
var MessageConversionError = class extends AISDKError {
constructor({ originalMessage, message }) {
super({
name: name13,
message
});
this[_a13] = true;
this.originalMessage = originalMessage;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker13);
}
};
_a13 = symbol13;
var name15 = "AI_RetryError";
var marker15 = `vercel.ai.error.${name15}`;
var symbol15 = Symbol.for(marker15);
var _a15;
var RetryError = class extends AISDKError {
constructor({ message, reason, errors }) {
super({
name: name15,
message
});
this[_a15] = true;
this.reason = reason;
this.errors = errors;
this.lastError = errors[errors.length - 1];
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker15);
}
};
_a15 = symbol15;
function resolveEmbeddingModel(model) {
if (typeof model !== "string") {
if (model.specificationVersion !== "v2") throw new UnsupportedModelVersionError({
version: model.specificationVersion,
provider: model.provider,
modelId: model.modelId
});
return model;
}
return getGlobalProvider().textEmbeddingModel(model);
}
function getGlobalProvider() {
var _a17;
return (_a17 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a17 : gateway;
}
var audioMediaTypeSignatures = [
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 251]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 250]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 243]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 242]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 227]
},
{
mediaType: "audio/mpeg",
bytesPrefix: [255, 226]
},
{
mediaType: "audio/wav",
bytesPrefix: [
82,
73,
70,
70,
null,
null,
null,
null,
87,
65,
86,
69
]
},
{
mediaType: "audio/ogg",
bytesPrefix: [
79,
103,
103,
83
]
},
{
mediaType: "audio/flac",
bytesPrefix: [
102,
76,
97,
67
]
},
{
mediaType: "audio/aac",
bytesPrefix: [
64,
21,
0,
0
]
},
{
mediaType: "audio/mp4",
bytesPrefix: [
0,
0,
0,
null,
102,
116,
121,
112
]
},
{
mediaType: "audio/webm",
bytesPrefix: [
26,
69,
223,
163
]
}
];
var DEFAULT_SNIFF_BYTES = 18;
var ID3_SCAN_BYTES = 131084;
function decodePrefix(data, maxBytes) {
if (typeof data !== "string") return data.length > maxBytes ? data.subarray(0, maxBytes) : data;
const maxChars = Math.ceil(maxBytes / 3) * 4;
const bytes = convertBase64ToUint8Array(data.substring(0, Math.min(data.length, maxChars)));
return bytes.length > maxBytes ? bytes.subarray(0, maxBytes) : bytes;
}
function hasID3(bytes) {
return bytes.length > 10 && bytes[0] === 73 && bytes[1] === 68 && bytes[2] === 51;
}
var stripID3 = (bytes) => {
const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
return bytes.subarray(id3Size + 10);
};
function detectMediaType({ data, signatures }) {
let bytes = decodePrefix(data, DEFAULT_SNIFF_BYTES);
if (hasID3(bytes)) bytes = stripID3(decodePrefix(data, ID3_SCAN_BYTES));
for (const signature of signatures) if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => byte === null || bytes[index] === byte)) return signature.mediaType;
}
var VERSION = "5.0.285";
var download = async ({ url, maxBytes, abortSignal }) => {
var _a17;
const urlText = url.toString();
try {
const response = await fetchWithValidatedRedirects({
url: urlText,
headers: withUserAgentSuffix({}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent()),
abortSignal
});
if (!response.ok) {
await cancelResponseBody(response);
throw new DownloadError({
url: urlText,
statusCode: response.status,
statusText: response.statusText
});
}
return {
data: await readResponseWithSizeLimit({
response,
url: urlText,
maxBytes: maxBytes != null ? maxBytes : DEFAULT_MAX_DOWNLOAD_SIZE
}),
mediaType: (_a17 = response.headers.get("content-type")) != null ? _a17 : void 0
};
} catch (error) {
if (DownloadError.isInstance(error)) throw error;
throw new DownloadError({
url: urlText,
cause: error
});
}
};
var dataContentSchema = z.union([
z.string(),
z.custom(isUint8Array, { message: "Must be a Uint8Array" }),
z.custom(isArrayBuffer, { message: "Must be an ArrayBuffer" }),
z.custom((value) => {
var _a17, _b;
return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
}, { message: "Must be a Buffer" })
]);
function convertDataContentToUint8Array(content) {
if (isUint8Array(content)) {
if (content instanceof Uint8Array) return content;
const { buffer, byteOffset, byteLength } = content;
return new Uint8Array(buffer, byteOffset, byteLength);
}
if (typeof content === "string") try {
return convertBase64ToUint8Array(content);
} catch (error) {
throw new InvalidDataContentError({
message: "Invalid data content. Content string is not a base64-encoded media.",
content,
cause: error
});
}
if (isArrayBuffer(content)) return new Uint8Array(content);
throw new InvalidDataContentError({ content });
}
var jsonValueSchema = z.lazy(() => z.union([
z.null(),
z.string(),
z.number(),
z.boolean(),
z.record(z.string(), jsonValueSchema.optional()),
z.array(jsonValueSchema)
]));
var providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema));
var textPartSchema = z.object({
type: z.literal("text"),
text: z.string(),
providerOptions: providerMetadataSchema.optional()
});
var imagePartSchema = z.object({
type: z.literal("image"),
image: z.union([dataContentSchema, z.instanceof(URL)]),
mediaType: z.string().optional(),
providerOptions: providerMetadataSchema.optional()
});
var filePartSchema = z.object({
type: z.literal("file"),
data: z.union([dataContentSchema, z.instanceof(URL)]),
filename: z.string().optional(),
mediaType: z.string(),
providerOptions: providerMetadataSchema.optional()
});
var reasoningPartSchema = z.object({
type: z.literal("reasoning"),
text: z.string(),
providerOptions: providerMetadataSchema.optional()
});
var toolCallPartSchema = z.object({
type: z.literal("tool-call"),
toolCallId: z.string(),
toolName: z.string(),
input: z.unknown(),
providerOptions: providerMetadataSchema.optional(),
providerExecuted: z.boolean().optional()
});
var outputSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("text"),
value: z.string()
}),
z.object({
type: z.literal("json"),
value: jsonValueSchema
}),
z.object({
type: z.literal("error-text"),
value: z.string()
}),
z.object({
type: z.literal("error-json"),
value: jsonValueSchema
}),
z.object({
type: z.literal("content"),
value: z.array(z.union([z.object({
type: z.literal("text"),
text: z.string()
}), z.object({
type: z.literal("media"),
data: z.string(),
mediaType: z.string()
})]))
})
]);
var toolResultPartSchema = z.object({
type: z.literal("tool-result"),
toolCallId: z.string(),
toolName: z.string(),
output: outputSchema,
providerOptions: providerMetadataSchema.optional()
});
var systemModelMessageSchema = z.object({
role: z.literal("system"),
content: z.string(),
providerOptions: providerMetadataSchema.optional()
});
var userModelMessageSchema = z.object({
role: z.literal("user"),
content: z.union([z.string(), z.array(z.union([
textPartSchema,
imagePartSchema,
filePartSchema
]))]),
providerOptions: providerMetadataSchema.optional()
});
var assistantModelMessageSchema = z.object({
role: z.literal("assistant"),
content: z.union([z.string(), z.array(z.union([
textPartSchema,
filePartSchema,
reasoningPartSchema,
toolCallPartSchema,
toolResultPartSchema
]))]),
providerOptions: providerMetadataSchema.optional()
});
var toolModelMessageSchema = z.object({
role: z.literal("tool"),
content: z.array(toolResultPartSchema),
providerOptions: providerMetadataSchema.optional()
});
z.union([
systemModelMessageSchema,
userModelMessageSchema,
assistantModelMessageSchema,
toolModelMessageSchema
]);
function assembleOperationName({ operationId, telemetry }) {
return {
"operation.name": `${operationId}${(telemetry == null ? void 0 : telemetry.functionId) != null ? ` ${telemetry.functionId}` : ""}`,
"resource.name": telemetry == null ? void 0 : telemetry.functionId,
"ai.operationId": operationId,
"ai.telemetry.functionId": telemetry == null ? void 0 : telemetry.functionId
};
}
function getTelemetryMetadataAttributes(telemetry) {
var _a17;
return Object.entries((_a17 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a17 : {}).reduce((attributes, [key, value]) => {
attributes[`ai.telemetry.metadata.${key}`] = value;
return attributes;
}, {});
}
function getBaseTelemetryAttributes({ model, settings, telemetry, headers }) {
return {
"ai.model.provider": model.provider,
"ai.model.id": model.modelId,
...Object.entries(settings).reduce((attributes, [key, value]) => {
attributes[`ai.settings.${key}`] = value;
return attributes;
}, {}),
...getTelemetryMetadataAttributes(telemetry),
...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => {
if (value !== void 0) attributes[`ai.request.headers.${key}`] = value;
return attributes;
}, {})
};
}
var noopTracer = {
startSpan() {
return noopSpan;
},
startActiveSpan(name17, arg1, arg2, arg3) {
if (typeof arg1 === "function") return arg1(noopSpan);
if (typeof arg2 === "function") return arg2(noopSpan);
if (typeof arg3 === "function") return arg3(noopSpan);
}
};
var noopSpan = {
spanContext() {
return noopSpanContext;
},
setAttribute() {
return this;
},
setAttributes() {
return this;
},
addEvent() {
return this;
},
addLink() {
return this;
},
addLinks() {
return this;
},
setStatus() {
return this;
},
updateName() {
return this;
},
end() {
return this;
},
isRecording() {
return false;
},
recordException() {
return this;
}
};
var noopSpanContext = {
traceId: "",
spanId: "",
traceFlags: 0
};
function getTracer({ isEnabled = false, tracer } = {}) {
if (!isEnabled) return noopTracer;
if (tracer) return tracer;
return trace.getTracer("ai");
}
function recordSpan({ name: name17, tracer, attributes, fn, endWhenDone = true, endOnError = endWhenDone }) {
return tracer.startActiveSpan(name17, { attributes }, async (span) => {
try {
const result = await fn(span);
if (endWhenDone) span.end();
return result;
} catch (error) {
try {
recordErrorOnSpan(span, error);
} finally {
if (endOnError) span.end();
}
throw error;
}
});
}
function recordErrorOnSpan(span, error) {
if (error instanceof Error) {
span.recordException({
name: error.name,
message: error.message,
stack: error.stack
});
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
} else span.setStatus({ code: SpanStatusCode.ERROR });
}
function selectTelemetryAttributes({ telemetry, attributes }) {
if ((telemetry == null ? void 0 : telemetry.isEnabled) !== true) return {};
return Object.entries(attributes).reduce((attributes2, [key, value]) => {
if (value == null) return attributes2;
if (typeof value === "object" && "input" in value && typeof value.input === "function") {
if ((telemetry == null ? void 0 : telemetry.recordInputs) === false) return attributes2;
const result = value.input();
return result == null ? attributes2 : {
...attributes2,
[key]: result
};
}
if (typeof value === "object" && "output" in value && typeof value.output === "function") {
if ((telemetry == null ? void 0 : telemetry.recordOutputs) === false) return attributes2;
const result = value.output();
return result == null ? attributes2 : {
...attributes2,
[key]: result
};
}
return {
...attributes2,
[key]: value
};
}, {});
}
function getRetryDelayInMs({ error, exponentialBackoffDelay }) {
const headers = APICallError.isInstance(error) ? error.responseHeaders : APICallError.isInstance(error.cause) ? error.cause.responseHeaders : void 0;
if (!headers) return exponentialBackoffDelay;
let ms;
const retryAfterMs = headers["retry-after-ms"];
if (retryAfterMs) {
const timeoutMs = parseFloat(retryAfterMs);
if (!Number.isNaN(timeoutMs)) ms = timeoutMs;
}
const retryAfter = headers["retry-after"];
if (retryAfter && ms === void 0) {
const timeoutSeconds = parseFloat(retryAfter);
if (!Number.isNaN(timeoutSeconds)) ms = timeoutSeconds * 1e3;
else ms = Date.parse(retryAfter) - Date.now();
}
if (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 6e4 || ms < exponentialBackoffDelay)) return ms;
return exponentialBackoffDelay;
}
var retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal, additionalRetryableError } = {}) => async (f) => _retryWithExponentialBackoff(f, {
maxRetries,
delayInMs: initialDelayInMs,
backoffFactor,
abortSignal,
additionalRetryableError
});
async function _retryWithExponentialBackoff(f, { maxRetries, delayInMs, backoffFactor, abortSignal, additionalRetryableError }, 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 new RetryError({
message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
reason: "maxRetriesExceeded",
errors: newErrors
});
if ((error instanceof Error && (APICallError.isInstance(error) && error.isRetryable === true || GatewayError.isInstance(error) && error.isRetryable === true) || (additionalRetryableError == null ? void 0 : additionalRetryableError(error)) === true) && tryNumber <= maxRetries) {
await delay(getRetryDelayInMs({
error,
exponentialBackoffDelay: delayInMs
}), { abortSignal });
return _retryWithExponentialBackoff(f, {
maxRetries,
delayInMs: backoffFactor * delayInMs,
backoffFactor,
abortSignal,
additionalRetryableError
}, newErrors);
}
if (tryNumber === 1) throw error;
throw new RetryError({
message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
reason: "errorNotRetryable",
errors: newErrors
});
}
}
function prepareRetries({ maxRetries, abortSignal, additionalRetryableError }) {
if (maxRetries != null) {
if (!Number.isInteger(maxRetries)) throw new InvalidArgumentError({
parameter: "maxRetries",
value: maxRetries,
message: "maxRetries must be an integer"
});
if (maxRetries < 0) throw new InvalidArgumentError({
parameter: "maxRetries",
value: maxRetries,
message: "maxRetries must be >= 0"
});
}
const maxRetriesResult = maxRetries != null ? maxRetries : 2;
return {
maxRetries: maxRetriesResult,
retry: retryWithExponentialBackoffRespectingRetryHeaders({
maxRetries: maxRetriesResult,
abortSignal,
additionalRetryableError
})
};
}
var DefaultGeneratedFile = class {
constructor({ data, mediaType }) {
this.base64Data = typeof data === "string" ? data : void 0;
this.uint8ArrayData = typeof data === "string" ? void 0 : convertDataContentToUint8Array(data);
this.mediaType = mediaType;
}
get base64() {
if (this.base64Data == null) this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);
return this.base64Data;
}
get uint8Array() {
if (this.uint8ArrayData == null) this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);
return this.uint8ArrayData;
}
};
function createToolModelOutput({ output, tool: tool2, errorMode }) {
if (errorMode === "text") return {
type: "error-text",
value: getErrorMessage$1(output)
};
else if (errorMode === "json") return {
type: "error-json",
value: toJSONValue(output)
};
if (tool2 == null ? void 0 : tool2.toModelOutput) return tool2.toModelOutput(output);
return typeof output === "string" ? {
type: "text",
value: output
} : {
type: "json",
value: toJSONValue(output)
};
}
function toJSONValue(value) {
return value === void 0 ? null : value;
}
createIdGenerator({
prefix: "aitxt",
size: 24
});
TransformStream;
function fixJson(input) {
const stack = ["ROOT"];
let lastValidIndex = -1;
let literalStart = null;
function processValueStart(char, i, swapState) {
switch (char) {
case "\"":
lastValidIndex = i;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_STRING");
break;
case "f":
case "t":
case "n":
lastValidIndex = i;
literalStart = i;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_LITERAL");
break;
case "-":
stack.pop();
stack.push(swapState);
stack.push("INSIDE_NUMBER");
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
lastValidIndex = i;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_NUMBER");
break;
case "{":
lastValidIndex = i;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_OBJECT_START");
break;
case "[":
lastValidIndex = i;
stack.pop();
stack.push(swapState);
stack.push("INSIDE_ARRAY_START");
}
}
function processAfterObjectValue(char, i) {
switch (char) {
case ",":
stack.pop();
stack.push("INSIDE_OBJECT_AFTER_COMMA");
break;
case "}":
lastValidIndex = i;
stack.pop();
}
}
function processAfterArrayValue(char, i) {
switch (char) {
case ",":
stack.pop();
stack.push("INSIDE_ARRAY_AFTER_COMMA");
break;
case "]":
lastValidIndex = i;
stack.pop();
}
}
for (let i = 0; i < input.length; i++) {
const char = input[i];
switch (stack[stack.length - 1]) {
case "ROOT":
processValueStart(char, i, "FINISH");
break;
case "INSIDE_OBJECT_START":
switch (char) {
case "\"":
stack.pop();
stack.push("INSIDE_OBJECT_KEY");
break;
case "}":
lastValidIndex = i;
stack.pop();
}
break;
case "INSIDE_OBJECT_AFTER_COMMA":
switch (char) {
case "\"":
stack.pop();
stack.push("INSIDE_OBJECT_KEY");
}
break;
case "INSIDE_OBJECT_KEY":
switch (char) {
case "\"":
stack.pop();
stack.push("INSIDE_OBJECT_AFTER_KEY");
}
break;
case "INSIDE_OBJECT_AFTER_KEY":
switch (char) {
case ":":
stack.pop();
stack.push("INSIDE_OBJECT_BEFORE_VALUE");
}
break;
case "INSIDE_OBJECT_BEFORE_VALUE":
processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
break;
case "INSIDE_OBJECT_AFTER_VALUE":
processAfterObjectValue(char, i);
break;
case "INSIDE_STRING":
switch (char) {
case "\"":
stack.pop();
lastValidIndex = i;
break;
case "\\":
stack.push("INSIDE_STRING_ESCAPE");
break;
default: lastValidIndex = i;
}
break;
case "INSIDE_ARRAY_START":
switch (char) {
case "]":
lastValidIndex = i;
stack.pop();
break;
default:
lastValidIndex = i;
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
}
break;
case "INSIDE_ARRAY_AFTER_VALUE":
switch (char) {
case ",":
stack.pop();
stack.push("INSIDE_ARRAY_AFTER_COMMA");
break;
case "]":
lastValidIndex = i;
stack.pop();
break;
default: lastValidIndex = i;
}
break;
case "INSIDE_ARRAY_AFTER_COMMA":
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
break;
case "INSIDE_STRING_ESCAPE":
stack.pop();
lastValidIndex = i;
break;
case "INSIDE_NUMBER":
switch (char) {
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
lastValidIndex = i;
break;
case "e":
case "E":
case "-":
case ".": break;
case ",":
stack.pop();
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i);
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") processAfterObjectValue(char, i);
break;
case "}":
stack.pop();
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") processAfterObjectValue(char, i);
break;
case "]":
stack.pop();
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i);
break;
default: stack.pop();
}
break;
case "INSIDE_LITERAL": {
const partialLiteral = input.substring(literalStart, i + 1);
if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
stack.pop();
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") processAfterObjectValue(char, i);
else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") processAfterArrayValue(char, i);
} else lastValidIndex = i;
break;
}
}
}
let result = input.slice(0, lastValidIndex + 1);
for (let i = stack.length - 1; i >= 0; i--) switch (stack[i]) {
case "INSIDE_STRING":
result += "\"";
break;
case "INSIDE_OBJECT_KEY":
case "INSIDE_OBJECT_AFTER_KEY":
case "INSIDE_OBJECT_AFTER_COMMA":
case "INSIDE_OBJECT_START":
case "INSIDE_OBJECT_BEFORE_VALUE":
case "INSIDE_OBJECT_AFTER_VALUE":
result += "}";
break;
case "INSIDE_ARRAY_START":
case "INSIDE_ARRAY_AFTER_COMMA":
case "INSIDE_ARRAY_AFTER_VALUE":
result += "]";
break;
case "INSIDE_LITERAL": {
const partialLiteral = input.substring(literalStart, input.length);
if ("true".startsWith(partialLiteral)) result += "true".slice(partialLiteral.length);
else if ("false".startsWith(partialLiteral)) result += "false".slice(partialLiteral.length);
else if ("null".startsWith(partialLiteral)) result += "null".slice(partialLiteral.length);
}
}
return result;
}
async function parsePartialJson(jsonText) {
if (jsonText === void 0) return {
value: void 0,
state: "undefined-input"
};
let result = await safeParseJSON({ text: jsonText });
if (result.success) return {
value: result.value,
state: "successful-parse"
};
result = await safeParseJSON({ text: fixJson(jsonText) });
if (result.success) return {
value: result.value,
state: "repaired-parse"
};
return {
value: void 0,
state: "failed-parse"
};
}
function isDataUIPart(part) {
return part.type.startsWith("data-");
}
function isTextUIPart(part) {
return part.type === "text";
}
function isFileUIPart(part) {
return part.type === "file";
}
function isReasoningUIPart(part) {
return part.type === "reasoning";
}
function isToolUIPart(part) {
return part.type.startsWith("tool-");
}
function isDynamicToolUIPart(part) {
return part.type === "dynamic-tool";
}
function isToolOrDynamicToolUIPart(part) {
return isToolUIPart(part) || isDynamicToolUIPart(part);
}
function getToolName(part) {
return part.type.split("-").slice(1).join("-");
}
function getToolOrDynamicToolName(part) {
return isDynamicToolUIPart(part) ? part.toolName : getToolName(part);
}
createIdGenerator({
prefix: "aitxt",
size: 24
});
function getOwn(obj, key) {
return obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0;
}
function isToolPartFromUnavailableTool(part) {
return part.type === "dynamic-tool" && part.dynamic === false;
}
function convertToModelMessages(messages, options) {
const modelMessages = [];
if (options == null ? void 0 : options.ignoreIncompleteToolCalls) messages = messages.map((message) => ({
...message,
parts: message.parts.filter((part) => !isToolOrDynamicToolUIPart(part) || part.state !== "input-streaming" && part.state !== "input-available" && (part.state !== "output-available" || part.preliminary !== true))
}));
function createModelOutput({ toolPart, toolName, output, errorMode }) {
const tool2 = getOwn(options == null ? void 0 : options.tools, toolName);
if (errorMode === "none" && tool2 == null && isToolPartFromUnavailableTool(toolPart)) return {
type: "text",
value: "Tool output omitted because the tool is no longer available."
};
return createToolModelOutput({
output,
tool: tool2,
errorMode
});
}
for (const message of messages) switch (message.role) {
case "system": {
const textParts = message.parts.filter((part) => part.type === "text");
const providerMetadata = textParts.reduce((acc, part) => {
if (part.providerMetadata != null) return {
...acc,
...part.providerMetadata
};
return acc;
}, {});
modelMessages.push({
role: "system",
content: textParts.map((part) => part.text).join(""),
...Object.keys(providerMetadata).length > 0 ? { providerOptions: providerMetadata } : {}
});
break;
}
case "user":
modelMessages.push({
role: "user",
content: message.parts.map((part) => {
var _a17;
if (isTextUIPart(part)) return {
type: "text",
text: part.text,
...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}
};
if (isFileUIPart(part)) return {
type: "file",
mediaType: part.mediaType,
filename: part.filename,
data: part.url,
...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}
};
if (isDataUIPart(part)) return (_a17 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a17.call(options, part);
}).filter((part) => part != null)
});
break;
case "assistant":
if (message.parts != null) {
let processBlock2 = function() {
var _a17, _b;
if (block.length === 0) return;
const content = [];
for (const part of block) if (isTextUIPart(part)) content.push({
type: "text",
text: part.text,
...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}
});
else if (isFileUIPart(part)) content.push({
type: "file",
mediaType: part.mediaType,
filename: part.filename,
data: part.url
});
else if (isReasoningUIPart(part)) content.push({
type: "reasoning",
text: part.text,
providerOptions: part.providerMetadata
});
else if (isDynamicToolUIPart(part)) {
const toolName = part.toolName;
if (part.state !== "input-streaming") content.push({
type: "tool-call",
toolCallId: part.toolCallId,
toolName,
input: part.input,
...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}
});
} else if (isToolUIPart(part)) {
const toolName = getToolName(part);
if (part.state !== "input-streaming") {
content.push({
type: "tool-call",
toolCallId: part.toolCallId,
toolName,
input: part.state === "output-error" ? (_a17 = part.input) != null ? _a17 : part.rawInput : part.input,
providerExecuted: part.providerExecuted,
...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}
});
if (part.providerExecuted === true && (part.state === "output-available" || part.state === "output-error")) content.push({
type: "tool-result",
toolCallId: part.toolCallId,
toolName,
output: createModelOutput({
toolPart: part,
toolName,
output: part.state === "output-error" ? part.errorText : part.output,
errorMode: part.state === "output-error" ? "json" : "none"
}),
...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}
});
}
} else if (isDataUIPart(part)) {
const dataPart = (_b = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _b.call(options, part);
if (dataPart != null) content.push(dataPart);
} else throw new Error(`Unsupported part: ${part}`);
modelMessages.push({
role: "assistant",
content
});
const toolParts = block.filter((part) => isToolUIPart(part) && part.providerExecuted !== true || part.type === "dynamic-tool");
if (toolParts.length > 0) modelMessages.push({
role: "tool",
content: toolParts.map((toolPart) => {
switch (toolPart.state) {
case "output-error":
case "output-available": {
const toolName = getToolOrDynamicToolName(toolPart);
return {
type: "tool-result",
toolCallId: toolPart.toolCallId,
toolName,
output: createModelOutput({
toolPart,
toolName,
output: toolPart.state === "output-error" ? toolPart.errorText : toolPart.output,
errorMode: toolPart.state === "output-error" ? "text" : "none"
}),
...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}
};
}
default: return null;
}
}).filter((output) => output != null)
});
block = [];
};
let block = [];
for (const part of message.parts) if (isTextUIPart(part) || isReasoningUIPart(part) || isFileUIPart(part) || isToolOrDynamicToolUIPart(part) || isDataUIPart(part)) block.push(part);
else if (part.type === "step-start") processBlock2();
processBlock2();
break;
}
break;
default: {
const _exhaustiveCheck = message.role;
throw new MessageConversionError({
originalMessage: message,
message: `Unsupported role: ${_exhaustiveCheck}`
});
}
}
return modelMessages;
}
async function embed({ model: modelArg, value, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry }) {
const model = resolveEmbeddingModel(modelArg);
const { maxRetries, retry } = prepareRetries({
maxRetries: maxRetriesArg,
abortSignal
});
const headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);
const baseTelemetryAttributes = getBaseTelemetryAttributes({
model,
telemetry,
headers: headersWithUserAgent,
settings: { maxRetries }
});
const tracer = getTracer(telemetry);
return recordSpan({
name: "ai.embed",
attributes: selectTelemetryAttributes({
telemetry,
attributes: {
...assembleOperationName({
operationId: "ai.embed",
telemetry
}),
...baseTelemetryAttributes,
"ai.value": { input: () => JSON.stringify(value) }
}
}),
tracer,
fn: async (span) => {
const { embedding, usage, response, providerMetadata } = await retry(() => recordSpan({
name: "ai.embed.doEmbed",
attributes: selectTelemetryAttributes({
telemetry,
attributes: {
...assembleOperationName({
operationId: "ai.embed.doEmbed",
telemetry
}),
...baseTelemetryAttributes,
"ai.values": { input: () => [JSON.stringify(value)] }
}
}),
tracer,
fn: async (doEmbedSpan) => {
var _a17;
const modelResponse = await model.doEmbed({
values: [value],
abortSignal,
headers: headersWithUserAgent,
providerOptions
});
const embedding2 = modelResponse.embeddings[0];
const usage2 = (_a17 = modelResponse.usage) != null ? _a17 : { tokens: NaN };
doEmbedSpan.setAttributes(selectTelemetryAttributes({
telemetry,
attributes: {
"ai.embeddings": { output: () => modelResponse.embeddings.map((embedding3) => JSON.stringify(embedding3)) },
"ai.usage.tokens": usage2.tokens
}
}));
if (embedding2 == null) throw new InvalidResponseDataError({
data: modelResponse.embeddings,
message: "No embedding generated."
});
return {
embedding: embedding2,
usage: usage2,
providerMetadata: modelResponse.providerMetadata,
response: modelResponse.response
};
}
}));
span.setAttributes(selectTelemetryAttributes({
telemetry,
attributes: {
"ai.embedding": { output: () => JSON.stringify(embedding) },
"ai.usage.tokens": usage.tokens
}
}));
return new DefaultEmbedResult({
value,
embedding,
usage,
providerMetadata,
response
});
}
});
}
var DefaultEmbedResult = class {
constructor(options) {
this.value = options.value;
this.embedding = options.embedding;
this.usage = options.usage;
this.providerMetadata = options.providerMetadata;
this.response = options.response;
}
};
new TextEncoder();
createIdGenerator({
prefix: "aiobj",
size: 24
});
function createDownload(options) {
return ({ url, abortSignal }) => download({
url,
maxBytes: options == null ? void 0 : options.maxBytes,
abortSignal
});
}
var { atob } = globalThis;
function isDeepEqualData(obj1, obj2) {
if (obj1 === obj2) return true;
if (obj1 == null || obj2 == null) return false;
if (typeof obj1 !== "object" && typeof obj2 !== "object") return obj1 === obj2;
if (obj1.constructor !== obj2.constructor) return false;
if (obj1 instanceof Date && obj2 instanceof Date) return obj1.getTime() === obj2.getTime();
if (Array.isArray(obj1)) {
if (obj1.length !== obj2.length) return false;
for (let i = 0; i < obj1.length; i++) if (!isDeepEqualData(obj1[i], obj2[i])) return false;
return true;
}
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
for (const key of keys1) {
if (!keys2.includes(key)) return false;
if (!isDeepEqualData(obj1[key], obj2[key])) return false;
}
return true;
}
createIdGenerator({
prefix: "aiobj",
size: 24
});
var DefaultGeneratedAudioFile = class extends DefaultGeneratedFile {
constructor({ data, mediaType }) {
super({
data,
mediaType
});
let format = "mp3";
if (mediaType) {
const mediaTypeParts = mediaType.split("/");
if (mediaTypeParts.length === 2) {
if (mediaType !== "audio/mpeg") format = mediaTypeParts[1];
}
}
if (!format) throw new Error("Audio format must be provided or determinable from media type");
this.format = format;
}
};
async function generateSpeech({ model, text: text2, voice, outputFormat, instructions, speed, language, providerOptions = {}, maxRetries: maxRetriesArg, abortSignal, headers }) {
var _a17;
if (model.specificationVersion !== "v2") throw new UnsupportedModelVersionError({
version: model.specificationVersion,
provider: model.provider,
modelId: model.modelId
});
const headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);
const { retry } = prepareRetries({
maxRetries: maxRetriesArg,
abortSignal
});
const result = await retry(() => model.doGenerate({
text: text2,
voice,
outputFormat,
instructions,
speed,
language,
abortSignal,
headers: headersWithUserAgent,
providerOptions
}));
if (!result.audio || result.audio.length === 0) throw new NoSpeechGeneratedError({ responses: [result.response] });
logWarnings(result.warnings);
return new DefaultSpeechResult({
audio: new DefaultGeneratedAudioFile({
data: result.audio,
mediaType: (_a17 = detectMediaType({
data: result.audio,
signatures: audioMediaTypeSignatures
})) != null ? _a17 : "audio/mp3"
}),
warnings: result.warnings,
responses: [result.response],
providerMetadata: result.providerMetadata
});
}
var DefaultSpeechResult = class {
constructor(options) {
var _a17;
this.audio = options.audio;
this.warnings = options.warnings;
this.responses = options.responses;
this.providerMetadata = (_a17 = options.providerMetadata) != null ? _a17 : {};
}
};
__export({}, {
object: () => object$1,
text: () => text
});
var text = () => ({
type: "text",
responseFormat: { type: "text" },
async parsePartial({ text: text2 }) {
return { partial: text2 };
},
async parseOutput({ text: text2 }) {
return text2;
}
});
var object$1 = ({ schema: inputSchema }) => {
const schema = asSchema(inputSchema);
return {
type: "object",
responseFormat: {
type: "json",
schema: schema.jsonSchema
},
async parsePartial({ text: text2 }) {
const result = await parsePartialJson(text2);
switch (result.state) {
case "failed-parse":
case "undefined-input": return;
case "repaired-parse":
case "successful-parse": return { partial: result.value };
default: {
const _exhaustiveCheck = result.state;
throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
}
}
},
async parseOutput({ text: text2 }, context) {
const parseResult = await safeParseJSON({ text: text2 });
if (!parseResult.success) throw new NoObjectGeneratedError({
message: "No object generated: could not parse the response.",
cause: parseResult.error,
text: text2,
response: context.response,
usage: context.usage,
finishReason: context.finishReason
});
const validationResult = await safeValidateTypes({
value: parseResult.value,
schema
});
if (!validationResult.success) throw new NoObjectGeneratedError({
message: "No object generated: response did not match schema.",
cause: validationResult.error,
text: text2,
response: context.response,
usage: context.usage,
finishReason: context.finishReason
});
return validationResult.value;
}
};
};
var NoTranscriptGeneratedError = class extends AISDKError {
constructor(options) {
super({
name: "AI_NoTranscriptGeneratedError",
message: "No transcript generated."
});
this.responses = options.responses;
}
};
var defaultDownload = createDownload();
async function transcribe({ model, audio, providerOptions = {}, maxRetries: maxRetriesArg, abortSignal, headers, download: downloadFn = defaultDownload }) {
if (model.specificationVersion !== "v2") throw new UnsupportedModelVersionError({
version: model.specificationVersion,
provider: model.provider,
modelId: model.modelId
});
const { retry } = prepareRetries({
maxRetries: maxRetriesArg,
abortSignal
});
const headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);
const audioData = audio instanceof URL ? (await downloadFn({
url: audio,
abortSignal
})).data : convertDataContentToUint8Array(audio);
const result = await retry(() => {
var _a17;
return model.doGenerate({
audio: audioData,
abortSignal,
headers: headersWithUserAgent,
providerOptions,
mediaType: (_a17 = detectMediaType({
data: audioData,
signatures: audioMediaTypeSignatures
})) != null ? _a17 : "audio/wav"
});
});
logWarnings(result.warnings);
if (!result.text) throw new NoTranscriptGeneratedError({ responses: [result.response] });
return new DefaultTranscriptionResult({
text: result.text,
segments: result.segments,
language: result.language,
durationInSeconds: result.durationInSeconds,
warnings: result.warnings,
responses: [result.response],
providerMetadata: result.providerMetadata
});
}
var DefaultTranscriptionResult = class {
constructor(options) {
var _a17;
this.text = options.text;
this.segments = options.segments;
this.language = options.language;
this.durationInSeconds = options.durationInSeconds;
this.warnings = options.warnings;
this.responses = options.responses;
this.providerMetadata = (_a17 = options.providerMetadata) != null ? _a17 : {};
}
};
export { getToolName as a, parsePartialJson as c, JSONParseError as d, TypeValidationError as f, tool as h, generateSpeech as i, transcribe as l, generateId as m, convertToModelMessages as n, isDeepEqualData as o, asSchema as p, embed as r, isToolUIPart as s, NoObjectGeneratedError as t, APICallError as u };
//# sourceMappingURL=dist-TPVqg8oV.js.map