@mastra/core
Version:
Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.
1,614 lines (1,613 loc) • 398 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_v6/dist/chunk-AYUI5GCM.js
var marker = "vercel.ai.error";
var symbol = Symbol.for(marker);
var _a;
var _b;
var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) {
/**
* 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: name1422,
message,
cause
}) {
super(message);
this[_a] = true;
this.name = name1422;
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);
}
static hasMarker(error, marker1522) {
const markerSymbol = Symbol.for(marker1522);
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
}
};
var name = "AI_APICallError";
var marker2 = `vercel.ai.error.${name}`;
var symbol2 = Symbol.for(marker2);
var _a2;
var _b2;
var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {
constructor({
message,
url,
requestBodyValues,
statusCode,
responseHeaders,
responseBody,
cause,
isRetryable = statusCode != null && (statusCode === 408 || // request timeout
statusCode === 409 || // conflict
statusCode === 429 || // too many requests
statusCode >= 500),
// server error
data
}) {
super({ name, message, cause });
this[_a2] = 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);
}
};
var name2 = "AI_EmptyResponseBodyError";
var marker3 = `vercel.ai.error.${name2}`;
var symbol3 = Symbol.for(marker3);
var _a3;
var _b3;
var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {
// used in isInstance
constructor({ message = "Empty response body" } = {}) {
super({ name: name2, message });
this[_a3] = true;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker3);
}
};
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);
}
var name3 = "AI_InvalidArgumentError";
var marker4 = `vercel.ai.error.${name3}`;
var symbol4 = Symbol.for(marker4);
var _a4;
var _b4;
var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {
constructor({
message,
cause,
argument
}) {
super({ name: name3, message, cause });
this[_a4] = true;
this.argument = argument;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker4);
}
};
var name4 = "AI_InvalidPromptError";
var marker5 = `vercel.ai.error.${name4}`;
var symbol5 = Symbol.for(marker5);
var _a5;
var _b5;
var InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {
constructor({
prompt,
message,
cause
}) {
super({ name: name4, message: `Invalid prompt: ${message}`, cause });
this[_a5] = true;
this.prompt = prompt;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker5);
}
};
var name6 = "AI_JSONParseError";
var marker7 = `vercel.ai.error.${name6}`;
var symbol7 = Symbol.for(marker7);
var _a7;
var _b7;
var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {
constructor({ text: text2, cause }) {
super({
name: name6,
message: `JSON parsing failed: Text: ${text2}.
Error message: ${getErrorMessage(cause)}`,
cause
});
this[_a7] = true;
this.text = text2;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker7);
}
};
var name12 = "AI_TypeValidationError";
var marker13 = `vercel.ai.error.${name12}`;
var symbol13 = Symbol.for(marker13);
var _a13;
var _b13;
var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {
constructor({
value,
cause,
context: context2
}) {
let contextPrefix = "Type validation failed";
if (context2 == null ? void 0 : context2.field) {
contextPrefix += ` for ${context2.field}`;
}
if ((context2 == null ? void 0 : context2.entityName) || (context2 == null ? void 0 : context2.entityId)) {
contextPrefix += " (";
const parts = [];
if (context2.entityName) {
parts.push(context2.entityName);
}
if (context2.entityId) {
parts.push(`id: "${context2.entityId}"`);
}
contextPrefix += parts.join(", ");
contextPrefix += ")";
}
super({
name: name12,
message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
Error message: ${getErrorMessage(cause)}`,
cause
});
this[_a13] = true;
this.value = value;
this.context = context2;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker13);
}
/**
* Wraps an error into a TypeValidationError.
* If the cause is already a TypeValidationError with the same value and context, it returns the cause.
* Otherwise, it creates a new TypeValidationError.
*
* @param {Object} params - The parameters for wrapping the error.
* @param {unknown} params.value - The value that failed validation.
* @param {unknown} params.cause - The original error or cause of the validation failure.
* @param {TypeValidationContext} params.context - Optional context about what is being validated.
* @returns {TypeValidationError} A TypeValidationError instance.
*/
static wrap({
value,
cause,
context: context2
}) {
var _a1522, _b152, _c;
if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a1522 = cause.context) == null ? void 0 : _a1522.field) === (context2 == null ? void 0 : context2.field) && ((_b152 = cause.context) == null ? void 0 : _b152.entityName) === (context2 == null ? void 0 : context2.entityName) && ((_c = cause.context) == null ? void 0 : _c.entityId) === (context2 == null ? void 0 : context2.entityId)) {
return cause;
}
return new _TypeValidationError({ value, cause, context: context2 });
}
};
var name13 = "AI_UnsupportedFunctionalityError";
var marker14 = `vercel.ai.error.${name13}`;
var symbol14 = Symbol.for(marker14);
var _a14;
var _b14;
var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {
constructor({
functionality,
message = `'${functionality}' functionality not supported.`
}) {
super({ name: name13, message });
this[_a14] = true;
this.functionality = functionality;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker14);
}
};
var ParseError = class extends Error {
constructor(message, options) {
super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
}
};
var LF = 10;
var CR = 13;
var SPACE = 32;
function noop(_arg) {
}
function createParser(callbacks) {
if (typeof callbacks == "function")
throw new TypeError(
"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
);
const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];
let isFirstChunk = true, id, data = "", dataLines = 0, eventType;
function feed(chunk) {
if (isFirstChunk && (isFirstChunk = false, 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);
return;
}
if (chunk.indexOf(`
`) === -1 && chunk.indexOf("\r") === -1) {
pendingFragments.push(chunk);
return;
}
pendingFragments.push(chunk);
const input = pendingFragments.join("");
pendingFragments.length = 0;
const trailing = processLines(input);
trailing !== "" && pendingFragments.push(trailing);
}
function processLines(chunk) {
let searchIndex = 0;
if (chunk.indexOf("\r") === -1) {
let lfIndex = chunk.indexOf(`
`, searchIndex);
for (; lfIndex !== -1; ) {
if (searchIndex === lfIndex) {
dataLines > 0 && onEvent({ id, event: eventType, data }), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
`, searchIndex);
continue;
}
const firstCharCode = chunk.charCodeAt(searchIndex);
if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
onEvent({ id, event: eventType, data: value }), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
`, searchIndex);
continue;
}
data = dataLines === 0 ? value : `${data}
${value}`, dataLines++;
} else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(
chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,
lfIndex
) || void 0 : parseLine(chunk, searchIndex, lfIndex);
searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
`, searchIndex);
}
return chunk.slice(searchIndex);
}
for (; searchIndex < chunk.length; ) {
const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
`, searchIndex);
let lineEnd = -1;
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1)
break;
parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
}
return chunk.slice(searchIndex);
}
function parseLine(chunk, start, end) {
if (start === end) {
dispatchEvent();
return;
}
const firstCharCode = chunk.charCodeAt(start);
if (isDataPrefix(chunk, start, firstCharCode)) {
const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
data = dataLines === 0 ? value2 : `${data}
${value2}`, dataLines++;
return;
}
if (isEventPrefix(chunk, start, firstCharCode)) {
eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
return;
}
if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
id = value2.includes("\0") ? void 0 : value2;
return;
}
if (firstCharCode === 58) {
if (onComment) {
const line2 = chunk.slice(start, end);
onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
}
return;
}
const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
if (fieldSeparatorIndex === -1) {
processField(line, "", line);
return;
}
const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
processField(field, value, line);
}
function processField(field, value, line) {
switch (field) {
case "event":
eventType = value || void 0;
break;
case "data":
data = dataLines === 0 ? value : `${data}
${value}`, dataLines++;
break;
case "id":
id = value.includes("\0") ? void 0 : value;
break;
case "retry":
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
new ParseError(`Invalid \`retry\` value: "${value}"`, {
type: "invalid-retry",
value,
line
})
);
break;
default:
onError(
new ParseError(
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
{ type: "unknown-field", field, value, line }
)
);
break;
}
}
function dispatchEvent() {
dataLines > 0 && onEvent({
id,
event: eventType,
data
}), id = void 0, data = "", dataLines = 0, eventType = void 0;
}
function reset(options = {}) {
if (options.consume && pendingFragments.length > 0) {
const incompleteLine = pendingFragments.join("");
parseLine(incompleteLine, 0, incompleteLine.length);
}
isFirstChunk = true, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0;
}
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 } = {}) {
let parser;
super({
start(controller) {
parser = createParser({
onEvent: (event) => {
controller.enqueue(event);
},
onError(error) {
onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
},
onRetry,
onComment
});
},
transform(chunk) {
parser.feed(chunk);
}
});
}
};
function combineHeaders(...headers) {
return headers.reduce(
(combinedHeaders, currentHeaders) => ({
...combinedHeaders,
...currentHeaders != null ? 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 == null ? void 0 : signal.removeEventListener("abort", onAbort);
};
const onAbort = () => {
cleanup();
reject(createAbortError());
};
signal == null ? void 0 : signal.addEventListener("abort", onAbort);
});
}
function createAbortError() {
return new DOMException("Delay was aborted", "AbortError");
}
var DelayedPromise = class {
constructor() {
this.status = { type: "pending" };
this._resolve = void 0;
this._reject = void 0;
}
get promise() {
if (this._promise) {
return this._promise;
}
this._promise = new Promise((resolve2, reject) => {
if (this.status.type === "resolved") {
resolve2(this.status.value);
} else if (this.status.type === "rejected") {
reject(this.status.error);
}
this._resolve = resolve2;
this._reject = reject;
});
return this._promise;
}
resolve(value) {
var _a223;
this.status = { type: "resolved", value };
if (this._promise) {
(_a223 = this._resolve) == null ? void 0 : _a223.call(this, value);
}
}
reject(error) {
var _a223;
this.status = { type: "rejected", error };
if (this._promise) {
(_a223 = this._reject) == null ? void 0 : _a223.call(this, error);
}
}
isResolved() {
return this.status.type === "resolved";
}
isRejected() {
return this.status.type === "rejected";
}
isPending() {
return this.status.type === "pending";
}
};
function extractResponseHeaders(response) {
return Object.fromEntries([...response.headers]);
}
var { btoa, atob } = globalThis;
function convertBase64ToUint8Array(base64String) {
const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
const latin1string = atob(base64Url);
return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
}
function convertUint8ArrayToBase64(array2) {
let latin1string = "";
for (let i = 0; i < array2.length; i++) {
latin1string += String.fromCodePoint(array2[i]);
}
return btoa(latin1string);
}
var name14 = "AI_DownloadError";
var marker15 = `vercel.ai.error.${name14}`;
var symbol15 = Symbol.for(marker15);
var _a15;
var _b15;
var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) {
constructor({
url,
statusCode,
statusText,
cause,
message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
}) {
super({ name: name14, message, cause });
this[_a15] = true;
this.url = url;
this.statusCode = statusCode;
this.statusText = statusText;
}
static isInstance(error) {
return AISDKError.hasMarker(error, marker15);
}
};
var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
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) {
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 new Uint8Array(0);
}
const reader = body.getReader();
const chunks = [];
let totalBytes = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
totalBytes += value.length;
if (totalBytes > maxBytes) {
throw new DownloadError({
url,
message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`
});
}
chunks.push(value);
}
} finally {
try {
await reader.cancel();
} finally {
reader.releaseLock();
}
}
const result = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
function 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;
if (!hostname) {
throw new DownloadError({
url,
message: `URL must have a hostname`
});
}
if (hostname === "localhost" || hostname.endsWith(".local") || hostname.endsWith(".localhost")) {
throw new DownloadError({
url,
message: `URL with hostname ${hostname} is not allowed`
});
}
if (hostname.startsWith("[") && hostname.endsWith("]")) {
const ipv6 = hostname.slice(1, -1);
if (isPrivateIPv6(ipv6)) {
throw new DownloadError({
url,
message: `URL with IPv6 address ${hostname} is not allowed`
});
}
return;
}
if (isIPv4(hostname)) {
if (isPrivateIPv4(hostname)) {
throw new DownloadError({
url,
message: `URL with IP address ${hostname} is not allowed`
});
}
return;
}
}
function isIPv4(hostname) {
const parts = hostname.split(".");
if (parts.length !== 4) return false;
return parts.every((part) => {
const num = Number(part);
return Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;
});
}
function isPrivateIPv4(ip) {
const parts = ip.split(".").map(Number);
const [a, b] = parts;
if (a === 0) return true;
if (a === 10) 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 === 168) return true;
return false;
}
function isPrivateIPv6(ip) {
const normalized = ip.toLowerCase();
if (normalized === "::1") return true;
if (normalized === "::") return true;
if (normalized.startsWith("::ffff:")) {
const mappedPart = normalized.slice(7);
if (isIPv4(mappedPart)) {
return isPrivateIPv4(mappedPart);
}
const hexParts = mappedPart.split(":");
if (hexParts.length === 2) {
const high = parseInt(hexParts[0], 16);
const low = parseInt(hexParts[1], 16);
if (!isNaN(high) && !isNaN(low)) {
const a = high >> 8 & 255;
const b = high & 255;
const c = low >> 8 & 255;
const d = low & 255;
return isPrivateIPv4(`${a}.${b}.${c}.${d}`);
}
}
}
if (normalized.startsWith("fc") || normalized.startsWith("fd")) return true;
if (normalized.startsWith("fe80")) return true;
return false;
}
var createIdGenerator = ({
prefix,
size = 16,
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
separator = "-"
} = {}) => {
const generator = () => {
const alphabetLength = alphabet.length;
const chars = new Array(size);
for (let i = 0; i < size; i++) {
chars[i] = alphabet[Math.random() * alphabetLength | 0];
}
return chars.join("");
};
if (prefix == null) {
return generator;
}
if (alphabet.includes(separator)) {
throw new InvalidArgumentError({
argument: "separator",
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
});
}
return () => `${prefix}${separator}${generator()}`;
};
createIdGenerator();
function getErrorMessage2(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" || // Next.js
error.name === "TimeoutError");
}
var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"];
var BUN_ERROR_CODES = [
"ConnectionRefused",
"ConnectionClosed",
"FailedToOpenSocket",
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"EPIPE"
];
function isBunNetworkError(error) {
if (!(error instanceof Error)) {
return false;
}
const code = error.code;
if (typeof code === "string" && BUN_ERROR_CODES.includes(code)) {
return true;
}
return false;
}
function handleFetchError({
error,
url,
requestBodyValues
}) {
if (isAbortError(error)) {
return error;
}
if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {
const cause = error.cause;
if (cause != null) {
return new APICallError({
message: `Cannot connect to API: ${cause.message}`,
cause,
url,
requestBodyValues,
isRetryable: true
// retry when network error
});
}
}
if (isBunNetworkError(error)) {
return new APICallError({
message: `Cannot connect to API: ${error.message}`,
cause: error,
url,
requestBodyValues,
isRetryable: true
});
}
return error;
}
function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {
var _a223, _b222, _c;
if (globalThisAny.window) {
return `runtime/browser`;
}
if ((_a223 = globalThisAny.navigator) == null ? void 0 : _a223.userAgent) {
return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;
}
if ((_c = (_b222 = globalThisAny.process) == null ? void 0 : _b222.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 = "4.0.27";
var getOriginalFetch = () => globalThis.fetch;
var getFromApi = async ({
url,
headers = {},
successfulResponseHandler,
failedResponseHandler,
abortSignal,
fetch: fetch2 = getOriginalFetch()
}) => {
try {
const response = await fetch2(url, {
method: "GET",
headers: withUserAgentSuffix(
headers,
`ai-sdk/provider-utils/${VERSION}`,
getRuntimeEnvironmentUserAgent()
),
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (isAbortError(error) || APICallError.isInstance(error)) {
throw error;
}
throw new APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || APICallError.isInstance(error)) {
throw error;
}
}
throw new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
} catch (error) {
throw handleFetchError({ error, url, requestBodyValues: {} });
}
};
function isUrlSupported({
mediaType,
url,
supportedUrls
}) {
url = url.toLowerCase();
mediaType = mediaType.toLowerCase();
return Object.entries(supportedUrls).map(([key, value]) => {
const mediaType2 = key.toLowerCase();
return mediaType2 === "*" || mediaType2 === "*/*" ? { mediaTypePrefix: "", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\*/, ""), regexes: value };
}).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));
}
function loadOptionalSetting({
settingValue,
environmentVariableName
}) {
if (typeof settingValue === "string") {
return settingValue;
}
if (settingValue != null || typeof process === "undefined") {
return void 0;
}
settingValue = process.env[environmentVariableName];
if (settingValue == null || typeof settingValue !== "string") {
return void 0;
}
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(text2) {
const obj = JSON.parse(text2);
if (obj === null || typeof obj !== "object") {
return obj;
}
if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === 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(text2) {
const { stackTraceLimit } = Error;
try {
Error.stackTraceLimit = 0;
} catch (e) {
return _parse(text2);
}
try {
return _parse(text2);
} finally {
Error.stackTraceLimit = stackTraceLimit;
}
}
function addAdditionalPropertiesToJsonSchema(jsonSchema2) {
if (jsonSchema2.type === "object" || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) {
jsonSchema2.additionalProperties = false;
const { properties } = jsonSchema2;
if (properties != null) {
for (const key of Object.keys(properties)) {
properties[key] = visit(properties[key]);
}
}
}
if (jsonSchema2.items != null) {
jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items);
}
if (jsonSchema2.anyOf != null) {
jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit);
}
if (jsonSchema2.allOf != null) {
jsonSchema2.allOf = jsonSchema2.allOf.map(visit);
}
if (jsonSchema2.oneOf != null) {
jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit);
}
const { definitions } = jsonSchema2;
if (definitions != null) {
for (const key of Object.keys(definitions)) {
definitions[key] = visit(definitions[key]);
}
}
return jsonSchema2;
}
function visit(def) {
if (typeof def === "boolean") return def;
return addAdditionalPropertiesToJsonSchema(def);
}
var ignoreOverride = /* @__PURE__ */ Symbol(
"Let zodToJsonSchema decide on which parser to use"
);
var defaultOptions = {
name: void 0,
$refStrategy: "root",
basePath: ["#"],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: true,
rejectedAdditionalProperties: false,
definitionPath: "definitions",
strictUnions: false,
definitions: {},
errorMessages: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref"
};
var getDefaultOptions = (options) => typeof options === "string" ? {
...defaultOptions,
name: options
} : {
...defaultOptions,
...options
};
function parseAnyDef() {
return {};
}
function parseArrayDef(def, refs) {
var _a223, _b222, _c;
const res = {
type: "array"
};
if (((_a223 = def.type) == null ? void 0 : _a223._def) && ((_c = (_b222 = def.type) == null ? void 0 : _b222._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
res.items = parseDef(def.type._def, {
...refs,
currentPath: [...refs.currentPath, "items"]
});
}
if (def.minLength) {
res.minItems = def.minLength.value;
}
if (def.maxLength) {
res.maxItems = def.maxLength.value;
}
if (def.exactLength) {
res.minItems = def.exactLength.value;
res.maxItems = def.exactLength.value;
}
return res;
}
function parseBigintDef(def) {
const res = {
type: "integer",
format: "int64"
};
if (!def.checks) return res;
for (const check of def.checks) {
switch (check.kind) {
case "min":
if (check.inclusive) {
res.minimum = check.value;
} else {
res.exclusiveMinimum = check.value;
}
break;
case "max":
if (check.inclusive) {
res.maximum = check.value;
} else {
res.exclusiveMaximum = check.value;
}
break;
case "multipleOf":
res.multipleOf = check.value;
break;
}
}
return res;
}
function parseBooleanDef() {
return { type: "boolean" };
}
function parseBrandedDef(_def, refs) {
return parseDef(_def.type._def, refs);
}
var parseCatchDef = (def, refs) => {
return parseDef(def.innerType._def, refs);
};
function parseDateDef(def, refs, overrideDateStrategy) {
const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
if (Array.isArray(strategy)) {
return {
anyOf: strategy.map((item, 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;
break;
}
}
return res;
};
function parseDefaultDef(_def, refs) {
return {
...parseDef(_def.innerType._def, refs),
default: _def.defaultValue()
};
}
function parseEffectsDef(_def, refs) {
return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
}
function parseEnumDef(def) {
return {
type: "string",
enum: Array.from(def.values)
};
}
var isJsonSchema7AllOfType = (type) => {
if ("type" in type && type.type === "string") return false;
return "allOf" in type;
};
function parseIntersectionDef(def, refs) {
const allOf = [
parseDef(def.left._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", "0"]
}),
parseDef(def.right._def, {
...refs,
currentPath: [...refs.currentPath, "allOf", "1"]
})
].filter((x) => !!x);
const mergedAllOf = [];
allOf.forEach((schema) => {
if (isJsonSchema7AllOfType(schema)) {
mergedAllOf.push(...schema.allOf);
} else {
let nestedSchema = schema;
if ("additionalProperties" in schema && schema.additionalProperties === false) {
const { additionalProperties, ...rest } = schema;
nestedSchema = rest;
}
mergedAllOf.push(nestedSchema);
}
});
return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
}
function parseLiteralDef(def) {
const parsedType = typeof def.value;
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
return {
type: Array.isArray(def.value) ? "array" : "object"
};
}
return {
type: parsedType === "bigint" ? "integer" : parsedType,
const: def.value
};
}
var emojiRegex = void 0;
var zodPatterns = {
/**
* `c` was changed to `[cC]` to replicate /i flag
*/
cuid: /^[cC][^\s-]{8,}$/,
cuid2: /^[0-9a-z]+$/,
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
/**
* `a-z` was added to replicate /i flag
*/
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
/**
* Constructed a valid Unicode RegExp
*
* Lazily instantiate since this type of regex isn't supported
* in all envs (e.g. React Native).
*
* See:
* https://github.com/colinhacks/zod/issues/2433
* Fix in Zod:
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
*/
emoji: () => {
if (emojiRegex === void 0) {
emojiRegex = RegExp(
"^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
"u"
);
}
return emojiRegex;
},
/**
* Unused
*/
uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
/**
* Unused
*/
ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
/**
* Unused
*/
ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
nanoid: /^[a-zA-Z0-9_-]{21}$/,
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
};
function parseStringDef(def, refs) {
const res = {
type: "string"
};
if (def.checks) {
for (const check of def.checks) {
switch (check.kind) {
case "min":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
break;
case "max":
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
break;
case "email":
switch (refs.emailStrategy) {
case "format:email":
addFormat(res, "email", check.message, refs);
break;
case "format:idn-email":
addFormat(res, "idn-email", check.message, refs);
break;
case "pattern:zod":
addPattern(res, zodPatterns.email, check.message, refs);
break;
}
break;
case "url":
addFormat(res, "uri", check.message, refs);
break;
case "uuid":
addFormat(res, "uuid", check.message, refs);
break;
case "regex":
addPattern(res, check.regex, check.message, refs);
break;
case "cuid":
addPattern(res, zodPatterns.cuid, check.message, refs);
break;
case "cuid2":
addPattern(res, zodPatterns.cuid2, check.message, refs);
break;
case "startsWith":
addPattern(
res,
RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
check.message,
refs
);
break;
case "endsWith":
addPattern(
res,
RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
check.message,
refs
);
break;
case "datetime":
addFormat(res, "date-time", check.message, refs);
break;
case "date":
addFormat(res, "date", check.message, refs);
break;
case "time":
addFormat(res, "time", check.message, refs);
break;
case "duration":
addFormat(res, "duration", check.message, refs);
break;
case "length":
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
break;
case "includes": {
addPattern(
res,
RegExp(escapeLiteralCheckValue(check.value, refs)),
check.message,
refs
);
break;
}
case "ip": {
if (check.version !== "v6") {
addFormat(res, "ipv4", check.message, refs);
}
if (check.version !== "v4") {
addFormat(res, "ipv6", check.message, refs);
}
break;
}
case "base64url":
addPattern(res, zodPatterns.base64url, check.message, refs);
break;
case "jwt":
addPattern(res, zodPatterns.jwt, check.message, refs);
break;
case "cidr": {
if (check.version !== "v6") {
addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
}
if (check.version !== "v4") {
addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
}
break;
}
case "emoji":
addPattern(res, zodPatterns.emoji(), check.message, refs);
break;
case "ulid": {
addPattern(res, zodPatterns.ulid, check.message, refs);
break;
}
case "base64": {
switch (refs.base64Strategy) {
case "format:binary": {
addFormat(res, "binary", check.message, refs);
break;
}
case "contentEncoding:base64": {
res.contentEncoding = "base64";
break;
}
case "pattern:zod": {
addPattern(res, zodPatterns.base64, check.message, refs);
break;
}
}
break;
}
case "nanoid": {
addPattern(res, zodPatterns.nanoid, check.message, refs);
}
}
}
}
return res;
}
function escapeLiteralCheckValue(literal, refs) {
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
}
var ALPHA_NUMERIC = 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 _a223;
if (schema.format || ((_a223 = schema.anyOf) == null ? void 0 : _a223.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 _a223;
if (schema.pattern || ((_a223 = schema.allOf) == null ? void 0 : _a223.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 _a223;
if (!refs.applyRegexFlags || !regex.flags) {
return regex.source;
}
const flags = {
i: regex.flags.includes("i"),
// Case-insensitive
m: regex.flags.includes("m"),
// `^` and `$` matches adjacent to newline characters
s: regex.flags.includes("s")
// `.` matches newlines
};
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] === "-" && ((_a223 = source[i + 2]) == null ? void 0 : _a223.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;
}
}
return pattern;
}
function parseRecordDef(def, refs) {
var _a223, _b222, _c, _d, _e, _f;
const schema = {
type: "object",
additionalProperties: (_a223 = parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "additionalProperties"]
})) != null ? _a223 : refs.allowedAdditionalProperties
};
if (((_b222 = def.keyType) == null ? void 0 : _b222._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);
}
const keys = parseDef(def.keyType._def, {
...refs,
currentPath: [...refs.currentPath, "items", "items", "0"]
}) || parseAnyDef();
const values = parseDef(def.valueType._def, {
...refs,
currentPath: [...refs.currentPath, "items", "items", "1"]
}) || parseAnyDef();
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [keys, values],
minItems: 2,
maxItems: 2
}
};
}
function parseNativeEnumDef(def) {
const object2 = def.values;
const actualKeys = Object.keys(def.values).filter((key) => {
return typeof object2[object2[key]] !== "number";
});
const actualValues = actualKeys.map((key) => object2[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 instance