diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 424c0d8..11da51d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,7 +41,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: - node-version: 22 + node-version: 24 cache: 'pnpm' # Update npm to the latest version to enable OIDC diff --git a/action.yml b/action.yml index f4fc606..7adede6 100644 --- a/action.yml +++ b/action.yml @@ -20,6 +20,10 @@ inputs: required: false default: '' type: string + ai_model: + description: 'AI model to use for degradation analysis (e.g. claude-3-5-haiku-latest, gpt-4o-mini). Provider is auto-detected from the model name prefix.' + required: false + default: 'claude-3-5-haiku-latest' runs: using: 'node20' diff --git a/dist/682.js b/dist/682.js new file mode 100644 index 0000000..00fc0bb --- /dev/null +++ b/dist/682.js @@ -0,0 +1,424 @@ +"use strict"; +exports.ids = [ + "682" +]; +exports.modules = { + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/auth-config.js": function(module, __unused_webpack_exports, __webpack_require__) { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target)=>(target = null != mod ? __create(__getProtoOf(mod)) : {}, __copyProps(!isNodeMode && mod && mod.__esModule ? target : __defProp(target, "default", { + value: mod, + enumerable: true + }), mod)); + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var auth_config_exports = {}; + __export(auth_config_exports, { + isValidAccessToken: ()=>isValidAccessToken, + readAuthConfig: ()=>readAuthConfig, + writeAuthConfig: ()=>writeAuthConfig + }); + module.exports = __toCommonJS(auth_config_exports); + var fs = __toESM(__webpack_require__("fs")); + var path = __toESM(__webpack_require__("path")); + var import_token_util = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-util.js"); + function getAuthConfigPath() { + const dataDir = (0, import_token_util.getVercelDataDir)(); + if (!dataDir) throw new Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`); + return path.join(dataDir, "auth.json"); + } + function readAuthConfig() { + try { + const authPath = getAuthConfigPath(); + if (!fs.existsSync(authPath)) return null; + const content = fs.readFileSync(authPath, "utf8"); + if (!content) return null; + return JSON.parse(content); + } catch (error) { + return null; + } + } + function writeAuthConfig(config) { + const authPath = getAuthConfigPath(); + const authDir = path.dirname(authPath); + if (!fs.existsSync(authDir)) fs.mkdirSync(authDir, { + mode: 504, + recursive: true + }); + fs.writeFileSync(authPath, JSON.stringify(config, null, 2), { + mode: 384 + }); + } + function isValidAccessToken(authConfig) { + if (!authConfig.token) return false; + if ("number" != typeof authConfig.expiresAt) return true; + const nowInSeconds = Math.floor(Date.now() / 1e3); + return authConfig.expiresAt >= nowInSeconds; + } + }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/oauth.js": function(module, __unused_webpack_exports, __webpack_require__) { + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var oauth_exports = {}; + __export(oauth_exports, { + processTokenResponse: ()=>processTokenResponse, + refreshTokenRequest: ()=>refreshTokenRequest + }); + module.exports = __toCommonJS(oauth_exports); + var import_os = __webpack_require__("os"); + const VERCEL_ISSUER = "https://vercel.com"; + const VERCEL_CLI_CLIENT_ID = "cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp"; + const userAgent = `@vercel/oidc node-${process.version} ${(0, import_os.platform)()} (${(0, import_os.arch)()}) ${(0, import_os.hostname)()}`; + let _tokenEndpoint = null; + async function getTokenEndpoint() { + if (_tokenEndpoint) return _tokenEndpoint; + const discoveryUrl = `${VERCEL_ISSUER}/.well-known/openid-configuration`; + const response = await fetch(discoveryUrl, { + headers: { + "user-agent": userAgent + } + }); + if (!response.ok) throw new Error("Failed to discover OAuth endpoints"); + const metadata = await response.json(); + if (!metadata || "string" != typeof metadata.token_endpoint) throw new Error("Invalid OAuth discovery response"); + const endpoint = metadata.token_endpoint; + _tokenEndpoint = endpoint; + return endpoint; + } + async function refreshTokenRequest(options) { + const tokenEndpoint = await getTokenEndpoint(); + return await fetch(tokenEndpoint, { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + "user-agent": userAgent + }, + body: new URLSearchParams({ + client_id: VERCEL_CLI_CLIENT_ID, + grant_type: "refresh_token", + ...options + }) + }); + } + async function processTokenResponse(response) { + const json = await response.json(); + if (!response.ok) { + const errorMsg = "object" == typeof json && json && "error" in json ? String(json.error) : "Token refresh failed"; + return [ + new Error(errorMsg) + ]; + } + if ("object" != typeof json || null === json) return [ + new Error("Invalid token response") + ]; + if ("string" != typeof json.access_token) return [ + new Error("Missing access_token in response") + ]; + if ("Bearer" !== json.token_type) return [ + new Error("Invalid token_type in response") + ]; + if ("number" != typeof json.expires_in) return [ + new Error("Missing expires_in in response") + ]; + return [ + null, + json + ]; + } + }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-io.js": function(module, __unused_webpack_exports, __webpack_require__) { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target)=>(target = null != mod ? __create(__getProtoOf(mod)) : {}, __copyProps(!isNodeMode && mod && mod.__esModule ? target : __defProp(target, "default", { + value: mod, + enumerable: true + }), mod)); + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var token_io_exports = {}; + __export(token_io_exports, { + findRootDir: ()=>findRootDir, + getUserDataDir: ()=>getUserDataDir + }); + module.exports = __toCommonJS(token_io_exports); + var import_path = __toESM(__webpack_require__("path")); + var import_fs = __toESM(__webpack_require__("fs")); + var import_os = __toESM(__webpack_require__("os")); + var import_token_error = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-error.js"); + function findRootDir() { + try { + let dir = process.cwd(); + while(dir !== import_path.default.dirname(dir)){ + const pkgPath = import_path.default.join(dir, ".vercel"); + if (import_fs.default.existsSync(pkgPath)) return dir; + dir = import_path.default.dirname(dir); + } + } catch (e) { + throw new import_token_error.VercelOidcTokenError("Token refresh only supported in node server environments"); + } + return null; + } + function getUserDataDir() { + if (process.env.XDG_DATA_HOME) return process.env.XDG_DATA_HOME; + switch(import_os.default.platform()){ + case "darwin": + return import_path.default.join(import_os.default.homedir(), "Library/Application Support"); + case "linux": + return import_path.default.join(import_os.default.homedir(), ".local/share"); + case "win32": + if (process.env.LOCALAPPDATA) return process.env.LOCALAPPDATA; + return null; + default: + return null; + } + } + }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-util.js": function(module, __unused_webpack_exports, __webpack_require__) { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target)=>(target = null != mod ? __create(__getProtoOf(mod)) : {}, __copyProps(!isNodeMode && mod && mod.__esModule ? target : __defProp(target, "default", { + value: mod, + enumerable: true + }), mod)); + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var token_util_exports = {}; + __export(token_util_exports, { + assertVercelOidcTokenResponse: ()=>assertVercelOidcTokenResponse, + findProjectInfo: ()=>findProjectInfo, + getTokenPayload: ()=>getTokenPayload, + getVercelCliToken: ()=>getVercelCliToken, + getVercelDataDir: ()=>getVercelDataDir, + getVercelOidcToken: ()=>getVercelOidcToken, + isExpired: ()=>isExpired, + loadToken: ()=>loadToken, + saveToken: ()=>saveToken + }); + module.exports = __toCommonJS(token_util_exports); + var path = __toESM(__webpack_require__("path")); + var fs = __toESM(__webpack_require__("fs")); + var import_token_error = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-error.js"); + var import_token_io = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-io.js"); + var import_auth_config = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/auth-config.js"); + var import_oauth = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/oauth.js"); + function getVercelDataDir() { + const vercelFolder = "com.vercel.cli"; + const dataDir = (0, import_token_io.getUserDataDir)(); + if (!dataDir) return null; + return path.join(dataDir, vercelFolder); + } + async function getVercelCliToken() { + const authConfig = (0, import_auth_config.readAuthConfig)(); + if (!authConfig) return null; + if ((0, import_auth_config.isValidAccessToken)(authConfig)) return authConfig.token || null; + if (!authConfig.refreshToken) { + (0, import_auth_config.writeAuthConfig)({}); + return null; + } + try { + const tokenResponse = await (0, import_oauth.refreshTokenRequest)({ + refresh_token: authConfig.refreshToken + }); + const [tokensError, tokens] = await (0, import_oauth.processTokenResponse)(tokenResponse); + if (tokensError || !tokens) { + (0, import_auth_config.writeAuthConfig)({}); + return null; + } + const updatedConfig = { + token: tokens.access_token, + expiresAt: Math.floor(Date.now() / 1e3) + tokens.expires_in + }; + if (tokens.refresh_token) updatedConfig.refreshToken = tokens.refresh_token; + (0, import_auth_config.writeAuthConfig)(updatedConfig); + return updatedConfig.token ?? null; + } catch (error) { + (0, import_auth_config.writeAuthConfig)({}); + return null; + } + } + async function getVercelOidcToken(authToken, projectId, teamId) { + const url = `https://api.vercel.com/v1/projects/${projectId}/token?source=vercel-oidc-refresh${teamId ? `&teamId=${teamId}` : ""}`; + const res = await fetch(url, { + method: "POST", + headers: { + Authorization: `Bearer ${authToken}` + } + }); + if (!res.ok) throw new import_token_error.VercelOidcTokenError(`Failed to refresh OIDC token: ${res.statusText}`); + const tokenRes = await res.json(); + assertVercelOidcTokenResponse(tokenRes); + return tokenRes; + } + function assertVercelOidcTokenResponse(res) { + if (!res || "object" != typeof res) throw new TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again"); + if (!("token" in res) || "string" != typeof res.token) throw new TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again"); + } + function findProjectInfo() { + const dir = (0, import_token_io.findRootDir)(); + if (!dir) throw new import_token_error.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`"); + const prjPath = path.join(dir, ".vercel", "project.json"); + if (!fs.existsSync(prjPath)) throw new import_token_error.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`"); + const prj = JSON.parse(fs.readFileSync(prjPath, "utf8")); + if ("string" != typeof prj.projectId && "string" != typeof prj.orgId) throw new TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project."); + return { + projectId: prj.projectId, + teamId: prj.orgId + }; + } + function saveToken(token, projectId) { + const dir = (0, import_token_io.getUserDataDir)(); + if (!dir) throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support."); + const tokenPath = path.join(dir, "com.vercel.token", `${projectId}.json`); + const tokenJson = JSON.stringify(token); + fs.mkdirSync(path.dirname(tokenPath), { + mode: 504, + recursive: true + }); + fs.writeFileSync(tokenPath, tokenJson); + fs.chmodSync(tokenPath, 432); + } + function loadToken(projectId) { + const dir = (0, import_token_io.getUserDataDir)(); + if (!dir) throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support."); + const tokenPath = path.join(dir, "com.vercel.token", `${projectId}.json`); + if (!fs.existsSync(tokenPath)) return null; + const token = JSON.parse(fs.readFileSync(tokenPath, "utf8")); + assertVercelOidcTokenResponse(token); + return token; + } + function getTokenPayload(token) { + const tokenParts = token.split("."); + if (3 !== tokenParts.length) throw new import_token_error.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again"); + const base64 = tokenParts[1].replace(/-/g, "+").replace(/_/g, "/"); + const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "="); + return JSON.parse(Buffer.from(padded, "base64").toString("utf8")); + } + function isExpired(token) { + return 1e3 * token.exp < Date.now(); + } + }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token.js": function(module, __unused_webpack_exports, __webpack_require__) { + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var token_exports = {}; + __export(token_exports, { + refreshToken: ()=>refreshToken + }); + module.exports = __toCommonJS(token_exports); + var import_token_error = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-error.js"); + var import_token_util = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-util.js"); + async function refreshToken() { + const { projectId, teamId } = (0, import_token_util.findProjectInfo)(); + let maybeToken = (0, import_token_util.loadToken)(projectId); + if (!maybeToken || (0, import_token_util.isExpired)((0, import_token_util.getTokenPayload)(maybeToken.token))) { + const authToken = await (0, import_token_util.getVercelCliToken)(); + if (!authToken) throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`"); + if (!projectId) throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`"); + maybeToken = await (0, import_token_util.getVercelOidcToken)(authToken, projectId, teamId); + if (!maybeToken) throw new import_token_error.VercelOidcTokenError("Failed to refresh OIDC token"); + (0, import_token_util.saveToken)(maybeToken, projectId); + } + process.env.VERCEL_OIDC_TOKEN = maybeToken.token; + } + } +}; diff --git a/dist/749.js b/dist/749.js new file mode 100644 index 0000000..06adfb9 --- /dev/null +++ b/dist/749.js @@ -0,0 +1,380 @@ +"use strict"; +exports.ids = [ + "749" +]; +exports.modules = { + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/auth-config.js": function(module, __unused_webpack_exports, __webpack_require__) { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target)=>(target = null != mod ? __create(__getProtoOf(mod)) : {}, __copyProps(!isNodeMode && mod && mod.__esModule ? target : __defProp(target, "default", { + value: mod, + enumerable: true + }), mod)); + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var auth_config_exports = {}; + __export(auth_config_exports, { + isValidAccessToken: ()=>isValidAccessToken, + readAuthConfig: ()=>readAuthConfig, + writeAuthConfig: ()=>writeAuthConfig + }); + module.exports = __toCommonJS(auth_config_exports); + var fs = __toESM(__webpack_require__("fs")); + var path = __toESM(__webpack_require__("path")); + var import_token_util = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-util.js"); + function getAuthConfigPath() { + const dataDir = (0, import_token_util.getVercelDataDir)(); + if (!dataDir) throw new Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`); + return path.join(dataDir, "auth.json"); + } + function readAuthConfig() { + try { + const authPath = getAuthConfigPath(); + if (!fs.existsSync(authPath)) return null; + const content = fs.readFileSync(authPath, "utf8"); + if (!content) return null; + return JSON.parse(content); + } catch (error) { + return null; + } + } + function writeAuthConfig(config) { + const authPath = getAuthConfigPath(); + const authDir = path.dirname(authPath); + if (!fs.existsSync(authDir)) fs.mkdirSync(authDir, { + mode: 504, + recursive: true + }); + fs.writeFileSync(authPath, JSON.stringify(config, null, 2), { + mode: 384 + }); + } + function isValidAccessToken(authConfig) { + if (!authConfig.token) return false; + if ("number" != typeof authConfig.expiresAt) return true; + const nowInSeconds = Math.floor(Date.now() / 1e3); + return authConfig.expiresAt >= nowInSeconds; + } + }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/oauth.js": function(module, __unused_webpack_exports, __webpack_require__) { + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var oauth_exports = {}; + __export(oauth_exports, { + processTokenResponse: ()=>processTokenResponse, + refreshTokenRequest: ()=>refreshTokenRequest + }); + module.exports = __toCommonJS(oauth_exports); + var import_os = __webpack_require__("os"); + const VERCEL_ISSUER = "https://vercel.com"; + const VERCEL_CLI_CLIENT_ID = "cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp"; + const userAgent = `@vercel/oidc node-${process.version} ${(0, import_os.platform)()} (${(0, import_os.arch)()}) ${(0, import_os.hostname)()}`; + let _tokenEndpoint = null; + async function getTokenEndpoint() { + if (_tokenEndpoint) return _tokenEndpoint; + const discoveryUrl = `${VERCEL_ISSUER}/.well-known/openid-configuration`; + const response = await fetch(discoveryUrl, { + headers: { + "user-agent": userAgent + } + }); + if (!response.ok) throw new Error("Failed to discover OAuth endpoints"); + const metadata = await response.json(); + if (!metadata || "string" != typeof metadata.token_endpoint) throw new Error("Invalid OAuth discovery response"); + const endpoint = metadata.token_endpoint; + _tokenEndpoint = endpoint; + return endpoint; + } + async function refreshTokenRequest(options) { + const tokenEndpoint = await getTokenEndpoint(); + return await fetch(tokenEndpoint, { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + "user-agent": userAgent + }, + body: new URLSearchParams({ + client_id: VERCEL_CLI_CLIENT_ID, + grant_type: "refresh_token", + ...options + }) + }); + } + async function processTokenResponse(response) { + const json = await response.json(); + if (!response.ok) { + const errorMsg = "object" == typeof json && json && "error" in json ? String(json.error) : "Token refresh failed"; + return [ + new Error(errorMsg) + ]; + } + if ("object" != typeof json || null === json) return [ + new Error("Invalid token response") + ]; + if ("string" != typeof json.access_token) return [ + new Error("Missing access_token in response") + ]; + if ("Bearer" !== json.token_type) return [ + new Error("Invalid token_type in response") + ]; + if ("number" != typeof json.expires_in) return [ + new Error("Missing expires_in in response") + ]; + return [ + null, + json + ]; + } + }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-io.js": function(module, __unused_webpack_exports, __webpack_require__) { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target)=>(target = null != mod ? __create(__getProtoOf(mod)) : {}, __copyProps(!isNodeMode && mod && mod.__esModule ? target : __defProp(target, "default", { + value: mod, + enumerable: true + }), mod)); + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var token_io_exports = {}; + __export(token_io_exports, { + findRootDir: ()=>findRootDir, + getUserDataDir: ()=>getUserDataDir + }); + module.exports = __toCommonJS(token_io_exports); + var import_path = __toESM(__webpack_require__("path")); + var import_fs = __toESM(__webpack_require__("fs")); + var import_os = __toESM(__webpack_require__("os")); + var import_token_error = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-error.js"); + function findRootDir() { + try { + let dir = process.cwd(); + while(dir !== import_path.default.dirname(dir)){ + const pkgPath = import_path.default.join(dir, ".vercel"); + if (import_fs.default.existsSync(pkgPath)) return dir; + dir = import_path.default.dirname(dir); + } + } catch (e) { + throw new import_token_error.VercelOidcTokenError("Token refresh only supported in node server environments"); + } + return null; + } + function getUserDataDir() { + if (process.env.XDG_DATA_HOME) return process.env.XDG_DATA_HOME; + switch(import_os.default.platform()){ + case "darwin": + return import_path.default.join(import_os.default.homedir(), "Library/Application Support"); + case "linux": + return import_path.default.join(import_os.default.homedir(), ".local/share"); + case "win32": + if (process.env.LOCALAPPDATA) return process.env.LOCALAPPDATA; + return null; + default: + return null; + } + } + }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-util.js": function(module, __unused_webpack_exports, __webpack_require__) { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target)=>(target = null != mod ? __create(__getProtoOf(mod)) : {}, __copyProps(!isNodeMode && mod && mod.__esModule ? target : __defProp(target, "default", { + value: mod, + enumerable: true + }), mod)); + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var token_util_exports = {}; + __export(token_util_exports, { + assertVercelOidcTokenResponse: ()=>assertVercelOidcTokenResponse, + findProjectInfo: ()=>findProjectInfo, + getTokenPayload: ()=>getTokenPayload, + getVercelCliToken: ()=>getVercelCliToken, + getVercelDataDir: ()=>getVercelDataDir, + getVercelOidcToken: ()=>getVercelOidcToken, + isExpired: ()=>isExpired, + loadToken: ()=>loadToken, + saveToken: ()=>saveToken + }); + module.exports = __toCommonJS(token_util_exports); + var path = __toESM(__webpack_require__("path")); + var fs = __toESM(__webpack_require__("fs")); + var import_token_error = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-error.js"); + var import_token_io = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-io.js"); + var import_auth_config = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/auth-config.js"); + var import_oauth = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/oauth.js"); + function getVercelDataDir() { + const vercelFolder = "com.vercel.cli"; + const dataDir = (0, import_token_io.getUserDataDir)(); + if (!dataDir) return null; + return path.join(dataDir, vercelFolder); + } + async function getVercelCliToken() { + const authConfig = (0, import_auth_config.readAuthConfig)(); + if (!authConfig) return null; + if ((0, import_auth_config.isValidAccessToken)(authConfig)) return authConfig.token || null; + if (!authConfig.refreshToken) { + (0, import_auth_config.writeAuthConfig)({}); + return null; + } + try { + const tokenResponse = await (0, import_oauth.refreshTokenRequest)({ + refresh_token: authConfig.refreshToken + }); + const [tokensError, tokens] = await (0, import_oauth.processTokenResponse)(tokenResponse); + if (tokensError || !tokens) { + (0, import_auth_config.writeAuthConfig)({}); + return null; + } + const updatedConfig = { + token: tokens.access_token, + expiresAt: Math.floor(Date.now() / 1e3) + tokens.expires_in + }; + if (tokens.refresh_token) updatedConfig.refreshToken = tokens.refresh_token; + (0, import_auth_config.writeAuthConfig)(updatedConfig); + return updatedConfig.token ?? null; + } catch (error) { + (0, import_auth_config.writeAuthConfig)({}); + return null; + } + } + async function getVercelOidcToken(authToken, projectId, teamId) { + const url = `https://api.vercel.com/v1/projects/${projectId}/token?source=vercel-oidc-refresh${teamId ? `&teamId=${teamId}` : ""}`; + const res = await fetch(url, { + method: "POST", + headers: { + Authorization: `Bearer ${authToken}` + } + }); + if (!res.ok) throw new import_token_error.VercelOidcTokenError(`Failed to refresh OIDC token: ${res.statusText}`); + const tokenRes = await res.json(); + assertVercelOidcTokenResponse(tokenRes); + return tokenRes; + } + function assertVercelOidcTokenResponse(res) { + if (!res || "object" != typeof res) throw new TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again"); + if (!("token" in res) || "string" != typeof res.token) throw new TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again"); + } + function findProjectInfo() { + const dir = (0, import_token_io.findRootDir)(); + if (!dir) throw new import_token_error.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`"); + const prjPath = path.join(dir, ".vercel", "project.json"); + if (!fs.existsSync(prjPath)) throw new import_token_error.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`"); + const prj = JSON.parse(fs.readFileSync(prjPath, "utf8")); + if ("string" != typeof prj.projectId && "string" != typeof prj.orgId) throw new TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project."); + return { + projectId: prj.projectId, + teamId: prj.orgId + }; + } + function saveToken(token, projectId) { + const dir = (0, import_token_io.getUserDataDir)(); + if (!dir) throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support."); + const tokenPath = path.join(dir, "com.vercel.token", `${projectId}.json`); + const tokenJson = JSON.stringify(token); + fs.mkdirSync(path.dirname(tokenPath), { + mode: 504, + recursive: true + }); + fs.writeFileSync(tokenPath, tokenJson); + fs.chmodSync(tokenPath, 432); + } + function loadToken(projectId) { + const dir = (0, import_token_io.getUserDataDir)(); + if (!dir) throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support."); + const tokenPath = path.join(dir, "com.vercel.token", `${projectId}.json`); + if (!fs.existsSync(tokenPath)) return null; + const token = JSON.parse(fs.readFileSync(tokenPath, "utf8")); + assertVercelOidcTokenResponse(token); + return token; + } + function getTokenPayload(token) { + const tokenParts = token.split("."); + if (3 !== tokenParts.length) throw new import_token_error.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again"); + const base64 = tokenParts[1].replace(/-/g, "+").replace(/_/g, "/"); + const padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, "="); + return JSON.parse(Buffer.from(padded, "base64").toString("utf8")); + } + function isExpired(token) { + return 1e3 * token.exp < Date.now(); + } + } +}; diff --git a/dist/index.js b/dist/index.js index 8536665..509dfc7 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5543,11 +5543,11 @@ The following characters are not allowed in files that are uploaded due to limit HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes = exports1.HttpCodes || (exports1.HttpCodes = {})); - var Headers; - (function(Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; - })(Headers = exports1.Headers || (exports1.Headers = {})); + var Headers1; + (function(Headers1) { + Headers1["Accept"] = "accept"; + Headers1["ContentType"] = "content-type"; + })(Headers1 = exports1.Headers || (exports1.Headers = {})); var MediaTypes; (function(MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; @@ -5660,28 +5660,28 @@ The following characters are not allowed in files that are uploaded due to limit return this.request(verb, requestUrl, stream, additionalHeaders); } async getJson(requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.Accept, MediaTypes.ApplicationJson); let res = await this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); } async postJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.ContentType, MediaTypes.ApplicationJson); let res = await this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async putJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.ContentType, MediaTypes.ApplicationJson); let res = await this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async patchJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.ContentType, MediaTypes.ApplicationJson); let res = await this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } @@ -6111,11 +6111,11 @@ The following characters are not allowed in files that are uploaded due to limit HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes || (exports1.HttpCodes = HttpCodes = {})); - var Headers; - (function(Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; - })(Headers || (exports1.Headers = Headers = {})); + var Headers1; + (function(Headers1) { + Headers1["Accept"] = "accept"; + Headers1["ContentType"] = "content-type"; + })(Headers1 || (exports1.Headers = Headers1 = {})); var MediaTypes; (function(MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; @@ -6260,7 +6260,7 @@ The following characters are not allowed in files that are uploaded due to limit } getJson(requestUrl, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function*() { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.Accept, MediaTypes.ApplicationJson); const res = yield this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); }); @@ -6268,8 +6268,8 @@ The following characters are not allowed in files that are uploaded due to limit postJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function*() { const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.ContentType, MediaTypes.ApplicationJson); const res = yield this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); @@ -6277,8 +6277,8 @@ The following characters are not allowed in files that are uploaded due to limit putJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function*() { const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.ContentType, MediaTypes.ApplicationJson); const res = yield this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); @@ -6286,8 +6286,8 @@ The following characters are not allowed in files that are uploaded due to limit patchJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function*() { const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers1.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers1.ContentType, MediaTypes.ApplicationJson); const res = yield this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); @@ -8262,11 +8262,11 @@ The following characters are not allowed in files that are uploaded due to limit for(const key in map)if (key.toLowerCase() === name) return key; } const MAP = Symbol('map'); - class Headers { + class Headers1 { constructor(){ let init = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : void 0; this[MAP] = Object.create(null); - if (init instanceof Headers) { + if (init instanceof Headers1) { const rawHeaders = init.raw(); const headerNames = Object.keys(rawHeaders); for (const headerName of headerNames)for (const value1 of rawHeaders[headerName])this.append(headerName, value1); @@ -8356,14 +8356,14 @@ The following characters are not allowed in files that are uploaded due to limit return createHeadersIterator(this, 'key+value'); } } - Headers.prototype.entries = Headers.prototype[Symbol.iterator]; - Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + Headers1.prototype.entries = Headers1.prototype[Symbol.iterator]; + Object.defineProperty(Headers1.prototype, Symbol.toStringTag, { value: 'Headers', writable: false, enumerable: false, configurable: true }); - Object.defineProperties(Headers.prototype, { + Object.defineProperties(Headers1.prototype, { get: { enumerable: true }, @@ -8449,7 +8449,7 @@ The following characters are not allowed in files that are uploaded due to limit return obj; } function createHeadersLenient(obj) { - const headers = new Headers(); + const headers = new Headers1(); for (const name of Object.keys(obj))if (!invalidTokenRegex.test(name)) { if (Array.isArray(obj[name])) { for (const val of obj[name])if (!invalidHeaderCharRegex.test(val)) if (void 0 === headers[MAP][name]) headers[MAP][name] = [ @@ -8470,7 +8470,7 @@ The following characters are not allowed in files that are uploaded due to limit let opts = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}; Body.call(this, body, opts); const status = opts.status || 200; - const headers = new Headers(opts.headers); + const headers = new Headers1(opts.headers); if (null != body && !headers.has('Content-Type')) { const contentType = extractContentType(body); if (contentType) headers.append('Content-Type', contentType); @@ -8575,7 +8575,7 @@ The following characters are not allowed in files that are uploaded due to limit timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0 }); - const headers = new Headers(init.headers || input.headers || {}); + const headers = new Headers1(init.headers || input.headers || {}); if (null != inputBody && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody); if (contentType) headers.append('Content-Type', contentType); @@ -8643,7 +8643,7 @@ The following characters are not allowed in files that are uploaded due to limit }); function getNodeRequestOptions(request) { const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); + const headers = new Headers1(request[INTERNALS$2].headers); if (!headers.has('Accept')) headers.set('Accept', '*/*'); if (!parsedURL.protocol || !parsedURL.hostname) throw new TypeError('Only absolute URLs are supported'); if (!/^https?:$/.test(parsedURL.protocol)) throw new TypeError('Only HTTP(S) protocols are supported'); @@ -8775,7 +8775,7 @@ The following characters are not allowed in files that are uploaded due to limit return; } const requestOpts = { - headers: new Headers(request.headers), + headers: new Headers1(request.headers), follow: request.follow, counter: request.counter + 1, agent: request.agent, @@ -8945,8 +8945,8 @@ The following characters are not allowed in files that are uploaded due to limit let headers = {}; let status; let url; - const fetch = requestOptions.request && requestOptions.request.fetch || lib; - return fetch(requestOptions.url, Object.assign({ + const fetch1 = requestOptions.request && requestOptions.request.fetch || lib; + return fetch1(requestOptions.url, Object.assign({ method: requestOptions.method, body: requestOptions.body, headers: requestOptions.headers, @@ -17971,6 +17971,181 @@ The following characters are not allowed in files that are uploaded due to limit return sb.join(''); } }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-context.js": function(module) { + "use strict"; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var get_context_exports = {}; + __export(get_context_exports, { + SYMBOL_FOR_REQ_CONTEXT: ()=>SYMBOL_FOR_REQ_CONTEXT, + getContext: ()=>getContext + }); + module.exports = __toCommonJS(get_context_exports); + const SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context"); + function getContext() { + const fromSymbol = globalThis; + return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {}; + } + }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js": function(module, __unused_webpack_exports, __webpack_require__) { + "use strict"; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var get_vercel_oidc_token_exports = {}; + __export(get_vercel_oidc_token_exports, { + getVercelOidcToken: ()=>getVercelOidcToken, + getVercelOidcTokenSync: ()=>getVercelOidcTokenSync + }); + module.exports = __toCommonJS(get_vercel_oidc_token_exports); + var import_get_context = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-context.js"); + var import_token_error = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-error.js"); + async function getVercelOidcToken() { + let token = ""; + let err; + try { + token = getVercelOidcTokenSync(); + } catch (error) { + err = error; + } + try { + const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([ + await __webpack_require__.e("749").then(__webpack_require__.t.bind(__webpack_require__, "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-util.js", 23)), + await __webpack_require__.e("682").then(__webpack_require__.t.bind(__webpack_require__, "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token.js", 23)) + ]); + if (!token || isExpired(getTokenPayload(token))) { + await refreshToken(); + token = getVercelOidcTokenSync(); + } + } catch (error) { + let message = err instanceof Error ? err.message : ""; + if (error instanceof Error) message = `${message} +${error.message}`; + if (message) throw new import_token_error.VercelOidcTokenError(message); + throw error; + } + return token; + } + function getVercelOidcTokenSync() { + const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN; + if (!token) throw new Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?"); + return token; + } + }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/index.js": function(module, __unused_webpack_exports, __webpack_require__) { + "use strict"; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var src_exports = {}; + __export(src_exports, { + getContext: ()=>import_get_context.getContext, + getVercelOidcToken: ()=>import_get_vercel_oidc_token.getVercelOidcToken, + getVercelOidcTokenSync: ()=>import_get_vercel_oidc_token.getVercelOidcTokenSync + }); + module.exports = __toCommonJS(src_exports); + var import_get_vercel_oidc_token = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"); + var import_get_context = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-context.js"); + }, + "./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/token-error.js": function(module) { + "use strict"; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __export = (target, all)=>{ + for(var name in all)__defProp(target, name, { + get: all[name], + enumerable: true + }); + }; + var __copyProps = (to, from, except, desc)=>{ + if (from && "object" == typeof from || "function" == typeof from) { + for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ()=>from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; + }; + var __toCommonJS = (mod)=>__copyProps(__defProp({}, "__esModule", { + value: true + }), mod); + var token_error_exports = {}; + __export(token_error_exports, { + VercelOidcTokenError: ()=>VercelOidcTokenError + }); + module.exports = __toCommonJS(token_error_exports); + class VercelOidcTokenError extends Error { + constructor(message, cause){ + super(message); + this.name = "VercelOidcTokenError"; + this.cause = cause; + } + toString() { + if (this.cause) return `${this.name}: ${this.message}: ${this.cause}`; + return `${this.name}: ${this.message}`; + } + } + }, "./node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/dist/helpers.js": function(__unused_webpack_module, exports1, __webpack_require__) { "use strict"; var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) { @@ -42229,12 +42404,12 @@ The following characters are not allowed in files that are uploaded due to limit const { parseSetCookie } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/cookies/parse.js"); const { stringify } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/cookies/util.js"); const { webidl } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/webidl.js"); - const { Headers } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/headers.js"); + const { Headers: Headers1 } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/headers.js"); function getCookies(headers) { webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }); - webidl.brandCheck(headers, Headers, { + webidl.brandCheck(headers, Headers1, { strict: false }); const cookie = headers.get('cookie'); @@ -42250,7 +42425,7 @@ The following characters are not allowed in files that are uploaded due to limit webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }); - webidl.brandCheck(headers, Headers, { + webidl.brandCheck(headers, Headers1, { strict: false }); name = webidl.converters.DOMString(name); @@ -42266,7 +42441,7 @@ The following characters are not allowed in files that are uploaded due to limit webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }); - webidl.brandCheck(headers, Headers, { + webidl.brandCheck(headers, Headers1, { strict: false }); const cookies = headers.getSetCookie(); @@ -42277,7 +42452,7 @@ The following characters are not allowed in files that are uploaded due to limit webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }); - webidl.brandCheck(headers, Headers, { + webidl.brandCheck(headers, Headers1, { strict: false }); cookie = webidl.converters.Cookie(cookie); @@ -43812,7 +43987,7 @@ The following characters are not allowed in files that are uploaded due to limit const { FormData: FormData1 } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/formdata.js"); const { kState } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/symbols.js"); const { webidl } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/webidl.js"); - const { DOMException: DOMException1, structuredClone } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/constants.js"); + const { DOMException: DOMException1, structuredClone: structuredClone1 } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/constants.js"); const { Blob: Blob1, File: NativeFile } = __webpack_require__("buffer"); const { kBodyUsed } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/core/symbols.js"); const assert = __webpack_require__("assert"); @@ -43937,7 +44112,7 @@ The following characters are not allowed in files that are uploaded due to limit } function cloneBody(body) { const [out1, out2] = body.stream.tee(); - const out2Clone = structuredClone(out2, { + const out2Clone = structuredClone1(out2, { transfer: [ out2 ] @@ -44312,7 +44487,7 @@ The following characters are not allowed in files that are uploaded due to limit } })(); let channel; - const structuredClone = globalThis.structuredClone ?? function(value1, options1) { + const structuredClone1 = globalThis.structuredClone ?? function(value1, options1) { if (0 === arguments.length) throw new TypeError('missing argument'); if (!channel) channel = new MessageChannel(); channel.port1.unref(); @@ -44322,7 +44497,7 @@ The following characters are not allowed in files that are uploaded due to limit }; module.exports = { DOMException: DOMException1, - structuredClone, + structuredClone: structuredClone1, subresource, forbiddenMethods, requestBodyHeader, @@ -45041,7 +45216,7 @@ The following characters are not allowed in files that are uploaded due to limit return headers; } } - class Headers { + class Headers1 { constructor(init){ if (init === kConstruct) return; this[kHeadersList] = new HeadersList(); @@ -45052,7 +45227,7 @@ The following characters are not allowed in files that are uploaded due to limit } } append(name, value1) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }); @@ -45061,7 +45236,7 @@ The following characters are not allowed in files that are uploaded due to limit return appendHeader(this, name, value1); } delete(name) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }); @@ -45077,7 +45252,7 @@ The following characters are not allowed in files that are uploaded due to limit this[kHeadersList].delete(name); } get(name) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }); @@ -45090,7 +45265,7 @@ The following characters are not allowed in files that are uploaded due to limit return this[kHeadersList].get(name); } has(name) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }); @@ -45103,7 +45278,7 @@ The following characters are not allowed in files that are uploaded due to limit return this[kHeadersList].contains(name); } set(name, value1) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }); @@ -45126,7 +45301,7 @@ The following characters are not allowed in files that are uploaded due to limit this[kHeadersList].set(name, value1); } getSetCookie() { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); const list = this[kHeadersList].cookies; if (list) return [ ...list @@ -45158,7 +45333,7 @@ The following characters are not allowed in files that are uploaded due to limit return headers; } keys() { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); if ('immutable' === this[kGuard]) { const value1 = this[kHeadersSortedMap]; return makeIterator(()=>value1, 'Headers', 'key'); @@ -45168,7 +45343,7 @@ The following characters are not allowed in files that are uploaded due to limit ], 'Headers', 'key'); } values() { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); if ('immutable' === this[kGuard]) { const value1 = this[kHeadersSortedMap]; return makeIterator(()=>value1, 'Headers', 'value'); @@ -45178,7 +45353,7 @@ The following characters are not allowed in files that are uploaded due to limit ], 'Headers', 'value'); } entries() { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); if ('immutable' === this[kGuard]) { const value1 = this[kHeadersSortedMap]; return makeIterator(()=>value1, 'Headers', 'key+value'); @@ -45188,7 +45363,7 @@ The following characters are not allowed in files that are uploaded due to limit ], 'Headers', 'key+value'); } forEach(callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }); @@ -45200,12 +45375,12 @@ The following characters are not allowed in files that are uploaded due to limit ]); } [Symbol.for('nodejs.util.inspect.custom')]() { - webidl.brandCheck(this, Headers); + webidl.brandCheck(this, Headers1); return this[kHeadersList]; } } - Headers.prototype[Symbol.iterator] = Headers.prototype.entries; - Object.defineProperties(Headers.prototype, { + Headers1.prototype[Symbol.iterator] = Headers1.prototype.entries; + Object.defineProperties(Headers1.prototype, { append: kEnumerableProperty, delete: kEnumerableProperty, get: kEnumerableProperty, @@ -45243,14 +45418,14 @@ The following characters are not allowed in files that are uploaded due to limit }; module.exports = { fill, - Headers, + Headers: Headers1, HeadersList }; }, "./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/index.js": function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; const { Response, makeNetworkError, makeAppropriateNetworkError, filterResponse, makeResponse } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/response.js"); - const { Headers } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/headers.js"); + const { Headers: Headers1 } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/headers.js"); const { Request, makeRequest } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/request.js"); const zlib = __webpack_require__("zlib"); const { bytesMatch, makePolicyContainer, clonePolicyContainer, requestBadPort, TAOCheck, appendRequestOriginHeader, responseLocationURL, requestCurrentURL, setRequestReferrerPolicyOnRedirect, tryUpgradeRequestToAPotentiallyTrustworthyURL, createOpaqueTimingInfo, appendFetchMetadata, corsCheck, crossOriginResourcePolicyCheck, determineRequestsReferrer, coarsenedSharedCurrentTime, createDeferredPromise, isBlobLike, sameOrigin, isCancelled, isAborted, isErrorLike, fullyReadBody, readableStreamClose, isomorphicEncode, urlIsLocal, urlIsHttpHttpsScheme, urlHasHttpsScheme } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/util.js"); @@ -45263,7 +45438,7 @@ The following characters are not allowed in files that are uploaded due to limit const { Readable, pipeline } = __webpack_require__("stream"); const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/core/util.js"); const { dataURLProcessor, serializeAMimeType } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/dataURL.js"); - const { TransformStream } = __webpack_require__("stream/web"); + const { TransformStream: TransformStream1 } = __webpack_require__("stream/web"); const { getGlobalDispatcher } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/global.js"); const { webidl } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/webidl.js"); const { STATUS_CODES } = __webpack_require__("http"); @@ -45297,7 +45472,7 @@ The following characters are not allowed in files that are uploaded due to limit this.emit('terminated', error); } } - function fetch(input, init = {}) { + function fetch1(input, init = {}) { webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }); @@ -45573,7 +45748,7 @@ The following characters are not allowed in files that are uploaded due to limit const identityTransformAlgorithm = (chunk, controller)=>{ controller.enqueue(chunk); }; - const transformStream = new TransformStream({ + const transformStream = new TransformStream1({ start () {}, transform: identityTransformAlgorithm, flush: processResponseEndOfBody @@ -45889,7 +46064,7 @@ The following characters are not allowed in files that are uploaded due to limit if (status < 200) return; let codings = []; let location = ''; - const headers = new Headers(); + const headers = new Headers1(); if (Array.isArray(headersList)) for(let n = 0; n < headersList.length; n += 2){ const key = headersList[n + 0].toString('latin1'); const val = headersList[n + 1].toString('latin1'); @@ -45948,7 +46123,7 @@ The following characters are not allowed in files that are uploaded due to limit }, onUpgrade (status, headersList, socket) { if (101 !== status) return; - const headers = new Headers(); + const headers = new Headers1(); for(let n = 0; n < headersList.length; n += 2){ const key = headersList[n + 0].toString('latin1'); const val = headersList[n + 1].toString('latin1'); @@ -45966,7 +46141,7 @@ The following characters are not allowed in files that are uploaded due to limit } } module.exports = { - fetch, + fetch: fetch1, Fetch, fetching, finalizeAndReportTiming @@ -45975,7 +46150,7 @@ The following characters are not allowed in files that are uploaded due to limit "./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/request.js": function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; const { extractBody, mixinBody, cloneBody } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/body.js"); - const { Headers, fill: fillHeaders, HeadersList } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/headers.js"); + const { Headers: Headers1, fill: fillHeaders, HeadersList } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/headers.js"); const { FinalizationRegistry } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/compat/dispatcher-weakref.js")(); const util = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/core/util.js"); const { isValidHTTPToken, sameOrigin, normalizeMethod, makePolicyContainer, normalizeMethodRecord } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/util.js"); @@ -45988,7 +46163,7 @@ The following characters are not allowed in files that are uploaded due to limit const { kHeadersList, kConstruct } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/core/symbols.js"); const assert = __webpack_require__("assert"); const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __webpack_require__("events"); - let TransformStream = globalThis.TransformStream; + let TransformStream1 = globalThis.TransformStream; const kAbortController = Symbol('abortController'); const requestFinalizer = new FinalizationRegistry(({ signal, abort })=>{ signal.removeEventListener('abort', abort); @@ -46138,7 +46313,7 @@ The following characters are not allowed in files that are uploaded due to limit }); } } - this[kHeaders] = new Headers(kConstruct); + this[kHeaders] = new Headers1(kConstruct); this[kHeaders][kHeadersList] = request.headersList; this[kHeaders][kGuard] = 'request'; this[kHeaders][kRealm] = this[kRealm]; @@ -46172,8 +46347,8 @@ The following characters are not allowed in files that are uploaded due to limit let finalBody = inputOrInitBody; if (null == initBody && null != inputBody) { if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) throw new TypeError('Cannot construct a Request with a Request object that has already been used.'); - if (!TransformStream) TransformStream = __webpack_require__("stream/web").TransformStream; - const identityTransform = new TransformStream(); + if (!TransformStream1) TransformStream1 = __webpack_require__("stream/web").TransformStream; + const identityTransform = new TransformStream1(); inputBody.stream.pipeThrough(identityTransform); finalBody = { source: inputBody.source, @@ -46263,7 +46438,7 @@ The following characters are not allowed in files that are uploaded due to limit const clonedRequestObject = new Request(kConstruct); clonedRequestObject[kState] = clonedRequest; clonedRequestObject[kRealm] = this[kRealm]; - clonedRequestObject[kHeaders] = new Headers(kConstruct); + clonedRequestObject[kHeaders] = new Headers1(kConstruct); clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList; clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]; clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]; @@ -46434,7 +46609,7 @@ The following characters are not allowed in files that are uploaded due to limit }, "./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/response.js": function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; - const { Headers, HeadersList, fill } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/headers.js"); + const { Headers: Headers1, HeadersList, fill } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/headers.js"); const { extractBody, cloneBody, mixinBody } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/body.js"); const util = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/core/util.js"); const { kEnumerableProperty } = util; @@ -46517,7 +46692,7 @@ The following characters are not allowed in files that are uploaded due to limit settingsObject: {} }; this[kState] = makeResponse({}); - this[kHeaders] = new Headers(kConstruct); + this[kHeaders] = new Headers1(kConstruct); this[kHeaders][kGuard] = 'response'; this[kHeaders][kHeadersList] = this[kState].headersList; this[kHeaders][kRealm] = this[kRealm]; @@ -50124,7 +50299,7 @@ ${pendingInterceptorsFormatter.format(pending)} const { CloseEvent } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/websocket/events.js"); const { makeRequest } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/request.js"); const { fetching } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/index.js"); - const { Headers } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/headers.js"); + const { Headers: Headers1 } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/fetch/headers.js"); const { getGlobalDispatcher } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/global.js"); const { kHeadersList } = __webpack_require__("./node_modules/.pnpm/undici@5.29.0/node_modules/undici/lib/core/symbols.js"); const channels = {}; @@ -50150,7 +50325,7 @@ ${pendingInterceptorsFormatter.format(pending)} redirect: 'error' }); if (options1.headers) { - const headersList = new Headers(options1.headers)[kHeadersList]; + const headersList = new Headers1(options1.headers)[kHeadersList]; request.headersList = headersList; } const keyValue = crypto.randomBytes(16).toString('base64'); @@ -95600,6 +95775,7 @@ function __webpack_require__(moduleId) { module.loaded = true; return module.exports; } +__webpack_require__.m = __webpack_modules__; (()=>{ __webpack_require__.n = (module)=>{ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module; @@ -95609,6 +95785,33 @@ function __webpack_require__(moduleId) { return getter; }; })(); +(()=>{ + var getProto = Object.getPrototypeOf ? (obj)=>Object.getPrototypeOf(obj) : (obj)=>obj.__proto__; + var leafPrototypes; + __webpack_require__.t = function(value1, mode) { + if (1 & mode) value1 = this(value1); + if (8 & mode) return value1; + if ('object' == typeof value1 && value1) { + if (4 & mode && value1.__esModule) return value1; + if (16 & mode && 'function' == typeof value1.then) return value1; + } + var ns = Object.create(null); + __webpack_require__.r(ns); + var def = {}; + leafPrototypes = leafPrototypes || [ + null, + getProto({}), + getProto([]), + getProto(getProto) + ]; + for(var current = 2 & mode && value1; 'object' == typeof current && !~leafPrototypes.indexOf(current); current = getProto(current))Object.getOwnPropertyNames(current).forEach((key)=>{ + def[key] = ()=>value1[key]; + }); + def['default'] = ()=>value1; + __webpack_require__.d(ns, def); + return ns; + }; +})(); (()=>{ __webpack_require__.d = (exports1, definition)=>{ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, { @@ -95617,6 +95820,16 @@ function __webpack_require__(moduleId) { }); }; })(); +(()=>{ + __webpack_require__.f = {}; + __webpack_require__.e = (chunkId)=>Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key)=>{ + __webpack_require__.f[key](chunkId, promises); + return promises; + }, [])); +})(); +(()=>{ + __webpack_require__.u = (chunkId)=>"" + chunkId + ".js"; +})(); (()=>{ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop); })(); @@ -95637,6 +95850,20 @@ function __webpack_require__(moduleId) { return module; }; })(); +(()=>{ + var installedChunks = { + 410: 1 + }; + var installChunk = (chunk)=>{ + var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime; + for(var moduleId in moreModules)if (__webpack_require__.o(moreModules, moduleId)) __webpack_require__.m[moduleId] = moreModules[moduleId]; + if (runtime) runtime(__webpack_require__); + for(var i = 0; i < chunkIds.length; i++)installedChunks[chunkIds[i]] = 1; + }; + __webpack_require__.f.require = (chunkId, promises)=>{ + if (!installedChunks[chunkId]) installChunk(require("./" + __webpack_require__.u(chunkId))); + }; +})(); var __webpack_exports__ = {}; (()=>{ "use strict"; @@ -95644,6 +95871,281 @@ var __webpack_exports__ = {}; __webpack_require__.d(__webpack_exports__, { extractProjectName: ()=>extractProjectName }); + var regexes_namespaceObject = {}; + __webpack_require__.r(regexes_namespaceObject); + __webpack_require__.d(regexes_namespaceObject, { + base64: ()=>regexes_base64, + base64url: ()=>regexes_base64url, + bigint: ()=>bigint, + boolean: ()=>regexes_boolean, + browserEmail: ()=>browserEmail, + cidrv4: ()=>cidrv4, + cidrv6: ()=>cidrv6, + cuid: ()=>cuid, + cuid2: ()=>cuid2, + date: ()=>date, + datetime: ()=>datetime, + domain: ()=>domain, + duration: ()=>regexes_duration, + e164: ()=>e164, + email: ()=>email, + emoji: ()=>emoji, + extendedDuration: ()=>extendedDuration, + guid: ()=>guid, + hex: ()=>regexes_hex, + hostname: ()=>regexes_hostname, + html5Email: ()=>html5Email, + idnEmail: ()=>idnEmail, + integer: ()=>integer, + ipv4: ()=>ipv4, + ipv6: ()=>regexes_ipv6, + ksuid: ()=>ksuid, + lowercase: ()=>lowercase, + mac: ()=>mac, + md5_base64: ()=>md5_base64, + md5_base64url: ()=>md5_base64url, + md5_hex: ()=>md5_hex, + nanoid: ()=>nanoid, + null: ()=>_null, + number: ()=>regexes_number, + rfc5322Email: ()=>rfc5322Email, + sha1_base64: ()=>sha1_base64, + sha1_base64url: ()=>sha1_base64url, + sha1_hex: ()=>sha1_hex, + sha256_base64: ()=>sha256_base64, + sha256_base64url: ()=>sha256_base64url, + sha256_hex: ()=>sha256_hex, + sha384_base64: ()=>sha384_base64, + sha384_base64url: ()=>sha384_base64url, + sha384_hex: ()=>sha384_hex, + sha512_base64: ()=>sha512_base64, + sha512_base64url: ()=>sha512_base64url, + sha512_hex: ()=>sha512_hex, + string: ()=>string, + time: ()=>regexes_time, + ulid: ()=>ulid, + undefined: ()=>_undefined, + unicodeEmail: ()=>unicodeEmail, + uppercase: ()=>uppercase, + uuid: ()=>uuid, + uuid4: ()=>uuid4, + uuid6: ()=>uuid6, + uuid7: ()=>uuid7, + xid: ()=>xid + }); + var classic_checks_namespaceObject = {}; + __webpack_require__.r(classic_checks_namespaceObject); + __webpack_require__.d(classic_checks_namespaceObject, { + endsWith: ()=>_endsWith, + gt: ()=>_gt, + gte: ()=>_gte, + includes: ()=>_includes, + length: ()=>_length, + lowercase: ()=>_lowercase, + lt: ()=>_lt, + lte: ()=>_lte, + maxLength: ()=>_maxLength, + maxSize: ()=>_maxSize, + mime: ()=>_mime, + minLength: ()=>_minLength, + minSize: ()=>_minSize, + multipleOf: ()=>_multipleOf, + negative: ()=>_negative, + nonnegative: ()=>_nonnegative, + nonpositive: ()=>_nonpositive, + normalize: ()=>_normalize, + overwrite: ()=>_overwrite, + positive: ()=>_positive, + property: ()=>_property, + regex: ()=>_regex, + size: ()=>_size, + slugify: ()=>_slugify, + startsWith: ()=>_startsWith, + toLowerCase: ()=>_toLowerCase, + toUpperCase: ()=>_toUpperCase, + trim: ()=>_trim, + uppercase: ()=>_uppercase + }); + var iso_namespaceObject = {}; + __webpack_require__.r(iso_namespaceObject); + __webpack_require__.d(iso_namespaceObject, { + ZodISODate: ()=>ZodISODate, + ZodISODateTime: ()=>ZodISODateTime, + ZodISODuration: ()=>ZodISODuration, + ZodISOTime: ()=>ZodISOTime, + date: ()=>iso_date, + datetime: ()=>iso_datetime, + duration: ()=>iso_duration, + time: ()=>iso_time + }); + var classic_schemas_namespaceObject = {}; + __webpack_require__.r(classic_schemas_namespaceObject); + __webpack_require__.d(classic_schemas_namespaceObject, { + ZodAny: ()=>ZodAny, + ZodArray: ()=>ZodArray, + ZodBase64: ()=>ZodBase64, + ZodBase64URL: ()=>ZodBase64URL, + ZodBigInt: ()=>ZodBigInt, + ZodBigIntFormat: ()=>ZodBigIntFormat, + ZodBoolean: ()=>ZodBoolean, + ZodCIDRv4: ()=>ZodCIDRv4, + ZodCIDRv6: ()=>ZodCIDRv6, + ZodCUID: ()=>ZodCUID, + ZodCUID2: ()=>ZodCUID2, + ZodCatch: ()=>ZodCatch, + ZodCodec: ()=>ZodCodec, + ZodCustom: ()=>ZodCustom, + ZodCustomStringFormat: ()=>ZodCustomStringFormat, + ZodDate: ()=>ZodDate, + ZodDefault: ()=>ZodDefault, + ZodDiscriminatedUnion: ()=>ZodDiscriminatedUnion, + ZodE164: ()=>ZodE164, + ZodEmail: ()=>ZodEmail, + ZodEmoji: ()=>ZodEmoji, + ZodEnum: ()=>ZodEnum, + ZodExactOptional: ()=>ZodExactOptional, + ZodFile: ()=>ZodFile, + ZodFunction: ()=>ZodFunction, + ZodGUID: ()=>ZodGUID, + ZodIPv4: ()=>ZodIPv4, + ZodIPv6: ()=>ZodIPv6, + ZodIntersection: ()=>ZodIntersection, + ZodJWT: ()=>ZodJWT, + ZodKSUID: ()=>ZodKSUID, + ZodLazy: ()=>ZodLazy, + ZodLiteral: ()=>ZodLiteral, + ZodMAC: ()=>ZodMAC, + ZodMap: ()=>ZodMap, + ZodNaN: ()=>ZodNaN, + ZodNanoID: ()=>ZodNanoID, + ZodNever: ()=>ZodNever, + ZodNonOptional: ()=>ZodNonOptional, + ZodNull: ()=>ZodNull, + ZodNullable: ()=>ZodNullable, + ZodNumber: ()=>ZodNumber, + ZodNumberFormat: ()=>ZodNumberFormat, + ZodObject: ()=>ZodObject, + ZodOptional: ()=>ZodOptional, + ZodPipe: ()=>ZodPipe, + ZodPrefault: ()=>ZodPrefault, + ZodPromise: ()=>ZodPromise, + ZodReadonly: ()=>ZodReadonly, + ZodRecord: ()=>ZodRecord, + ZodSet: ()=>ZodSet, + ZodString: ()=>ZodString, + ZodStringFormat: ()=>ZodStringFormat, + ZodSuccess: ()=>ZodSuccess, + ZodSymbol: ()=>ZodSymbol, + ZodTemplateLiteral: ()=>ZodTemplateLiteral, + ZodTransform: ()=>ZodTransform, + ZodTuple: ()=>ZodTuple, + ZodType: ()=>ZodType, + ZodULID: ()=>ZodULID, + ZodURL: ()=>ZodURL, + ZodUUID: ()=>ZodUUID, + ZodUndefined: ()=>ZodUndefined, + ZodUnion: ()=>ZodUnion, + ZodUnknown: ()=>ZodUnknown, + ZodVoid: ()=>ZodVoid, + ZodXID: ()=>ZodXID, + ZodXor: ()=>ZodXor, + _ZodString: ()=>_ZodString, + _default: ()=>schemas_default, + _function: ()=>_function, + any: ()=>any, + array: ()=>schemas_array, + base64: ()=>schemas_base64, + base64url: ()=>schemas_base64url, + bigint: ()=>schemas_bigint, + boolean: ()=>schemas_boolean, + catch: ()=>schemas_catch, + check: ()=>schemas_check, + cidrv4: ()=>schemas_cidrv4, + cidrv6: ()=>schemas_cidrv6, + codec: ()=>schemas_codec, + cuid: ()=>schemas_cuid, + cuid2: ()=>schemas_cuid2, + custom: ()=>custom, + date: ()=>schemas_date, + describe: ()=>schemas_describe, + discriminatedUnion: ()=>discriminatedUnion, + e164: ()=>schemas_e164, + email: ()=>schemas_email, + emoji: ()=>schemas_emoji, + enum: ()=>schemas_enum, + exactOptional: ()=>exactOptional, + file: ()=>schemas_file, + float32: ()=>float32, + float64: ()=>float64, + function: ()=>_function, + guid: ()=>schemas_guid, + hash: ()=>schemas_hash, + hex: ()=>schemas_hex, + hostname: ()=>schemas_hostname, + httpUrl: ()=>httpUrl, + instanceof: ()=>_instanceof, + int: ()=>schemas_int, + int32: ()=>int32, + int64: ()=>int64, + intersection: ()=>intersection, + ipv4: ()=>schemas_ipv4, + ipv6: ()=>schemas_ipv6, + json: ()=>schemas_json, + jwt: ()=>schemas_jwt, + keyof: ()=>keyof, + ksuid: ()=>schemas_ksuid, + lazy: ()=>lazy, + literal: ()=>schemas_literal, + looseObject: ()=>looseObject, + looseRecord: ()=>looseRecord, + mac: ()=>schemas_mac, + map: ()=>schemas_map, + meta: ()=>schemas_meta, + nan: ()=>nan, + nanoid: ()=>schemas_nanoid, + nativeEnum: ()=>nativeEnum, + never: ()=>never, + nonoptional: ()=>nonoptional, + null: ()=>schemas_null, + nullable: ()=>nullable, + nullish: ()=>schemas_nullish, + number: ()=>schemas_number, + object: ()=>schemas_object, + optional: ()=>optional, + partialRecord: ()=>partialRecord, + pipe: ()=>pipe, + prefault: ()=>prefault, + preprocess: ()=>schemas_preprocess, + promise: ()=>schemas_promise, + readonly: ()=>readonly, + record: ()=>schemas_record, + refine: ()=>refine, + set: ()=>schemas_set, + strictObject: ()=>strictObject, + string: ()=>schemas_string, + stringFormat: ()=>stringFormat, + stringbool: ()=>stringbool, + success: ()=>schemas_success, + superRefine: ()=>superRefine, + symbol: ()=>schemas_symbol, + templateLiteral: ()=>templateLiteral, + transform: ()=>schemas_transform, + tuple: ()=>tuple, + uint32: ()=>uint32, + uint64: ()=>uint64, + ulid: ()=>schemas_ulid, + undefined: ()=>schemas_undefined, + union: ()=>union, + unknown: ()=>unknown, + url: ()=>schemas_url, + uuid: ()=>schemas_uuid, + uuidv4: ()=>uuidv4, + uuidv6: ()=>uuidv6, + uuidv7: ()=>uuidv7, + void: ()=>schemas_void, + xid: ()=>schemas_xid, + xor: ()=>xor + }); var core = __webpack_require__("./node_modules/.pnpm/@actions+core@1.11.1/node_modules/@actions/core/lib/core.js"); var lib_artifact = __webpack_require__("./node_modules/.pnpm/@actions+artifact@2.3.2/node_modules/@actions/artifact/lib/artifact.js"); var external_path_ = __webpack_require__("path"); @@ -96555,305 +97057,31947 @@ var __webpack_exports__ = {}; await core.summary.write(); console.log('āœ… Bundle size report card generated successfully'); } - var external_util_ = __webpack_require__("util"); - var out = __webpack_require__("./node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/index.js"); - var out_default = /*#__PURE__*/ __webpack_require__.n(out); - const execFileAsync = (0, external_util_.promisify)(external_child_process_.execFile); - function isPullRequestEvent() { - const { context } = __webpack_require__("./node_modules/.pnpm/@actions+github@4.0.0/node_modules/@actions/github/lib/github.js"); - const isPR = 'pull_request' === context.eventName; - if (isPR) { - const prAction = context.payload.action; - const prMerged = context.payload.pull_request?.merged; - const prNumber = context.payload.pull_request?.number; - const baseRef = context.payload.pull_request?.base?.ref; - const headRef = context.payload.pull_request?.head?.ref; - if ('closed' === prAction) { - if (true === prMerged) console.log(`ā„¹ļø PR is closed and merged - upload will happen on push event`); - else console.log(`ā„¹ļø PR is closed but not merged - skipping processing`); - return false; - } - console.log(`šŸ“„ Detected pull request event`); - console.log(` Action: ${prAction}`); - console.log(` PR #${prNumber}: ${headRef} -> ${baseRef}`); - console.log(` Merged: ${prMerged}`); - console.log(" This is a PR review/update event - comparing with baseline (no upload)"); + var marker = "vercel.ai.error"; + var symbol = Symbol.for(marker); + var dist_a, dist_b; + var AISDKError = class _AISDKError extends (dist_b = Error, dist_a = symbol, dist_b) { + constructor({ name: name14, message, cause }){ + super(message); + this[dist_a] = true; + this.name = name14; + this.cause = cause; + } + static isInstance(error) { + return _AISDKError.hasMarker(error, marker); + } + static hasMarker(error, marker15) { + const markerSymbol = Symbol.for(marker15); + return null != error && "object" == typeof error && markerSymbol in error && "boolean" == typeof error[markerSymbol] && true === error[markerSymbol]; } - return isPR; + }; + var dist_name = "AI_APICallError"; + var marker2 = `vercel.ai.error.${dist_name}`; + var symbol2 = Symbol.for(marker2); + var dist_a2, dist_b2; + var APICallError = class extends (dist_b2 = AISDKError, dist_a2 = symbol2, dist_b2) { + constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = null != statusCode && (408 === statusCode || 409 === statusCode || 429 === statusCode || statusCode >= 500), data }){ + super({ + name: dist_name, + message, + cause + }); + this[dist_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 dist_name2 = "AI_EmptyResponseBodyError"; + var marker3 = `vercel.ai.error.${dist_name2}`; + var symbol3 = Symbol.for(marker3); + var dist_a3, _b3; + var EmptyResponseBodyError = class extends (_b3 = AISDKError, dist_a3 = symbol3, _b3) { + constructor({ message = "Empty response body" } = {}){ + super({ + name: dist_name2, + message + }); + this[dist_a3] = true; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker3); + } + }; + function getErrorMessage(error) { + if (null == error) return "unknown error"; + if ("string" == typeof error) return error; + if (error instanceof Error) return error.message; + return JSON.stringify(error); } - function isPushEvent() { - const { context } = __webpack_require__("./node_modules/.pnpm/@actions+github@4.0.0/node_modules/@actions/github/lib/github.js"); - const isPush = 'push' === context.eventName; - if (isPush) { - const ref = context.ref; - const targetBranch = (0, core.getInput)('target_branch') || 'main'; - const targetBranchRef = `refs/heads/${targetBranch}`; - if (ref === targetBranchRef) { - console.log(`šŸ”„ Detected push event to ${targetBranch} branch`); - console.log(" This may be a merge commit - will upload artifacts"); - return true; + var dist_name3 = "AI_InvalidArgumentError"; + var marker4 = `vercel.ai.error.${dist_name3}`; + var symbol4 = Symbol.for(marker4); + var _a4, _b4; + var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) { + constructor({ message, cause, argument }){ + super({ + name: dist_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, _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 name5 = "AI_InvalidResponseDataError"; + var marker6 = `vercel.ai.error.${name5}`; + var symbol6 = Symbol.for(marker6); + var _a6, _b6; + var InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) { + constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }){ + super({ + name: name5, + message + }); + this[_a6] = true; + this.data = data; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker6); + } + }; + var name6 = "AI_JSONParseError"; + var marker7 = `vercel.ai.error.${name6}`; + var symbol7 = Symbol.for(marker7); + var _a7, _b7; + var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) { + constructor({ text, cause }){ + super({ + name: name6, + message: `JSON parsing failed: Text: ${text}. +Error message: ${getErrorMessage(cause)}`, + cause + }); + this[_a7] = true; + this.text = text; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker7); + } + }; + var name7 = "AI_LoadAPIKeyError"; + var marker8 = `vercel.ai.error.${name7}`; + var symbol8 = Symbol.for(marker8); + var _a8, _b8; + var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) { + constructor({ message }){ + super({ + name: name7, + message + }); + this[_a8] = true; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker8); + } + }; + var name8 = "AI_LoadSettingError"; + var marker9 = `vercel.ai.error.${name8}`; + Symbol.for(marker9); + var name9 = "AI_NoContentGeneratedError"; + var marker10 = `vercel.ai.error.${name9}`; + Symbol.for(marker10); + var name10 = "AI_NoSuchModelError"; + var marker11 = `vercel.ai.error.${name10}`; + var symbol11 = Symbol.for(marker11); + var _a11, _b11; + var NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) { + constructor({ errorName = name10, modelId, modelType, message = `No such ${modelType}: ${modelId}` }){ + super({ + name: errorName, + message + }); + this[_a11] = true; + this.modelId = modelId; + this.modelType = modelType; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker11); + } + }; + var name11 = "AI_TooManyEmbeddingValuesForCallError"; + var marker12 = `vercel.ai.error.${name11}`; + var symbol12 = Symbol.for(marker12); + var _a12, _b12; + var TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) { + constructor(options1){ + super({ + name: name11, + message: `Too many values for a single embedding call. The ${options1.provider} model "${options1.modelId}" can only embed up to ${options1.maxEmbeddingsPerCall} values per call, but ${options1.values.length} values were provided.` + }); + this[_a12] = true; + this.provider = options1.provider; + this.modelId = options1.modelId; + this.maxEmbeddingsPerCall = options1.maxEmbeddingsPerCall; + this.values = options1.values; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker12); + } + }; + var name12 = "AI_TypeValidationError"; + var marker13 = `vercel.ai.error.${name12}`; + var symbol13 = Symbol.for(marker13); + var _a13, _b13; + var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) { + constructor({ value: value1, cause, context }){ + let contextPrefix = "Type validation failed"; + if (null == context ? void 0 : context.field) contextPrefix += ` for ${context.field}`; + if ((null == context ? void 0 : context.entityName) || (null == context ? void 0 : context.entityId)) { + contextPrefix += " ("; + const parts = []; + if (context.entityName) parts.push(context.entityName); + if (context.entityId) parts.push(`id: "${context.entityId}"`); + contextPrefix += parts.join(", "); + contextPrefix += ")"; + } + super({ + name: name12, + message: `${contextPrefix}: Value: ${JSON.stringify(value1)}. +Error message: ${getErrorMessage(cause)}`, + cause + }); + this[_a13] = true; + this.value = value1; + this.context = context; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker13); + } + static wrap({ value: value1, cause, context }) { + var _a15, _b15, _c; + if (_TypeValidationError.isInstance(cause) && cause.value === value1 && (null == (_a15 = cause.context) ? void 0 : _a15.field) === (null == context ? void 0 : context.field) && (null == (_b15 = cause.context) ? void 0 : _b15.entityName) === (null == context ? void 0 : context.entityName) && (null == (_c = cause.context) ? void 0 : _c.entityId) === (null == context ? void 0 : context.entityId)) return cause; + return new _TypeValidationError({ + value: value1, + cause, + context + }); + } + }; + var name13 = "AI_UnsupportedFunctionalityError"; + var marker14 = `vercel.ai.error.${name13}`; + var symbol14 = Symbol.for(marker14); + var _a14, _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); + } + }; + Object.freeze({ + status: "aborted" + }); + function $constructor(name, initializer, params) { + function init(inst, def) { + if (!inst._zod) Object.defineProperty(inst, "_zod", { + value: { + def, + constr: _1, + traits: new Set() + }, + enumerable: false + }); + if (inst._zod.traits.has(name)) return; + inst._zod.traits.add(name); + initializer(inst, def); + const proto = _1.prototype; + const keys = Object.keys(proto); + for(let i = 0; i < keys.length; i++){ + const k = keys[i]; + if (!(k in inst)) inst[k] = proto[k].bind(inst); } - console.log(`ā„¹ļø Push event detected but not to target branch (${targetBranch})`); - console.log(` Current ref: ${ref}`); } - return false; + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { + value: name + }); + function _1(def) { + var _a; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a = inst._zod).deferred ?? (_a.deferred = []); + for (const fn of inst._zod.deferred)fn(); + return inst; + } + Object.defineProperty(_1, "init", { + value: init + }); + Object.defineProperty(_1, Symbol.hasInstance, { + value: (inst)=>{ + if (params?.Parent && inst instanceof params.Parent) return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_1, "name", { + value: name + }); + return _1; } - function isWorkflowDispatchEvent() { - const { context } = __webpack_require__("./node_modules/.pnpm/@actions+github@4.0.0/node_modules/@actions/github/lib/github.js"); - const isDispatch = 'workflow_dispatch' === context.eventName; - if (isDispatch) { - console.log(`šŸ”§ Detected workflow_dispatch event`); - console.log(" This is a manually triggered workflow"); - return true; + Symbol("zod_brand"); + class $ZodAsyncError extends Error { + constructor(){ + super("Encountered Promise during synchronous parse. Use .parseAsync() instead."); } - return false; } - function runRsdoctorViaNode(requirePath, args = []) { - const nodeExec = process.execPath; - console.log('process.execPath =', nodeExec); - console.log('Running:', nodeExec, requirePath, args.join(' ')); - const r = (0, external_child_process_.spawnSync)(nodeExec, [ - requirePath, - ...args - ], { - stdio: 'inherit' - }); - if (r.error) throw r.error; - if (0 !== r.status) throw new Error(`rsdoctor exited with code ${r.status}`); + class $ZodEncodeError extends Error { + constructor(name){ + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } } - function extractProjectName(filePath) { - const relativePath = external_path_default().relative(process.cwd(), filePath); - const pathParts = relativePath.split(external_path_default().sep); - const buildOutputDirs = [ - 'dist', - '.rsdoctor', - 'output', - '.next', - 'public' - ]; - const monorepoPatterns = [ - 'packages', - 'apps', - 'projects', - 'libs', - 'modules', - 'examples' - ]; - const patternIndex = pathParts.findIndex((part)=>monorepoPatterns.includes(part)); - if (patternIndex >= 0 && patternIndex + 1 < pathParts.length) { - let packageName = null; - let packageNameIndex = -1; - for(let i = patternIndex + 1; i < pathParts.length; i++)if (!buildOutputDirs.includes(pathParts[i])) { - packageName = pathParts[i]; - packageNameIndex = i; - break; - } - if (packageName) { - for(let i = pathParts.length - 2; i > packageNameIndex; i--){ - const part = pathParts[i]; - if (!buildOutputDirs.includes(part)) return `${packageName}/${part}`; + const globalConfig = {}; + function core_config(newConfig) { + if (newConfig) Object.assign(globalConfig, newConfig); + return globalConfig; + } + function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v)=>"number" == typeof v); + const values = Object.entries(entries).filter(([k, _1])=>-1 === numericValues.indexOf(+k)).map(([_1, v])=>v); + return values; + } + function util_joinValues(array, separator = "|") { + return array.map((val)=>stringifyPrimitive(val)).join(separator); + } + function jsonStringifyReplacer(_1, value1) { + if ("bigint" == typeof value1) return value1.toString(); + return value1; + } + function cached(getter) { + const set = false; + return { + get value () { + if (!set) { + const value1 = getter(); + Object.defineProperty(this, "value", { + value: value1 + }); + return value1; } - return packageName; + throw new Error("cached value already set"); } + }; + } + function nullish(input) { + return null == input; + } + function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); + } + function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepString = step.toString(); + let stepDecCount = (stepString.split(".")[1] || "").length; + if (0 === stepDecCount && /\d?e-\d?/.test(stepString)) { + const match = stepString.match(/\d?e-(\d?)/); + if (match?.[1]) stepDecCount = Number.parseInt(match[1]); + } + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; + } + const EVALUATING = Symbol("evaluating"); + function defineLazy(object, key, getter) { + let value1; + Object.defineProperty(object, key, { + get () { + if (value1 === EVALUATING) return; + if (void 0 === value1) { + value1 = EVALUATING; + value1 = getter(); + } + return value1; + }, + set (v) { + Object.defineProperty(object, key, { + value: v + }); + }, + configurable: true + }); + } + function assignProp(target, prop, value1) { + Object.defineProperty(target, prop, { + value: value1, + writable: true, + enumerable: true, + configurable: true + }); + } + function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs){ + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); } - for(let i = pathParts.length - 2; i >= 0; i--){ - const part = pathParts[i]; - if (!buildOutputDirs.includes(part)) return part; + return Object.defineProperties({}, mergedDescriptors); + } + function esc(str) { + return JSON.stringify(str); + } + function slugify(input) { + return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); + } + const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args)=>{}; + function util_isObject(data) { + return "object" == typeof data && null !== data && !Array.isArray(data); + } + const util_allowsEval = cached(()=>{ + if ("undefined" != typeof navigator && navigator?.userAgent?.includes("Cloudflare")) return false; + try { + const F = Function; + new F(""); + return true; + } catch (_1) { + return false; } - return pathParts[0] || 'root'; + }); + function isPlainObject(o) { + if (false === util_isObject(o)) return false; + const ctor = o.constructor; + if (void 0 === ctor) return true; + if ("function" != typeof ctor) return true; + const prot = ctor.prototype; + if (false === util_isObject(prot)) return false; + if (false === Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf")) return false; + return true; } - async function processSingleFile(fullPath, currentCommitHash, targetCommitHash, baselineUsedFallback, baselineLatestCommitHash) { - const fileName = external_path_default().basename(fullPath); - const relativePath = external_path_default().relative(process.cwd(), fullPath); - const pathParts = relativePath.split(external_path_default().sep); - const fileNameWithoutExt = external_path_default().parse(fileName).name; - const fileExt = external_path_default().parse(fileName).ext; - const projectName = extractProjectName(fullPath); - console.log(`\nšŸ“¦ Processing project: ${projectName}`); - console.log(` File: ${relativePath}`); - const report = { - projectName, - filePath: relativePath, - current: null, - baseline: null + function shallowClone(o) { + if (isPlainObject(o)) return { + ...o }; - const currentBundleAnalysis = parseRsdoctorData(fullPath); - if (!currentBundleAnalysis) { - console.warn(`āš ļø Failed to parse rsdoctor data from ${fullPath}, skipping...`); - return report; - } - report.current = currentBundleAnalysis; - let baselineJsonPath = null; - let baselinePRs = []; - if (targetCommitHash) try { - console.log(`šŸ“„ Attempting to download baseline for ${projectName}...`); - const downloadResult = await downloadArtifactByCommitHash(targetCommitHash, fileName, fullPath); - baselineJsonPath = external_path_default().join(downloadResult.downloadPath, fileName); - console.log(`šŸ“ Downloaded baseline file path: ${baselineJsonPath}`); - const baselineBundleAnalysis = parseRsdoctorData(baselineJsonPath); - if (baselineBundleAnalysis) { - report.baseline = baselineBundleAnalysis; - report.baselineCommitHash = targetCommitHash; - report.baselineUsedFallback = baselineUsedFallback; - report.baselineLatestCommitHash = baselineLatestCommitHash; - try { - const githubService = new GitHubService(); - baselinePRs = await githubService.findPRsByCommit(targetCommitHash); - if (baselinePRs.length > 0) { - report.baselinePRs = baselinePRs; - console.log(`šŸ“Ž Found ${baselinePRs.length} PR(s) associated with baseline commit ${targetCommitHash}`); - } - } catch (prError) { - console.log(`ā„¹ļø Could not find PRs for baseline commit: ${prError}`); + if (Array.isArray(o)) return [ + ...o + ]; + return o; + } + const propertyKeyTypes = new Set([ + "string", + "number", + "symbol" + ]); + const primitiveTypes = new Set([ + "string", + "number", + "bigint", + "boolean", + "symbol", + "undefined" + ]); + function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) cl._zod.parent = inst; + return cl; + } + function normalizeParams(_params) { + const params = _params; + if (!params) return {}; + if ("string" == typeof params) return { + error: ()=>params + }; + if (params?.message !== void 0) { + if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if ("string" == typeof params.error) return { + ...params, + error: ()=>params.error + }; + return params; + } + function stringifyPrimitive(value1) { + if ("bigint" == typeof value1) return value1.toString() + "n"; + if ("string" == typeof value1) return `"${value1}"`; + return `${value1}`; + } + function optionalKeys(shape) { + return Object.keys(shape).filter((k)=>"optional" === shape[k]._zod.optin && "optional" === shape[k]._zod.optout); + } + const NUMBER_FORMAT_RANGES = { + safeint: [ + Number.MIN_SAFE_INTEGER, + Number.MAX_SAFE_INTEGER + ], + int32: [ + -2147483648, + 2147483647 + ], + uint32: [ + 0, + 4294967295 + ], + float32: [ + -3.4028234663852886e+38, + 3.4028234663852886e38 + ], + float64: [ + -Number.MAX_VALUE, + Number.MAX_VALUE + ] + }; + const BIGINT_FORMAT_RANGES = { + int64: [ + /* @__PURE__*/ BigInt("-9223372036854775808"), + /* @__PURE__*/ BigInt("9223372036854775807") + ], + uint64: [ + /* @__PURE__*/ BigInt(0), + /* @__PURE__*/ BigInt("18446744073709551615") + ] + }; + function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) throw new Error(".pick() cannot be used on object schemas containing refinements"); + const def = mergeDefs(schema._zod.def, { + get shape () { + const newShape = {}; + for(const key in mask){ + if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`); + if (mask[key]) newShape[key] = currDef.shape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, + checks: [] + }); + return clone(schema, def); + } + function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) throw new Error(".omit() cannot be used on object schemas containing refinements"); + const def = mergeDefs(schema._zod.def, { + get shape () { + const newShape = { + ...schema._zod.def.shape + }; + for(const key in mask){ + if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`); + if (mask[key]) delete newShape[key]; } - console.log(`āœ… Successfully downloaded and parsed baseline for ${projectName}`); + assignProp(this, "shape", newShape); + return newShape; + }, + checks: [] + }); + return clone(schema, def); + } + function extend(schema, shape) { + if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object"); + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + const existingShape = schema._zod.def.shape; + for(const key in shape)if (void 0 !== Object.getOwnPropertyDescriptor(existingShape, key)) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + const def = mergeDefs(schema._zod.def, { + get shape () { + const _shape = { + ...schema._zod.def.shape, + ...shape + }; + assignProp(this, "shape", _shape); + return _shape; } - } catch (downloadError) { - console.log(`āŒ Failed to download baseline for ${projectName}: ${downloadError}`); - console.log(`ā„¹ļø No baseline data found for ${projectName} - skipping bundle diff for this project`); - baselineJsonPath = null; - } - if (report.baseline && baselineJsonPath) try { - const tempOutDir = process.cwd(); - pathParts.join('-'); - console.log(`šŸ” Looking for target artifact: ${pathParts.join('-')}-${fileNameWithoutExt}-${targetCommitHash}${fileExt}`); - try { - const cliEntry = require.resolve('@rsdoctor/cli', { - paths: [ - process.cwd() - ] - }); - const binCliEntry = external_path_default().join(external_path_default().dirname(external_path_default().dirname(cliEntry)), 'bin', 'rsdoctor'); - console.log(`šŸ” Found rsdoctor CLI at: ${binCliEntry}`); - runRsdoctorViaNode(binCliEntry, [ - 'bundle-diff', - '--html', - `--baseline=${baselineJsonPath}`, - `--current=${fullPath}` - ]); - } catch (e) { - console.log(`āš ļø rsdoctor CLI not found in node_modules: ${e}`); - try { - const shellCmd = `npx @rsdoctor/cli bundle-diff --html --baseline="${baselineJsonPath}" --current="${fullPath}"`; - console.log(`šŸ› ļø Running rsdoctor via npx: ${shellCmd}`); - await execFileAsync('sh', [ - '-c', - shellCmd - ], { - cwd: tempOutDir + }); + return clone(schema, def); + } + function safeExtend(schema, shape) { + if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object"); + const def = mergeDefs(schema._zod.def, { + get shape () { + const _shape = { + ...schema._zod.def.shape, + ...shape + }; + assignProp(this, "shape", _shape); + return _shape; + } + }); + return clone(schema, def); + } + function merge(a, b) { + const def = mergeDefs(a._zod.def, { + get shape () { + const _shape = { + ...a._zod.def.shape, + ...b._zod.def.shape + }; + assignProp(this, "shape", _shape); + return _shape; + }, + get catchall () { + return b._zod.def.catchall; + }, + checks: [] + }); + return clone(a, def); + } + function partial(Class, schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) throw new Error(".partial() cannot be used on object schemas containing refinements"); + const def = mergeDefs(schema._zod.def, { + get shape () { + const oldShape = schema._zod.def.shape; + const shape = { + ...oldShape + }; + if (mask) for(const key in mask){ + if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`); + if (mask[key]) shape[key] = Class ? new Class({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + else for(const key in oldShape)shape[key] = Class ? new Class({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + assignProp(this, "shape", shape); + return shape; + }, + checks: [] + }); + return clone(schema, def); + } + function util_required(Class, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape () { + const oldShape = schema._zod.def.shape; + const shape = { + ...oldShape + }; + if (mask) for(const key in mask){ + if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`); + if (mask[key]) shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key] }); - } catch (npxError) { - console.log(`āš ļø npx approach also failed: ${npxError}`); } + else for(const key in oldShape)shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key] + }); + assignProp(this, "shape", shape); + return shape; } - const safeProjectName = projectName.replace(/\//g, '-'); - const diffHtmlPath = external_path_default().join(tempOutDir, `rsdoctor-diff-${safeProjectName}.html`); - const defaultDiffPath = external_path_default().join(tempOutDir, 'rsdoctor-diff.html'); - if (external_fs_.existsSync(defaultDiffPath)) try { - await external_fs_.promises.rename(defaultDiffPath, diffHtmlPath); - } catch (e) { - report.diffHtmlPath = defaultDiffPath; - } - if (!report.diffHtmlPath) report.diffHtmlPath = external_fs_.existsSync(diffHtmlPath) ? diffHtmlPath : defaultDiffPath; - if (external_fs_.existsSync(report.diffHtmlPath)) try { - const uploadRes = await uploadArtifact(report.diffHtmlPath, currentCommitHash); - if ('number' == typeof uploadRes.id) { - report.diffHtmlArtifactId = uploadRes.id; - console.log(`āœ… Uploaded bundle diff HTML for ${projectName}, artifact id: ${uploadRes.id}`); + }); + return clone(schema, def); + } + function aborted(x, startIndex = 0) { + if (true === x.aborted) return true; + for(let i = startIndex; i < x.issues.length; i++)if (x.issues[i]?.continue !== true) return true; + return false; + } + function prefixIssues(path, issues) { + return issues.map((iss)=>{ + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); + } + function unwrapMessage(message) { + return "string" == typeof message ? message : message?.message; + } + function finalizeIssue(iss, ctx, config) { + const full = { + ...iss, + path: iss.path ?? [] + }; + if (!iss.message) { + const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input"; + full.message = message; + } + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) delete full.input; + return full; + } + function getSizableOrigin(input) { + if (input instanceof Set) return "set"; + if (input instanceof Map) return "map"; + if (input instanceof File) return "file"; + return "unknown"; + } + function getLengthableOrigin(input) { + if (Array.isArray(input)) return "array"; + if ("string" == typeof input) return "string"; + return "unknown"; + } + function util_parsedType(data) { + const t = typeof data; + switch(t){ + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "object": + { + if (null === data) return "null"; + if (Array.isArray(data)) return "array"; + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) return obj.constructor.name; } - } catch (e) { - console.warn(`āš ļø Failed to upload diff html for ${projectName}: ${e}`); - } - } catch (e) { - console.warn(`āš ļø rsdoctor bundle-diff failed for ${projectName}: ${e}`); } - return report; + return t; } - (async ()=>{ - try { - const githubService = new GitHubService(); - const filePathPattern = (0, core.getInput)('file_path'); - if (!filePathPattern) throw new Error('file_path is required'); - const matchedFiles = await out_default()(filePathPattern, { - cwd: process.cwd(), - absolute: true, - onlyFiles: true + function util_issue(...args) { + const [iss, input, inst] = args; + if ("string" == typeof iss) return { + message: iss, + code: "custom", + input, + inst + }; + return { + ...iss + }; + } + const errors_initializer = (inst, def)=>{ + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false + }); + inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); + Object.defineProperty(inst, "toString", { + value: ()=>inst.message, + enumerable: false + }); + }; + const $ZodError = $constructor("$ZodError", errors_initializer); + const $ZodRealError = $constructor("$ZodError", errors_initializer, { + Parent: Error + }); + function flattenError(error, mapper = (issue)=>issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues)if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } else formErrors.push(mapper(sub)); + return { + formErrors, + fieldErrors + }; + } + function formatError(error, mapper = (issue)=>issue.message) { + const fieldErrors = { + _errors: [] + }; + const processError = (error)=>{ + for (const issue of error.issues)if ("invalid_union" === issue.code && issue.errors.length) issue.errors.map((issues)=>processError({ + issues + })); + else if ("invalid_key" === issue.code) processError({ + issues: issue.issues }); - if (0 === matchedFiles.length) throw new Error(`No files found matching pattern: ${filePathPattern}`); - console.log(`šŸ“ Found ${matchedFiles.length} file(s) matching pattern: ${filePathPattern}`); - matchedFiles.forEach((file, index)=>{ - console.log(` ${index + 1}. ${file}`); + else if ("invalid_element" === issue.code) processError({ + issues: issue.issues }); - const currentCommitHash = githubService.getCurrentCommitHash(); - console.log(`Current commit hash: ${currentCommitHash}`); - let targetCommitHash = null; - let baselineUsedFallback = false; - let baselineLatestCommitHash; - const isPush = isPushEvent(); - const isPR = isPullRequestEvent(); - const isDispatch = isWorkflowDispatchEvent(); - if (isPR || isDispatch) try { - console.log('šŸ” Getting target branch commit hash...'); - const commitInfo = await githubService.getTargetBranchLatestCommit(); - targetCommitHash = commitInfo.commitHash; - baselineUsedFallback = commitInfo.usedFallbackCommit; - baselineLatestCommitHash = commitInfo.latestCommitHash; - console.log(`āœ… Target branch commit hash: ${targetCommitHash}`); - if (baselineUsedFallback && baselineLatestCommitHash) console.log(`āš ļø Using fallback commit: ${targetCommitHash} (latest: ${baselineLatestCommitHash})`); - } catch (error) { - console.error(`āŒ Failed to get target branch commit: ${error}`); - console.log('šŸ“ No baseline data available for comparison'); - } - const projectReports = []; - if (isPush) { - console.log('šŸ”„ Detected push event to target branch - uploading artifacts'); - for (const fullPath of matchedFiles){ - const uploadResponse = await uploadArtifact(fullPath, currentCommitHash); - if ('number' != typeof uploadResponse.id) console.warn(`āš ļø Artifact upload failed for ${fullPath}`); - else console.log(`āœ… Successfully uploaded artifact with ID: ${uploadResponse.id}`); - const currentBundleAnalysis = parseRsdoctorData(fullPath); - if (currentBundleAnalysis) { - const projectName = extractProjectName(fullPath); - const relativePath = external_path_default().relative(process.cwd(), fullPath); - projectReports.push({ - projectName, - filePath: relativePath, - current: currentBundleAnalysis, - baseline: null - }); - } else { - const currentSizeData = loadSizeData(fullPath); - if (currentSizeData) await generateSizeReport(currentSizeData); - } - } - if (projectReports.length > 0) if (1 === projectReports.length) { - const report = projectReports[0]; - if (report.current) await generateBundleAnalysisReport(report.current, void 0, true, null, void 0); - } else { - await core.summary.addHeading('šŸ“¦ Monorepo Bundle Analysis', 2); - for (const report of projectReports)if (report.current) { - await core.summary.addHeading(`šŸ“ ${report.projectName}`, 3); - await core.summary.addRaw(`**Path:** \`${report.filePath}\``); - await generateBundleAnalysisReport(report.current, void 0, false, null, void 0); - } - await core.summary.write(); - } - } else if (isDispatch || isPR) { - if (isDispatch) console.log('šŸ”§ Processing workflow_dispatch event - uploading artifacts and comparing with baseline'); - else console.log('šŸ“„ Detected pull request event - processing files'); - for (const fullPath of matchedFiles){ - const report = await processSingleFile(fullPath, currentCommitHash, targetCommitHash, baselineUsedFallback, baselineLatestCommitHash); - projectReports.push(report); - if (isDispatch) { - const uploadResponse = await uploadArtifact(fullPath, currentCommitHash); - if ('number' != typeof uploadResponse.id) console.warn(`āš ļø Artifact upload failed for ${fullPath}`); - else console.log(`āœ… Successfully uploaded artifact with ID: ${uploadResponse.id}`); - } + else if (0 === issue.path.length) fieldErrors._errors.push(mapper(issue)); + else { + let curr = fieldErrors; + let i = 0; + while(i < issue.path.length){ + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (terminal) { + curr[el] = curr[el] || { + _errors: [] + }; + curr[el]._errors.push(mapper(issue)); + } else curr[el] = curr[el] || { + _errors: [] + }; + curr = curr[el]; + i++; } - if (projectReports.length > 0) if (1 === projectReports.length) { - const report = projectReports[0]; - if (report.current) { - if (report.baselineUsedFallback && report.baselineLatestCommitHash) await core.summary.addRaw(`> āš ļø **Note:** The latest commit (\`${report.baselineLatestCommitHash}\`) does not have baseline artifacts. Using commit \`${report.baselineCommitHash}\` for baseline comparison instead. If this seems incorrect, please wait a few minutes and try rerunning the workflow.\n\n`); + } + }; + processError(error); + return fieldErrors; + } + const _parse = (_Err)=>(schema, value1, _ctx, _params)=>{ + const ctx = _ctx ? Object.assign(_ctx, { + async: false + }) : { + async: false + }; + const result = schema._zod.run({ + value: value1, + issues: [] + }, ctx); + if (result instanceof Promise) throw new $ZodAsyncError(); + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss)=>finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, _params?.callee); + throw e; + } + return result.value; + }; + const parse = /* @__PURE__*/ _parse($ZodRealError); + const _parseAsync = (_Err)=>async (schema, value1, _ctx, params)=>{ + const ctx = _ctx ? Object.assign(_ctx, { + async: true + }) : { + async: true + }; + let result = schema._zod.run({ + value: value1, + issues: [] + }, ctx); + if (result instanceof Promise) result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss)=>finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, params?.callee); + throw e; + } + return result.value; + }; + const parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError); + const _safeParse = (_Err)=>(schema, value1, _ctx)=>{ + const ctx = _ctx ? { + ..._ctx, + async: false + } : { + async: false + }; + const result = schema._zod.run({ + value: value1, + issues: [] + }, ctx); + if (result instanceof Promise) throw new $ZodAsyncError(); + return result.issues.length ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss)=>finalizeIssue(iss, ctx, core_config()))) + } : { + success: true, + data: result.value + }; + }; + const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); + const _safeParseAsync = (_Err)=>async (schema, value1, _ctx)=>{ + const ctx = _ctx ? Object.assign(_ctx, { + async: true + }) : { + async: true + }; + let result = schema._zod.run({ + value: value1, + issues: [] + }, ctx); + if (result instanceof Promise) result = await result; + return result.issues.length ? { + success: false, + error: new _Err(result.issues.map((iss)=>finalizeIssue(iss, ctx, core_config()))) + } : { + success: true, + data: result.value + }; + }; + const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); + const _encode = (_Err)=>(schema, value1, _ctx)=>{ + const ctx = _ctx ? Object.assign(_ctx, { + direction: "backward" + }) : { + direction: "backward" + }; + return _parse(_Err)(schema, value1, ctx); + }; + const _decode = (_Err)=>(schema, value1, _ctx)=>_parse(_Err)(schema, value1, _ctx); + const _encodeAsync = (_Err)=>async (schema, value1, _ctx)=>{ + const ctx = _ctx ? Object.assign(_ctx, { + direction: "backward" + }) : { + direction: "backward" + }; + return _parseAsync(_Err)(schema, value1, ctx); + }; + const _decodeAsync = (_Err)=>async (schema, value1, _ctx)=>_parseAsync(_Err)(schema, value1, _ctx); + const _safeEncode = (_Err)=>(schema, value1, _ctx)=>{ + const ctx = _ctx ? Object.assign(_ctx, { + direction: "backward" + }) : { + direction: "backward" + }; + return _safeParse(_Err)(schema, value1, ctx); + }; + const _safeDecode = (_Err)=>(schema, value1, _ctx)=>_safeParse(_Err)(schema, value1, _ctx); + const _safeEncodeAsync = (_Err)=>async (schema, value1, _ctx)=>{ + const ctx = _ctx ? Object.assign(_ctx, { + direction: "backward" + }) : { + direction: "backward" + }; + return _safeParseAsync(_Err)(schema, value1, ctx); + }; + const _safeDecodeAsync = (_Err)=>async (schema, value1, _ctx)=>_safeParseAsync(_Err)(schema, value1, _ctx); + const cuid = /^[cC][^\s-]{8,}$/; + const cuid2 = /^[0-9a-z]+$/; + const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; + const xid = /^[0-9a-vA-V]{20}$/; + const ksuid = /^[A-Za-z0-9]{27}$/; + const nanoid = /^[a-zA-Z0-9_-]{21}$/; + const regexes_duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; + const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; + const uuid = (version)=>{ + if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); + }; + const uuid4 = /*@__PURE__*/ uuid(4); + const uuid6 = /*@__PURE__*/ uuid(6); + const uuid7 = /*@__PURE__*/ uuid(7); + const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; + const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; + const idnEmail = unicodeEmail; + const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + const _emoji = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$"; + function emoji() { + return new RegExp(_emoji, "u"); + } + const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + const regexes_ipv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))$/; + const mac = (delimiter)=>{ + const escapedDelim = escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); + }; + const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; + const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; + const regexes_base64url = /^[A-Za-z0-9_-]*$/; + const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; + const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; + const e164 = /^\+[1-9]\d{6,14}$/; + const dateSource = "(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))"; + const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`); + function timeSource(args) { + const hhmm = "(?:[01]\\d|2[0-3]):[0-5]\\d"; + const regex = "number" == typeof args.precision ? -1 === args.precision ? `${hhmm}` : 0 === args.precision ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; + } + function regexes_time(args) { + return new RegExp(`^${timeSource(args)}$`); + } + function datetime(args) { + const time = timeSource({ + precision: args.precision + }); + const opts = [ + "Z" + ]; + if (args.local) opts.push(""); + if (args.offset) opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"); + const timeRegex = `${time}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); + } + const string = (params)=>{ + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : "[\\s\\S]*"; + return new RegExp(`^${regex}$`); + }; + const bigint = /^-?\d+n?$/; + const integer = /^-?\d+$/; + const regexes_number = /^-?\d+(?:\.\d+)?$/; + const regexes_boolean = /^(?:true|false)$/i; + const _null = /^null$/i; + const _undefined = /^undefined$/i; + const lowercase = /^[^A-Z]*$/; + const uppercase = /^[^a-z]*$/; + const regexes_hex = /^[0-9a-fA-F]*$/; + function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); + } + function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); + } + const md5_hex = /^[0-9a-fA-F]{32}$/; + const md5_base64 = /*@__PURE__*/ fixedBase64(22, "=="); + const md5_base64url = /*@__PURE__*/ fixedBase64url(22); + const sha1_hex = /^[0-9a-fA-F]{40}$/; + const sha1_base64 = /*@__PURE__*/ fixedBase64(27, "="); + const sha1_base64url = /*@__PURE__*/ fixedBase64url(27); + const sha256_hex = /^[0-9a-fA-F]{64}$/; + const sha256_base64 = /*@__PURE__*/ fixedBase64(43, "="); + const sha256_base64url = /*@__PURE__*/ fixedBase64url(43); + const sha384_hex = /^[0-9a-fA-F]{96}$/; + const sha384_base64 = /*@__PURE__*/ fixedBase64(64, ""); + const sha384_base64url = /*@__PURE__*/ fixedBase64url(64); + const sha512_hex = /^[0-9a-fA-F]{128}$/; + const sha512_base64 = /*@__PURE__*/ fixedBase64(86, "=="); + const sha512_base64url = /*@__PURE__*/ fixedBase64url(86); + const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def)=>{ + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); + }); + const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date" + }; + const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def)=>{ + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst)=>{ + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? 1 / 0; + if (def.value < curr) if (def.inclusive) bag.maximum = def.value; + else bag.exclusiveMaximum = def.value; + }); + inst._zod.check = (payload)=>{ + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return; + payload.issues.push({ + origin, + code: "too_big", + maximum: "object" == typeof def.value ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def)=>{ + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst)=>{ + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? -1 / 0; + if (def.value > curr) if (def.inclusive) bag.minimum = def.value; + else bag.exclusiveMinimum = def.value; + }); + inst._zod.check = (payload)=>{ + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return; + payload.issues.push({ + origin, + code: "too_small", + minimum: "object" == typeof def.value ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckMultipleOf = /*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def)=>{ + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst)=>{ + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload)=>{ + if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = "bigint" == typeof payload.value ? payload.value % def.value === BigInt(0) : 0 === floatSafeRemainder(payload.value, def.value); + if (isMultiple) return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def)=>{ + $ZodCheck.init(inst, def); + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst)=>{ + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) bag.pattern = integer; + }); + inst._zod.check = (payload)=>{ + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) return void payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst + }); + if (!Number.isSafeInteger(input)) { + if (input > 0) payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort + }); + else payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort + }); + return; + } + } + if (input < minimum) payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + if (input > maximum) payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckBigIntFormat = /*@__PURE__*/ $constructor("$ZodCheckBigIntFormat", (inst, def)=>{ + $ZodCheck.init(inst, def); + const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst)=>{ + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload)=>{ + const input = payload.value; + if (input < minimum) payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort + }); + if (input > maximum) payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckMaxSize = /*@__PURE__*/ $constructor("$ZodCheckMaxSize", (inst, def)=>{ + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload)=>{ + const val = payload.value; + return !nullish(val) && void 0 !== val.size; + }); + inst._zod.onattach.push((inst)=>{ + const curr = inst._zod.bag.maximum ?? 1 / 0; + if (def.maximum < curr) inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload)=>{ + const input = payload.value; + const size = input.size; + if (size <= def.maximum) return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckMinSize = /*@__PURE__*/ $constructor("$ZodCheckMinSize", (inst, def)=>{ + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload)=>{ + const val = payload.value; + return !nullish(val) && void 0 !== val.size; + }); + inst._zod.onattach.push((inst)=>{ + const curr = inst._zod.bag.minimum ?? -1 / 0; + if (def.minimum > curr) inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload)=>{ + const input = payload.value; + const size = input.size; + if (size >= def.minimum) return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckSizeEquals = /*@__PURE__*/ $constructor("$ZodCheckSizeEquals", (inst, def)=>{ + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload)=>{ + const val = payload.value; + return !nullish(val) && void 0 !== val.size; + }); + inst._zod.onattach.push((inst)=>{ + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload)=>{ + const input = payload.value; + const size = input.size; + if (size === def.size) return; + const tooBig = size > def.size; + payload.issues.push({ + origin: getSizableOrigin(input), + ...tooBig ? { + code: "too_big", + maximum: def.size + } : { + code: "too_small", + minimum: def.size + }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def)=>{ + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload)=>{ + const val = payload.value; + return !nullish(val) && void 0 !== val.length; + }); + inst._zod.onattach.push((inst)=>{ + const curr = inst._zod.bag.maximum ?? 1 / 0; + if (def.maximum < curr) inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload)=>{ + const input = payload.value; + const length = input.length; + if (length <= def.maximum) return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def)=>{ + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload)=>{ + const val = payload.value; + return !nullish(val) && void 0 !== val.length; + }); + inst._zod.onattach.push((inst)=>{ + const curr = inst._zod.bag.minimum ?? -1 / 0; + if (def.minimum > curr) inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload)=>{ + const input = payload.value; + const length = input.length; + if (length >= def.minimum) return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def)=>{ + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload)=>{ + const val = payload.value; + return !nullish(val) && void 0 !== val.length; + }); + inst._zod.onattach.push((inst)=>{ + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload)=>{ + const input = payload.value; + const length = input.length; + if (length === def.length) return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...tooBig ? { + code: "too_big", + maximum: def.length + } : { + code: "too_small", + minimum: def.length + }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def)=>{ + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst)=>{ + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload)=>{ + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...def.pattern ? { + pattern: def.pattern.toString() + } : {}, + inst, + continue: !def.abort + }); + }); + else (_b = inst._zod).check ?? (_b.check = ()=>{}); + }); + const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def)=>{ + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload)=>{ + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def)=>{ + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); + }); + const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def)=>{ + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); + }); + const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def)=>{ + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + const pattern = new RegExp("number" == typeof def.position ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst)=>{ + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload)=>{ + if (payload.value.includes(def.includes, def.position)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def)=>{ + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst)=>{ + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload)=>{ + if (payload.value.startsWith(def.prefix)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def)=>{ + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst)=>{ + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload)=>{ + if (payload.value.endsWith(def.suffix)) return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) payload.issues.push(...prefixIssues(property, result.issues)); + } + const $ZodCheckProperty = /*@__PURE__*/ $constructor("$ZodCheckProperty", (inst, def)=>{ + $ZodCheck.init(inst, def); + inst._zod.check = (payload)=>{ + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [] + }, {}); + if (result instanceof Promise) return result.then((result)=>handleCheckPropertyResult(result, payload, def.property)); + handleCheckPropertyResult(result, payload, def.property); + }; + }); + const $ZodCheckMimeType = /*@__PURE__*/ $constructor("$ZodCheckMimeType", (inst, def)=>{ + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst)=>{ + inst._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload)=>{ + if (mimeSet.has(payload.value.type)) return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def)=>{ + $ZodCheck.init(inst, def); + inst._zod.check = (payload)=>{ + payload.value = def.tx(payload.value); + }; + }); + class Doc { + constructor(args = []){ + this.content = []; + this.indent = 0; + if (this) this.args = args; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if ("function" == typeof arg) { + arg(this, { + execution: "sync" + }); + arg(this, { + execution: "async" + }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x)=>x); + const minIndent = Math.min(...lines.map((x)=>x.length - x.trimStart().length)); + const dedented = lines.map((x)=>x.slice(minIndent)).map((x)=>" ".repeat(2 * this.indent) + x); + for (const line of dedented)this.content.push(line); + } + compile() { + const F = Function; + const args = this?.args; + const content = this?.content ?? [ + "" + ]; + const lines = [ + ...content.map((x)=>` ${x}`) + ]; + return new F(...args, lines.join("\n")); + } + } + const versions_version = { + major: 4, + minor: 3, + patch: 6 + }; + const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def)=>{ + var _a; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = versions_version; + const checks = [ + ...inst._zod.def.checks ?? [] + ]; + if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst); + for (const ch of checks)for (const fn of ch._zod.onattach)fn(inst); + if (0 === checks.length) { + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(()=>{ + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks, ctx)=>{ + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks){ + if (ch._zod.def.when) { + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) continue; + } else if (isAborted) continue; + const currLen = payload.issues.length; + const _1 = ch._zod.check(payload); + if (_1 instanceof Promise && ctx?.async === false) throw new $ZodAsyncError(); + if (asyncResult || _1 instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async ()=>{ + await _1; + const nextLen = payload.issues.length; + if (nextLen === currLen) return; + if (!isAborted) isAborted = aborted(payload, currLen); + }); + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) continue; + if (!isAborted) isAborted = aborted(payload, currLen); + } + } + if (asyncResult) return asyncResult.then(()=>payload); + return payload; + }; + const handleCanaryResult = (canary, payload, ctx)=>{ + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (false === ctx.async) throw new $ZodAsyncError(); + return checkResult.then((checkResult)=>inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx)=>{ + if (ctx.skipChecks) return inst._zod.parse(payload, ctx); + if ("backward" === ctx.direction) { + const canary = inst._zod.parse({ + value: payload.value, + issues: [] + }, { + ...ctx, + skipChecks: true + }); + if (canary instanceof Promise) return canary.then((canary)=>handleCanaryResult(canary, payload, ctx)); + return handleCanaryResult(canary, payload, ctx); + } + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (false === ctx.async) throw new $ZodAsyncError(); + return result.then((result)=>runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } + defineLazy(inst, "~standard", ()=>({ + validate: (value1)=>{ + try { + const r = safeParse(inst, value1); + return r.success ? { + value: r.data + } : { + issues: r.error?.issues + }; + } catch (_1) { + return safeParseAsync(inst, value1).then((r)=>r.success ? { + value: r.data + } : { + issues: r.error?.issues + }); + } + }, + vendor: "zod", + version: 1 + })); + }); + const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.pattern = [ + ...inst?._zod.bag?.patterns ?? [] + ].pop() ?? string(inst._zod.bag); + inst._zod.parse = (payload, _1)=>{ + if (def.coerce) try { + payload.value = String(payload.value); + } catch (_1) {} + if ("string" == typeof payload.value) return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def)=>{ + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); + }); + const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def)=>{ + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); + }); + const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def)=>{ + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8 + }; + const v = versionMap[def.version]; + if (void 0 === v) throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } else def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); + }); + const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def)=>{ + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); + }); + const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def)=>{ + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload)=>{ + try { + const trimmed = payload.value.trim(); + const url = new URL(trimmed); + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url.hostname)) payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + if (def.normalize) payload.value = url.href; + else payload.value = trimmed; + return; + } catch (_1) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def)=>{ + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); + }); + const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def)=>{ + def.pattern ?? (def.pattern = nanoid); + $ZodStringFormat.init(inst, def); + }); + const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def)=>{ + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); + }); + const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def)=>{ + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); + }); + const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def)=>{ + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); + }); + const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def)=>{ + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); + }); + const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def)=>{ + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); + }); + const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def)=>{ + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + }); + const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def)=>{ + def.pattern ?? (def.pattern = date); + $ZodStringFormat.init(inst, def); + }); + const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def)=>{ + def.pattern ?? (def.pattern = regexes_time(def)); + $ZodStringFormat.init(inst, def); + }); + const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def)=>{ + def.pattern ?? (def.pattern = regexes_duration); + $ZodStringFormat.init(inst, def); + }); + const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def)=>{ + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = "ipv4"; + }); + const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def)=>{ + def.pattern ?? (def.pattern = regexes_ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = "ipv6"; + inst._zod.check = (payload)=>{ + try { + new URL(`http://[${payload.value}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + const $ZodMAC = /*@__PURE__*/ $constructor("$ZodMAC", (inst, def)=>{ + def.pattern ?? (def.pattern = mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = "mac"; + }); + const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def)=>{ + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); + }); + const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def)=>{ + def.pattern ?? (def.pattern = cidrv6); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload)=>{ + const parts = payload.value.split("/"); + try { + if (2 !== parts.length) throw new Error(); + const [address, prefix] = parts; + if (!prefix) throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) throw new Error(); + if (prefixNum < 0 || prefixNum > 128) throw new Error(); + new URL(`http://[${address}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + function isValidBase64(data) { + if ("" === data) return true; + if (data.length % 4 !== 0) return false; + try { + atob(data); + return true; + } catch { + return false; + } + } + const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def)=>{ + def.pattern ?? (def.pattern = regexes_base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload)=>{ + if (isValidBase64(payload.value)) return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + function isValidBase64URL(data) { + if (!regexes_base64url.test(data)) return false; + const base64 = data.replace(/[-_]/g, (c)=>"-" === c ? "+" : "/"); + const padded = base64.padEnd(4 * Math.ceil(base64.length / 4), "="); + return isValidBase64(padded); + } + const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def)=>{ + def.pattern ?? (def.pattern = regexes_base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload)=>{ + if (isValidBase64URL(payload.value)) return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def)=>{ + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); + }); + function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (3 !== tokensParts.length) return false; + const [header] = tokensParts; + if (!header) return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; + if (!parsedHeader.alg) return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; + return true; + } catch { + return false; + } + } + const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def)=>{ + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload)=>{ + if (isValidJWT(payload.value, def.alg)) return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + const $ZodCustomStringFormat = /*@__PURE__*/ $constructor("$ZodCustomStringFormat", (inst, def)=>{ + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload)=>{ + if (def.fn(payload.value)) return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? regexes_number; + inst._zod.parse = (payload, _ctx)=>{ + if (def.coerce) try { + payload.value = Number(payload.value); + } catch (_1) {} + const input = payload.value; + if ("number" == typeof input && !Number.isNaN(input) && Number.isFinite(input)) return payload; + const received = "number" == typeof input ? Number.isNaN(input) ? "NaN" : Number.isFinite(input) ? void 0 : "Infinity" : void 0; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...received ? { + received + } : {} + }); + return payload; + }; + }); + const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def)=>{ + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); + }); + const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.pattern = regexes_boolean; + inst._zod.parse = (payload, _ctx)=>{ + if (def.coerce) try { + payload.value = Boolean(payload.value); + } catch (_1) {} + const input = payload.value; + if ("boolean" == typeof input) return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + const $ZodBigInt = /*@__PURE__*/ $constructor("$ZodBigInt", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.pattern = bigint; + inst._zod.parse = (payload, _ctx)=>{ + if (def.coerce) try { + payload.value = BigInt(payload.value); + } catch (_1) {} + if ("bigint" == typeof payload.value) return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + const $ZodBigIntFormat = /*@__PURE__*/ $constructor("$ZodBigIntFormat", (inst, def)=>{ + $ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); + }); + const $ZodSymbol = /*@__PURE__*/ $constructor("$ZodSymbol", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx)=>{ + const input = payload.value; + if ("symbol" == typeof input) return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + const $ZodUndefined = /*@__PURE__*/ $constructor("$ZodUndefined", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.pattern = _undefined; + inst._zod.values = new Set([ + void 0 + ]); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + inst._zod.parse = (payload, _ctx)=>{ + const input = payload.value; + if (void 0 === input) return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = new Set([ + null + ]); + inst._zod.parse = (payload, _ctx)=>{ + const input = payload.value; + if (null === input) return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload)=>payload; + }); + const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload)=>payload; + }); + const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx)=>{ + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + const $ZodVoid = /*@__PURE__*/ $constructor("$ZodVoid", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx)=>{ + const input = payload.value; + if (void 0 === input) return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + const $ZodDate = /*@__PURE__*/ $constructor("$ZodDate", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx)=>{ + if (def.coerce) try { + payload.value = new Date(payload.value); + } catch (_err) {} + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...isDate ? { + received: "Invalid Date" + } : {}, + inst + }); + return payload; + }; + }); + function handleArrayResult(result, final, index) { + if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues)); + final.value[index] = result.value; + } + const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx)=>{ + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for(let i = 0; i < input.length; i++){ + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result)=>handleArrayResult(result, payload, i))); + else handleArrayResult(result, payload, i); + } + if (proms.length) return Promise.all(proms).then(()=>payload); + return payload; + }; + }); + function handlePropertyResult(result, final, key, input, isOptionalOut) { + if (result.issues.length) { + if (isOptionalOut && !(key in input)) return; + final.issues.push(...prefixIssues(key, result.issues)); + } + if (void 0 === result.value) { + if (key in input) final.value[key] = void 0; + } else final.value[key] = result.value; + } + function normalizeDef(def) { + const keys = Object.keys(def.shape); + for (const k of keys)if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + const okeys = optionalKeys(def.shape); + return { + ...def, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; + } + function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const isOptionalOut = "optional" === _catchall.optout; + for(const key in input){ + if (keySet.has(key)) continue; + if ("never" === t) { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ + value: input[key], + issues: [] + }, ctx); + if (r instanceof Promise) proms.push(r.then((r)=>handlePropertyResult(r, payload, key, input, isOptionalOut))); + else handlePropertyResult(r, payload, key, input, isOptionalOut); + } + if (unrecognized.length) payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + if (!proms.length) return payload; + return Promise.all(proms).then(()=>payload); + } + const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def)=>{ + $ZodType.init(inst, def); + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc?.get) { + const sh = def.shape; + Object.defineProperty(def, "shape", { + get: ()=>{ + const newSh = { + ...sh + }; + Object.defineProperty(def, "shape", { + value: newSh + }); + return newSh; + } + }); + } + const _normalized = cached(()=>normalizeDef(def)); + defineLazy(inst._zod, "propValues", ()=>{ + const shape = def.shape; + const propValues = {}; + for(const key in shape){ + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = new Set()); + for (const v of field.values)propValues[key].add(v); + } + } + return propValues; + }); + const isObject = util_isObject; + const catchall = def.catchall; + let value1; + inst._zod.parse = (payload, ctx)=>{ + value1 ?? (value1 = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = {}; + const proms = []; + const shape = value1.shape; + for (const key of value1.keys){ + const el = shape[key]; + const isOptionalOut = "optional" === el._zod.optout; + const r = el._zod.run({ + value: input[key], + issues: [] + }, ctx); + if (r instanceof Promise) proms.push(r.then((r)=>handlePropertyResult(r, payload, key, input, isOptionalOut))); + else handlePropertyResult(r, payload, key, input, isOptionalOut); + } + if (!catchall) return proms.length ? Promise.all(proms).then(()=>payload) : payload; + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; + }); + const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def)=>{ + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = cached(()=>normalizeDef(def)); + const generateFastpass = (shape)=>{ + const doc = new Doc([ + "shape", + "payload", + "ctx" + ]); + const normalized = _normalized.value; + const parseStr = (key)=>{ + const k = esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc.write("const input = payload.value;"); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.keys)ids[key] = `key_${counter++}`; + doc.write("const newResult = {};"); + for (const key of normalized.keys){ + const id = ids[key]; + const k = esc(key); + const schema = shape[key]; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(key)};`); + if (isOptionalOut) doc.write(` + if (${id}.issues.length) { + if (${k} in input) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + else doc.write(` + if (${id}.issues.length) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + doc.write("payload.value = newResult;"); + doc.write("return payload;"); + const fn = doc.compile(); + return (payload, ctx)=>fn(shape, payload, ctx); + }; + let fastpass; + const isObject = util_isObject; + const jit = !globalConfig.jitless; + const allowsEval = util_allowsEval; + const fastEnabled = jit && allowsEval.value; + const catchall = def.catchall; + let value1; + inst._zod.parse = (payload, ctx)=>{ + value1 ?? (value1 = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && true !== ctx.jitless) { + if (!fastpass) fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) return payload; + return handleCatchall([], input, payload, ctx, value1, inst); + } + return superParse(payload, ctx); + }; + }); + function handleUnionResults(results, final, inst, ctx) { + for (const result of results)if (0 === result.issues.length) { + final.value = result.value; + return final; + } + const nonaborted = results.filter((r)=>!aborted(r)); + if (1 === nonaborted.length) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result)=>result.issues.map((iss)=>finalizeIssue(iss, ctx, core_config()))) + }); + return final; + } + const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def)=>{ + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", ()=>def.options.some((o)=>"optional" === o._zod.optin) ? "optional" : void 0); + defineLazy(inst._zod, "optout", ()=>def.options.some((o)=>"optional" === o._zod.optout) ? "optional" : void 0); + defineLazy(inst._zod, "values", ()=>{ + if (def.options.every((o)=>o._zod.values)) return new Set(def.options.flatMap((option)=>Array.from(option._zod.values))); + }); + defineLazy(inst._zod, "pattern", ()=>{ + if (def.options.every((o)=>o._zod.pattern)) { + const patterns = def.options.map((o)=>o._zod.pattern); + return new RegExp(`^(${patterns.map((p)=>cleanRegex(p.source)).join("|")})$`); + } + }); + const single = 1 === def.options.length; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload, ctx)=>{ + if (single) return first(payload, ctx); + let async = false; + const results = []; + for (const option of def.options){ + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (0 === result.issues.length) return result; + results.push(result); + } + } + if (!async) return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results)=>handleUnionResults(results, payload, inst, ctx)); + }; + }); + function handleExclusiveUnionResults(results, final, inst, ctx) { + const successes = results.filter((r)=>0 === r.issues.length); + if (1 === successes.length) { + final.value = successes[0].value; + return final; + } + if (0 === successes.length) final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result)=>result.issues.map((iss)=>finalizeIssue(iss, ctx, core_config()))) + }); + else final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false + }); + return final; + } + const $ZodXor = /*@__PURE__*/ $constructor("$ZodXor", (inst, def)=>{ + $ZodUnion.init(inst, def); + def.inclusive = false; + const single = 1 === def.options.length; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload, ctx)=>{ + if (single) return first(payload, ctx); + let async = false; + const results = []; + for (const option of def.options){ + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else results.push(result); + } + if (!async) return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results)=>handleExclusiveUnionResults(results, payload, inst, ctx)); + }; + }); + const $ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("$ZodDiscriminatedUnion", (inst, def)=>{ + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", ()=>{ + const propValues = {}; + for (const option of def.options){ + const pv = option._zod.propValues; + if (!pv || 0 === Object.keys(pv).length) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)){ + if (!propValues[k]) propValues[k] = new Set(); + for (const val of v)propValues[k].add(val); + } + } + return propValues; + }); + const disc = cached(()=>{ + const opts = def.options; + const map = new Map(); + for (const o of opts){ + const values = o._zod.propValues?.[def.discriminator]; + if (!values || 0 === values.size) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values){ + if (map.has(v)) throw new Error(`Duplicate discriminator value "${String(v)}"`); + map.set(v, o); + } + } + return map; + }); + inst._zod.parse = (payload, ctx)=>{ + const input = payload.value; + if (!util_isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) return opt._zod.run(payload, ctx); + if (def.unionFallback) return _super(payload, ctx); + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + input, + path: [ + def.discriminator + ], + inst + }); + return payload; + }; + }); + const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx)=>{ + const input = payload.value; + const left = def.left._zod.run({ + value: input, + issues: [] + }, ctx); + const right = def.right._zod.run({ + value: input, + issues: [] + }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) return Promise.all([ + left, + right + ]).then(([left, right])=>handleIntersectionResults(payload, left, right)); + return handleIntersectionResults(payload, left, right); + }; + }); + function mergeValues(a, b) { + if (a === b) return { + valid: true, + data: a + }; + if (a instanceof Date && b instanceof Date && +a === +b) return { + valid: true, + data: a + }; + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key)=>-1 !== bKeys.indexOf(key)); + const newObj = { + ...a, + ...b + }; + for (const key of sharedKeys){ + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) return { + valid: false, + mergeErrorPath: [ + key, + ...sharedValue.mergeErrorPath + ] + }; + newObj[key] = sharedValue.data; + } + return { + valid: true, + data: newObj + }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) return { + valid: false, + mergeErrorPath: [] + }; + const newArray = []; + for(let index = 0; index < a.length; index++){ + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) return { + valid: false, + mergeErrorPath: [ + index, + ...sharedValue.mergeErrorPath + ] + }; + newArray.push(sharedValue.data); + } + return { + valid: true, + data: newArray + }; + } + return { + valid: false, + mergeErrorPath: [] + }; + } + function handleIntersectionResults(result, left, right) { + const unrecKeys = new Map(); + let unrecIssue; + for (const iss of left.issues)if ("unrecognized_keys" === iss.code) { + unrecIssue ?? (unrecIssue = iss); + for (const k of iss.keys){ + if (!unrecKeys.has(k)) unrecKeys.set(k, {}); + unrecKeys.get(k).l = true; + } + } else result.issues.push(iss); + for (const iss of right.issues)if ("unrecognized_keys" === iss.code) for (const k of iss.keys){ + if (!unrecKeys.has(k)) unrecKeys.set(k, {}); + unrecKeys.get(k).r = true; + } + else result.issues.push(iss); + const bothKeys = [ + ...unrecKeys + ].filter(([, f])=>f.l && f.r).map(([k])=>k); + if (bothKeys.length && unrecIssue) result.issues.push({ + ...unrecIssue, + keys: bothKeys + }); + if (aborted(result)) return result; + const merged = mergeValues(left.value, right.value); + if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + result.value = merged.data; + return result; + } + const $ZodTuple = /*@__PURE__*/ $constructor("$ZodTuple", (inst, def)=>{ + $ZodType.init(inst, def); + const items = def.items; + inst._zod.parse = (payload, ctx)=>{ + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type" + }); + return payload; + } + payload.value = []; + const proms = []; + const reversedIndex = [ + ...items + ].reverse().findIndex((item)=>"optional" !== item._zod.optin); + const optStart = -1 === reversedIndex ? 0 : items.length - reversedIndex; + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; + if (tooBig || tooSmall) { + payload.issues.push({ + ...tooBig ? { + code: "too_big", + maximum: items.length, + inclusive: true + } : { + code: "too_small", + minimum: items.length + }, + input, + inst, + origin: "array" + }); + return payload; + } + } + let i = -1; + for (const item of items){ + i++; + if (i >= input.length) { + if (i >= optStart) continue; + } + const result = item._zod.run({ + value: input[i], + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result)=>handleTupleResult(result, payload, i))); + else handleTupleResult(result, payload, i); + } + if (def.rest) { + const rest = input.slice(items.length); + for (const el of rest){ + i++; + const result = def.rest._zod.run({ + value: el, + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result)=>handleTupleResult(result, payload, i))); + else handleTupleResult(result, payload, i); + } + } + if (proms.length) return Promise.all(proms).then(()=>payload); + return payload; + }; + }); + function handleTupleResult(result, final, index) { + if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues)); + final.value[index] = result.value; + } + const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx)=>{ + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values) { + payload.value = {}; + const recordKeys = new Set(); + for (const key of values)if ("string" == typeof key || "number" == typeof key || "symbol" == typeof key) { + recordKeys.add("number" == typeof key ? key.toString() : key); + const result = def.valueType._zod.run({ + value: input[key], + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result)=>{ + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[key] = result.value; + })); + else { + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[key] = result.value; + } + } + let unrecognized; + for(const key in input)if (!recordKeys.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + if (unrecognized && unrecognized.length > 0) payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized + }); + } else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)){ + if ("__proto__" === key) continue; + let keyResult = def.keyType._zod.run({ + value: key, + issues: [] + }, ctx); + if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); + const checkNumericKey = "string" == typeof key && regexes_number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ + value: Number(key), + issues: [] + }, ctx); + if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); + if (0 === retryResult.issues.length) keyResult = retryResult; + } + if (keyResult.issues.length) { + if ("loose" === def.mode) payload.value[key] = input[key]; + else payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss)=>finalizeIssue(iss, ctx, core_config())), + input: key, + path: [ + key + ], + inst + }); + continue; + } + const result = def.valueType._zod.run({ + value: input[key], + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result)=>{ + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[keyResult.value] = result.value; + })); + else { + if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); + payload.value[keyResult.value] = result.value; + } + } + } + if (proms.length) return Promise.all(proms).then(()=>payload); + return payload; + }; + }); + const $ZodMap = /*@__PURE__*/ $constructor("$ZodMap", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx)=>{ + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + payload.value = new Map(); + for (const [key, value1] of input){ + const keyResult = def.keyType._zod.run({ + value: key, + issues: [] + }, ctx); + const valueResult = def.valueType._zod.run({ + value: value1, + issues: [] + }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) proms.push(Promise.all([ + keyResult, + valueResult + ]).then(([keyResult, valueResult])=>{ + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); + else handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + if (proms.length) return Promise.all(proms).then(()=>payload); + return payload; + }; + }); + function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) if (propertyKeyTypes.has(typeof key)) final.issues.push(...prefixIssues(key, keyResult.issues)); + else final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss)=>finalizeIssue(iss, ctx, core_config())) + }); + if (valueResult.issues.length) if (propertyKeyTypes.has(typeof key)) final.issues.push(...prefixIssues(key, valueResult.issues)); + else final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss)=>finalizeIssue(iss, ctx, core_config())) + }); + final.value.set(keyResult.value, valueResult.value); + } + const $ZodSet = /*@__PURE__*/ $constructor("$ZodSet", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx)=>{ + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type" + }); + return payload; + } + const proms = []; + payload.value = new Set(); + for (const item of input){ + const result = def.valueType._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) proms.push(result.then((result)=>handleSetResult(result, payload))); + else handleSetResult(result, payload); + } + if (proms.length) return Promise.all(proms).then(()=>payload); + return payload; + }; + }); + function handleSetResult(result, final) { + if (result.issues.length) final.issues.push(...result.issues); + final.value.add(result.value); + } + const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def)=>{ + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + inst._zod.pattern = new RegExp(`^(${values.filter((k)=>propertyKeyTypes.has(typeof k)).map((o)=>"string" == typeof o ? escapeRegex(o) : o.toString()).join("|")})$`); + inst._zod.parse = (payload, _ctx)=>{ + const input = payload.value; + if (valuesSet.has(input)) return payload; + payload.issues.push({ + code: "invalid_value", + values, + input, + inst + }); + return payload; + }; + }); + const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def)=>{ + $ZodType.init(inst, def); + if (0 === def.values.length) throw new Error("Cannot create literal schema with no valid values"); + const values = new Set(def.values); + inst._zod.values = values; + inst._zod.pattern = new RegExp(`^(${def.values.map((o)=>"string" == typeof o ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); + inst._zod.parse = (payload, _ctx)=>{ + const input = payload.value; + if (values.has(input)) return payload; + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst + }); + return payload; + }; + }); + const $ZodFile = /*@__PURE__*/ $constructor("$ZodFile", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx)=>{ + const input = payload.value; + if (input instanceof File) return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx)=>{ + if ("backward" === ctx.direction) throw new $ZodEncodeError(inst.constructor.name); + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output)=>{ + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) throw new $ZodAsyncError(); + payload.value = _out; + return payload; + }; + }); + function handleOptionalResult(result, input) { + if (result.issues.length && void 0 === input) return { + issues: [], + value: void 0 + }; + return result; + } + const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", ()=>def.innerType._zod.values ? new Set([ + ...def.innerType._zod.values, + void 0 + ]) : void 0); + defineLazy(inst._zod, "pattern", ()=>{ + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx)=>{ + if ("optional" === def.innerType._zod.optin) { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((r)=>handleOptionalResult(r, payload.value)); + return handleOptionalResult(result, payload.value); + } + if (void 0 === payload.value) return payload; + return def.innerType._zod.run(payload, ctx); + }; + }); + const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def)=>{ + $ZodOptional.init(inst, def); + defineLazy(inst._zod, "values", ()=>def.innerType._zod.values); + defineLazy(inst._zod, "pattern", ()=>def.innerType._zod.pattern); + inst._zod.parse = (payload, ctx)=>def.innerType._zod.run(payload, ctx); + }); + const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def)=>{ + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", ()=>def.innerType._zod.optin); + defineLazy(inst._zod, "optout", ()=>def.innerType._zod.optout); + defineLazy(inst._zod, "pattern", ()=>{ + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazy(inst._zod, "values", ()=>def.innerType._zod.values ? new Set([ + ...def.innerType._zod.values, + null + ]) : void 0); + inst._zod.parse = (payload, ctx)=>{ + if (null === payload.value) return payload; + return def.innerType._zod.run(payload, ctx); + }; + }); + const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", ()=>def.innerType._zod.values); + inst._zod.parse = (payload, ctx)=>{ + if ("backward" === ctx.direction) return def.innerType._zod.run(payload, ctx); + if (void 0 === payload.value) { + payload.value = def.defaultValue; + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((result)=>handleDefaultResult(result, def)); + return handleDefaultResult(result, def); + }; + }); + function handleDefaultResult(payload, def) { + if (void 0 === payload.value) payload.value = def.defaultValue; + return payload; + } + const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", ()=>def.innerType._zod.values); + inst._zod.parse = (payload, ctx)=>{ + if ("backward" === ctx.direction) return def.innerType._zod.run(payload, ctx); + if (void 0 === payload.value) payload.value = def.defaultValue; + return def.innerType._zod.run(payload, ctx); + }; + }); + const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def)=>{ + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", ()=>{ + const v = def.innerType._zod.values; + return v ? new Set([ + ...v + ].filter((x)=>void 0 !== x)) : void 0; + }); + inst._zod.parse = (payload, ctx)=>{ + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((result)=>handleNonOptionalResult(result, inst)); + return handleNonOptionalResult(result, inst); + }; + }); + function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && void 0 === payload.value) payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst + }); + return payload; + } + const $ZodSuccess = /*@__PURE__*/ $constructor("$ZodSuccess", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx)=>{ + if ("backward" === ctx.direction) throw new $ZodEncodeError("ZodSuccess"); + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((result)=>{ + payload.value = 0 === result.issues.length; + return payload; + }); + payload.value = 0 === result.issues.length; + return payload; + }; + }); + const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def)=>{ + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", ()=>def.innerType._zod.optin); + defineLazy(inst._zod, "optout", ()=>def.innerType._zod.optout); + defineLazy(inst._zod, "values", ()=>def.innerType._zod.values); + inst._zod.parse = (payload, ctx)=>{ + if ("backward" === ctx.direction) return def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then((result)=>{ + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss)=>finalizeIssue(iss, ctx, core_config())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; + }); + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss)=>finalizeIssue(iss, ctx, core_config())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; + }; + }); + const $ZodNaN = /*@__PURE__*/ $constructor("$ZodNaN", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx)=>{ + if ("number" != typeof payload.value || !Number.isNaN(payload.value)) payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type" + }); + return payload; + }; + }); + const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def)=>{ + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", ()=>def.in._zod.values); + defineLazy(inst._zod, "optin", ()=>def.in._zod.optin); + defineLazy(inst._zod, "optout", ()=>def.out._zod.optout); + defineLazy(inst._zod, "propValues", ()=>def.in._zod.propValues); + inst._zod.parse = (payload, ctx)=>{ + if ("backward" === ctx.direction) { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) return right.then((right)=>handlePipeResult(right, def.in, ctx)); + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) return left.then((left)=>handlePipeResult(left, def.out, ctx)); + return handlePipeResult(left, def.out, ctx); + }; + }); + function handlePipeResult(left, next, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return next._zod.run({ + value: left.value, + issues: left.issues + }, ctx); + } + const $ZodCodec = /*@__PURE__*/ $constructor("$ZodCodec", (inst, def)=>{ + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", ()=>def.in._zod.values); + defineLazy(inst._zod, "optin", ()=>def.in._zod.optin); + defineLazy(inst._zod, "optout", ()=>def.out._zod.optout); + defineLazy(inst._zod, "propValues", ()=>def.in._zod.propValues); + inst._zod.parse = (payload, ctx)=>{ + const direction = ctx.direction || "forward"; + if ("forward" === direction) { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) return left.then((left)=>handleCodecAResult(left, def, ctx)); + return handleCodecAResult(left, def, ctx); + } + { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) return right.then((right)=>handleCodecAResult(right, def, ctx)); + return handleCodecAResult(right, def, ctx); + } + }; + }); + function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if ("forward" === direction) { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) return transformed.then((value1)=>handleCodecTxResult(result, value1, def.out, ctx)); + return handleCodecTxResult(result, transformed, def.out, ctx); + } + { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) return transformed.then((value1)=>handleCodecTxResult(result, value1, def.in, ctx)); + return handleCodecTxResult(result, transformed, def.in, ctx); + } + } + function handleCodecTxResult(left, value1, nextSchema, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ + value: value1, + issues: left.issues + }, ctx); + } + const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def)=>{ + $ZodType.init(inst, def); + defineLazy(inst._zod, "propValues", ()=>def.innerType._zod.propValues); + defineLazy(inst._zod, "values", ()=>def.innerType._zod.values); + defineLazy(inst._zod, "optin", ()=>def.innerType?._zod?.optin); + defineLazy(inst._zod, "optout", ()=>def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx)=>{ + if ("backward" === ctx.direction) return def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) return result.then(handleReadonlyResult); + return handleReadonlyResult(result); + }; + }); + function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; + } + const $ZodTemplateLiteral = /*@__PURE__*/ $constructor("$ZodTemplateLiteral", (inst, def)=>{ + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts)if ("object" == typeof part && null !== part) { + if (!part._zod.pattern) throw new Error(`Invalid template literal part, no pattern found: ${[ + ...part._zod.traits + ].shift()}`); + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } else if (null === part || primitiveTypes.has(typeof part)) regexParts.push(escapeRegex(`${part}`)); + else throw new Error(`Invalid template literal part: ${part}`); + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx)=>{ + if ("string" != typeof payload.value) { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type" + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source + }); + return payload; + }; + }); + const $ZodFunction = /*@__PURE__*/ $constructor("$ZodFunction", (inst, def)=>{ + $ZodType.init(inst, def); + inst._def = def; + inst._zod.def = def; + inst.implement = (func)=>{ + if ("function" != typeof func) throw new Error("implement() must be called with a function"); + return function(...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) return parse(inst._def.output, result); + return result; + }; + }; + inst.implementAsync = (func)=>{ + if ("function" != typeof func) throw new Error("implementAsync() must be called with a function"); + return async function(...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) return await parseAsync(inst._def.output, result); + return result; + }; + }; + inst._zod.parse = (payload, _ctx)=>{ + if ("function" != typeof payload.value) { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst + }); + return payload; + } + const hasPromiseOutput = inst._def.output && "promise" === inst._def.output._zod.def.type; + if (hasPromiseOutput) payload.value = inst.implementAsync(payload.value); + else payload.value = inst.implement(payload.value); + return payload; + }; + inst.input = (...args)=>{ + const F = inst.constructor; + if (Array.isArray(args[0])) return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1] + }), + output: inst._def.output + }); + return new F({ + type: "function", + input: args[0], + output: inst._def.output + }); + }; + inst.output = (output)=>{ + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output + }); + }; + return inst; + }); + const $ZodPromise = /*@__PURE__*/ $constructor("$ZodPromise", (inst, def)=>{ + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx)=>Promise.resolve(payload.value).then((inner)=>def.innerType._zod.run({ + value: inner, + issues: [] + }, ctx)); + }); + const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def)=>{ + $ZodType.init(inst, def); + defineLazy(inst._zod, "innerType", ()=>def.getter()); + defineLazy(inst._zod, "pattern", ()=>inst._zod.innerType?._zod?.pattern); + defineLazy(inst._zod, "propValues", ()=>inst._zod.innerType?._zod?.propValues); + defineLazy(inst._zod, "optin", ()=>inst._zod.innerType?._zod?.optin ?? void 0); + defineLazy(inst._zod, "optout", ()=>inst._zod.innerType?._zod?.optout ?? void 0); + inst._zod.parse = (payload, ctx)=>{ + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; + }); + const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def)=>{ + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _1)=>payload; + inst._zod.check = (payload)=>{ + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) return r.then((r)=>handleRefineResult(r, payload, input, inst)); + handleRefineResult(r, payload, input, inst); + }; + }); + function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + path: [ + ...inst._zod.def.path ?? [] + ], + continue: !inst._zod.def.abort + }; + if (inst._zod.def.params) _iss.params = inst._zod.def.params; + payload.issues.push(util_issue(_iss)); + } + } + const en_error = ()=>{ + const Sizable = { + string: { + unit: "characters", + verb: "to have" + }, + file: { + unit: "bytes", + verb: "to have" + }, + array: { + unit: "items", + verb: "to have" + }, + set: { + unit: "items", + verb: "to have" + }, + map: { + unit: "entries", + verb: "to have" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue)=>{ + switch(issue.code){ + case "invalid_type": + { + const expected = TypeDictionary[issue.expected] ?? issue.expected; + const receivedType = util_parsedType(issue.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (1 === issue.values.length) return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${util_joinValues(issue.values, "|")}`; + case "too_big": + { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": + { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": + { + const _issue = issue; + if ("starts_with" === _issue.format) return `Invalid string: must start with "${_issue.prefix}"`; + if ("ends_with" === _issue.format) return `Invalid string: must end with "${_issue.suffix}"`; + if ("includes" === _issue.format) return `Invalid string: must include "${_issue.includes}"`; + if ("regex" === _issue.format) return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${util_joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return "Invalid input"; + } + }; + }; + function en() { + return { + localeError: en_error() + }; + } + var registries_a; + Symbol("ZodOutput"); + Symbol("ZodInput"); + class $ZodRegistry { + constructor(){ + this._map = new WeakMap(); + this._idmap = new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && "object" == typeof meta && "id" in meta) this._idmap.set(meta.id, schema); + return this; + } + clear() { + this._map = new WeakMap(); + this._idmap = new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && "object" == typeof meta && "id" in meta) this._idmap.delete(meta.id); + this._map.delete(schema); + return this; + } + get(schema) { + const p = schema._zod.parent; + if (p) { + const pm = { + ...this.get(p) ?? {} + }; + delete pm.id; + const f = { + ...pm, + ...this._map.get(schema) + }; + return Object.keys(f).length ? f : void 0; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } + } + function registries_registry() { + return new $ZodRegistry(); + } + (registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); + const globalRegistry = globalThis.__zod_globalRegistry; + function _string(Class, params) { + return new Class({ + type: "string", + ...normalizeParams(params) + }); + } + function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); + } + function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); + } + function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) + }); + } + function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function api_emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _mac(Class, params) { + return new Class({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); + } + function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); + } + function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); + } + function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); + } + function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...normalizeParams(params) + }); + } + function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params) + }); + } + function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params) + }); + } + function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...normalizeParams(params) + }); + } + function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...normalizeParams(params) + }); + } + function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...normalizeParams(params) + }); + } + function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...normalizeParams(params) + }); + } + function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...normalizeParams(params) + }); + } + function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...normalizeParams(params) + }); + } + function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...normalizeParams(params) + }); + } + function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...normalizeParams(params) + }); + } + function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...normalizeParams(params) + }); + } + function api_undefined(Class, params) { + return new Class({ + type: "undefined", + ...normalizeParams(params) + }); + } + function api_null(Class, params) { + return new Class({ + type: "null", + ...normalizeParams(params) + }); + } + function _any(Class) { + return new Class({ + type: "any" + }); + } + function _unknown(Class) { + return new Class({ + type: "unknown" + }); + } + function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params) + }); + } + function _void(Class, params) { + return new Class({ + type: "void", + ...normalizeParams(params) + }); + } + function _date(Class, params) { + return new Class({ + type: "date", + ...normalizeParams(params) + }); + } + function _nan(Class, params) { + return new Class({ + type: "nan", + ...normalizeParams(params) + }); + } + function _lt(value1, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value: value1, + inclusive: false + }); + } + function _lte(value1, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value: value1, + inclusive: true + }); + } + function _gt(value1, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value: value1, + inclusive: false + }); + } + function _gte(value1, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value: value1, + inclusive: true + }); + } + function _positive(params) { + return _gt(0, params); + } + function _negative(params) { + return _lt(0, params); + } + function _nonpositive(params) { + return _lte(0, params); + } + function _nonnegative(params) { + return _gte(0, params); + } + function _multipleOf(value1, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value: value1 + }); + } + function _maxSize(maximum, params) { + return new $ZodCheckMaxSize({ + check: "max_size", + ...normalizeParams(params), + maximum + }); + } + function _minSize(minimum, params) { + return new $ZodCheckMinSize({ + check: "min_size", + ...normalizeParams(params), + minimum + }); + } + function _size(size, params) { + return new $ZodCheckSizeEquals({ + check: "size_equals", + ...normalizeParams(params), + size + }); + } + function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum + }); + return ch; + } + function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum + }); + } + function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length + }); + } + function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern + }); + } + function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params) + }); + } + function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params) + }); + } + function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes + }); + } + function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix + }); + } + function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix + }); + } + function _property(property, schema, params) { + return new $ZodCheckProperty({ + check: "property", + property, + schema, + ...normalizeParams(params) + }); + } + function _mime(types, params) { + return new $ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...normalizeParams(params) + }); + } + function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); + } + function _normalize(form) { + return _overwrite((input)=>input.normalize(form)); + } + function _trim() { + return _overwrite((input)=>input.trim()); + } + function _toLowerCase() { + return _overwrite((input)=>input.toLowerCase()); + } + function _toUpperCase() { + return _overwrite((input)=>input.toUpperCase()); + } + function _slugify() { + return _overwrite((input)=>slugify(input)); + } + function _array(Class, element, params) { + return new Class({ + type: "array", + element, + ...normalizeParams(params) + }); + } + function _file(Class, params) { + return new Class({ + type: "file", + ...normalizeParams(params) + }); + } + function _custom(Class, fn, _params) { + const norm = normalizeParams(_params); + norm.abort ?? (norm.abort = true); + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm + }); + return schema; + } + function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...normalizeParams(_params) + }); + return schema; + } + function _superRefine(fn) { + const ch = _check((payload)=>{ + payload.addIssue = (issue)=>{ + if ("string" == typeof issue) payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); + else { + const _issue = issue; + if (_issue.fatal) _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(util_issue(_issue)); + } + }; + return fn(payload.value, payload); + }); + return ch; + } + function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params) + }); + ch._zod.check = fn; + return ch; + } + function describe(description) { + const ch = new $ZodCheck({ + check: "describe" + }); + ch._zod.onattach = [ + (inst)=>{ + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { + ...existing, + description + }); + } + ]; + ch._zod.check = ()=>{}; + return ch; + } + function api_meta(metadata) { + const ch = new $ZodCheck({ + check: "meta" + }); + ch._zod.onattach = [ + (inst)=>{ + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { + ...existing, + ...metadata + }); + } + ]; + ch._zod.check = ()=>{}; + return ch; + } + function _stringbool(Classes, _params) { + const params = normalizeParams(_params); + let truthyArray = params.truthy ?? [ + "true", + "1", + "yes", + "on", + "y", + "enabled" + ]; + let falsyArray = params.falsy ?? [ + "false", + "0", + "no", + "off", + "n", + "disabled" + ]; + if ("sensitive" !== params.case) { + truthyArray = truthyArray.map((v)=>"string" == typeof v ? v.toLowerCase() : v); + falsyArray = falsyArray.map((v)=>"string" == typeof v ? v.toLowerCase() : v); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? $ZodCodec; + const _Boolean = Classes.Boolean ?? $ZodBoolean; + const _String = Classes.String ?? $ZodString; + const stringSchema = new _String({ + type: "string", + error: params.error + }); + const booleanSchema = new _Boolean({ + type: "boolean", + error: params.error + }); + const codec = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: (input, payload)=>{ + let data = input; + if ("sensitive" !== params.case) data = data.toLowerCase(); + if (truthySet.has(data)) return true; + if (falsySet.has(data)) return false; + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [ + ...truthySet, + ...falsySet + ], + input: payload.value, + inst: codec, + continue: false + }); + return {}; + }, + reverseTransform: (input, _payload)=>{ + if (true === input) return truthyArray[0] || "true"; + return falsyArray[0] || "false"; + }, + error: params.error + }); + return codec; + } + function _stringFormat(Class, format, fnOrRegex, _params = {}) { + const params = normalizeParams(_params); + const def = { + ...normalizeParams(_params), + check: "string_format", + type: "string", + format, + fn: "function" == typeof fnOrRegex ? fnOrRegex : (val)=>fnOrRegex.test(val), + ...params + }; + if (fnOrRegex instanceof RegExp) def.pattern = fnOrRegex; + const inst = new Class(def); + return inst; + } + function initializeContext(params) { + let target = params?.target ?? "draft-2020-12"; + if ("draft-4" === target) target = "draft-04"; + if ("draft-7" === target) target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (()=>{}), + io: params?.io ?? "output", + counter: 0, + seen: new Map(), + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + external: params?.external ?? void 0 + }; + } + function to_json_schema_process(schema, ctx, _params = { + path: [], + schemaPath: [] + }) { + var _a; + const def = schema._zod.def; + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) seen.cycle = _params.path; + return seen.schema; + } + const result = { + schema: {}, + count: 1, + cycle: void 0, + path: _params.path + }; + ctx.seen.set(schema, result); + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) result.schema = overrideSchema; + else { + const params = { + ..._params, + schemaPath: [ + ..._params.schemaPath, + schema + ], + path: _params.path + }; + if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params); + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + if (!result.ref) result.ref = parent; + to_json_schema_process(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + const meta = ctx.metadataRegistry.get(schema); + if (meta) Object.assign(result.schema, meta); + if ("input" === ctx.io && isTransforming(schema)) { + delete result.schema.examples; + delete result.schema.default; + } + if ("input" === ctx.io && result.schema._prefault) (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + const _result = ctx.seen.get(schema); + return _result.schema; + } + function extractDefs(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + const idToSchema = new Map(); + for (const entry of ctx.seen.entries()){ + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + idToSchema.set(id, entry[0]); + } + } + const makeURI = (entry)=>{ + const defsSegment = "draft-2020-12" === ctx.target ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; + const uriGenerator = ctx.external.uri ?? ((id)=>id); + if (externalId) return { + ref: uriGenerator(externalId) + }; + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; + return { + defId: id, + ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` + }; + } + if (entry[1] === root) return { + ref: "#" + }; + const uriPrefix = "#"; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { + defId, + ref: defUriPrefix + defId + }; + }; + const extractToDef = (entry)=>{ + if (entry[1].schema.$ref) return; + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { + ...seen.schema + }; + if (defId) seen.defId = defId; + const schema = seen.schema; + for(const key in schema)delete schema[key]; + schema.$ref = ref; + }; + if ("throw" === ctx.cycles) for (const entry of ctx.seen.entries()){ + const seen = entry[1]; + if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + for (const entry of ctx.seen.entries()){ + const seen = entry[1]; + if (schema === entry[0]) { + extractToDef(entry); + continue; + } + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if ("ref" === ctx.reused) { + extractToDef(entry); + continue; + } + } + } + } + function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) throw new Error("Unprocessed schema. This is a bug in Zod."); + const flattenRef = (zodSchema)=>{ + const seen = ctx.seen.get(zodSchema); + if (null === seen.ref) return; + const schema = seen.def ?? seen.schema; + const _cached = { + ...schema + }; + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + if (refSchema.$ref && ("draft-07" === ctx.target || "draft-04" === ctx.target || "openapi-3.0" === ctx.target)) { + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } else Object.assign(schema, refSchema); + Object.assign(schema, _cached); + const isParentRef = zodSchema._zod.parent === ref; + if (isParentRef) { + for(const key in schema)if ("$ref" !== key && "allOf" !== key) { + if (!(key in _cached)) delete schema[key]; + } + } + if (refSchema.$ref && refSeen.def) { + for(const key in schema)if ("$ref" !== key && "allOf" !== key) { + if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key]; + } + } + } + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema.$ref = parentSeen.schema.$ref; + if (parentSeen.def) { + for(const key in schema)if ("$ref" !== key && "allOf" !== key) { + if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key]; + } + } + } + } + ctx.override({ + zodSchema: zodSchema, + jsonSchema: schema, + path: seen.path ?? [] + }); + }; + for (const entry of [ + ...ctx.seen.entries() + ].reverse())flattenRef(entry[0]); + const result = {}; + if ("draft-2020-12" === ctx.target) result.$schema = "https://json-schema.org/draft/2020-12/schema"; + else if ("draft-07" === ctx.target) result.$schema = "http://json-schema.org/draft-07/schema#"; + else if ("draft-04" === ctx.target) result.$schema = "http://json-schema.org/draft-04/schema#"; + else ctx.target; + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + Object.assign(result, root.def ?? root.schema); + const defs = ctx.external?.defs ?? {}; + for (const entry of ctx.seen.entries()){ + const seen = entry[1]; + if (seen.def && seen.defId) defs[seen.defId] = seen.def; + } + if (ctx.external) ; + else if (Object.keys(defs).length > 0) if ("draft-2020-12" === ctx.target) result.$defs = defs; + else result.definitions = defs; + try { + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) + } + }, + enumerable: false, + writable: false + }); + return finalized; + } catch (_err) { + throw new Error("Error converting schema to JSON."); + } + } + function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { + seen: new Set() + }; + if (ctx.seen.has(_schema)) return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if ("transform" === def.type) return true; + if ("array" === def.type) return isTransforming(def.element, ctx); + if ("set" === def.type) return isTransforming(def.valueType, ctx); + if ("lazy" === def.type) return isTransforming(def.getter(), ctx); + if ("promise" === def.type || "optional" === def.type || "nonoptional" === def.type || "nullable" === def.type || "readonly" === def.type || "default" === def.type || "prefault" === def.type) return isTransforming(def.innerType, ctx); + if ("intersection" === def.type) return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + if ("record" === def.type || "map" === def.type) return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + if ("pipe" === def.type) return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + if ("object" === def.type) { + for(const key in def.shape)if (isTransforming(def.shape[key], ctx)) return true; + return false; + } + if ("union" === def.type) { + for (const option of def.options)if (isTransforming(option, ctx)) return true; + return false; + } + if ("tuple" === def.type) { + for (const item of def.items)if (isTransforming(item, ctx)) return true; + if (def.rest && isTransforming(def.rest, ctx)) return true; + } + return false; + } + const createToJSONSchemaMethod = (schema, processors = {})=>(params)=>{ + const ctx = initializeContext({ + ...params, + processors + }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); + }; + const createStandardJSONSchemaMethod = (schema, io, processors = {})=>(params)=>{ + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ + ...libraryOptions ?? {}, + target, + io, + processors + }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); + }; + const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + }; + const stringProcessor = (schema, ctx, _json, _params)=>{ + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + if ("number" == typeof minimum) json.minLength = minimum; + if ("number" == typeof maximum) json.maxLength = maximum; + if (format) { + json.format = formatMap[format] ?? format; + if ("" === json.format) delete json.format; + if ("time" === format) delete json.format; + } + if (contentEncoding) json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [ + ...patterns + ]; + if (1 === regexes.length) json.pattern = regexes[0].source; + else if (regexes.length > 1) json.allOf = [ + ...regexes.map((regex)=>({ + ..."draft-07" === ctx.target || "draft-04" === ctx.target || "openapi-3.0" === ctx.target ? { + type: "string" + } : {}, + pattern: regex.source + })) + ]; + } + }; + const numberProcessor = (schema, ctx, _json, _params)=>{ + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if ("string" == typeof format && format.includes("int")) json.type = "integer"; + else json.type = "number"; + if ("number" == typeof exclusiveMinimum) if ("draft-04" === ctx.target || "openapi-3.0" === ctx.target) { + json.minimum = exclusiveMinimum; + json.exclusiveMinimum = true; + } else json.exclusiveMinimum = exclusiveMinimum; + if ("number" == typeof minimum) { + json.minimum = minimum; + if ("number" == typeof exclusiveMinimum && "draft-04" !== ctx.target) if (exclusiveMinimum >= minimum) delete json.minimum; + else delete json.exclusiveMinimum; + } + if ("number" == typeof exclusiveMaximum) if ("draft-04" === ctx.target || "openapi-3.0" === ctx.target) { + json.maximum = exclusiveMaximum; + json.exclusiveMaximum = true; + } else json.exclusiveMaximum = exclusiveMaximum; + if ("number" == typeof maximum) { + json.maximum = maximum; + if ("number" == typeof exclusiveMaximum && "draft-04" !== ctx.target) if (exclusiveMaximum <= maximum) delete json.maximum; + else delete json.exclusiveMaximum; + } + if ("number" == typeof multipleOf) json.multipleOf = multipleOf; + }; + const booleanProcessor = (_schema, _ctx, json, _params)=>{ + json.type = "boolean"; + }; + const bigintProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("BigInt cannot be represented in JSON Schema"); + }; + const symbolProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("Symbols cannot be represented in JSON Schema"); + }; + const nullProcessor = (_schema, ctx, json, _params)=>{ + if ("openapi-3.0" === ctx.target) { + json.type = "string"; + json.nullable = true; + json.enum = [ + null + ]; + } else json.type = "null"; + }; + const undefinedProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("Undefined cannot be represented in JSON Schema"); + }; + const voidProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("Void cannot be represented in JSON Schema"); + }; + const neverProcessor = (_schema, _ctx, json, _params)=>{ + json.not = {}; + }; + const anyProcessor = (_schema, _ctx, _json, _params)=>{}; + const unknownProcessor = (_schema, _ctx, _json, _params)=>{}; + const dateProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("Date cannot be represented in JSON Schema"); + }; + const enumProcessor = (schema, _ctx, json, _params)=>{ + const def = schema._zod.def; + const values = getEnumValues(def.entries); + if (values.every((v)=>"number" == typeof v)) json.type = "number"; + if (values.every((v)=>"string" == typeof v)) json.type = "string"; + json.enum = values; + }; + const literalProcessor = (schema, ctx, json, _params)=>{ + const def = schema._zod.def; + const vals = []; + for (const val of def.values)if (void 0 === val) { + if ("throw" === ctx.unrepresentable) throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else if ("bigint" == typeof val) if ("throw" === ctx.unrepresentable) throw new Error("BigInt literals cannot be represented in JSON Schema"); + else vals.push(Number(val)); + else vals.push(val); + if (0 === vals.length) ; + else if (1 === vals.length) { + const val = vals[0]; + json.type = null === val ? "null" : typeof val; + if ("draft-04" === ctx.target || "openapi-3.0" === ctx.target) json.enum = [ + val + ]; + else json.const = val; + } else { + if (vals.every((v)=>"number" == typeof v)) json.type = "number"; + if (vals.every((v)=>"string" == typeof v)) json.type = "string"; + if (vals.every((v)=>"boolean" == typeof v)) json.type = "boolean"; + if (vals.every((v)=>null === v)) json.type = "null"; + json.enum = vals; + } + }; + const nanProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("NaN cannot be represented in JSON Schema"); + }; + const templateLiteralProcessor = (schema, _ctx, json, _params)=>{ + const _json = json; + const pattern = schema._zod.pattern; + if (!pattern) throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; + }; + const fileProcessor = (schema, _ctx, json, _params)=>{ + const _json = json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (void 0 !== minimum) file.minLength = minimum; + if (void 0 !== maximum) file.maxLength = maximum; + if (mime) if (1 === mime.length) { + file.contentMediaType = mime[0]; + Object.assign(_json, file); + } else { + Object.assign(_json, file); + _json.anyOf = mime.map((m)=>({ + contentMediaType: m + })); + } + else Object.assign(_json, file); + }; + const successProcessor = (_schema, _ctx, json, _params)=>{ + json.type = "boolean"; + }; + const customProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("Custom types cannot be represented in JSON Schema"); + }; + const functionProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("Function types cannot be represented in JSON Schema"); + }; + const transformProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("Transforms cannot be represented in JSON Schema"); + }; + const mapProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("Map cannot be represented in JSON Schema"); + }; + const setProcessor = (_schema, ctx, _json, _params)=>{ + if ("throw" === ctx.unrepresentable) throw new Error("Set cannot be represented in JSON Schema"); + }; + const arrayProcessor = (schema, ctx, _json, params)=>{ + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if ("number" == typeof minimum) json.minItems = minimum; + if ("number" == typeof maximum) json.maxItems = maximum; + json.type = "array"; + json.items = to_json_schema_process(def.element, ctx, { + ...params, + path: [ + ...params.path, + "items" + ] + }); + }; + const objectProcessor = (schema, ctx, _json, params)=>{ + const json = _json; + const def = schema._zod.def; + json.type = "object"; + json.properties = {}; + const shape = def.shape; + for(const key in shape)json.properties[key] = to_json_schema_process(shape[key], ctx, { + ...params, + path: [ + ...params.path, + "properties", + key + ] + }); + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([ + ...allKeys + ].filter((key)=>{ + const v = def.shape[key]._zod; + if ("input" === ctx.io) return void 0 === v.optin; + return void 0 === v.optout; + })); + if (requiredKeys.size > 0) json.required = Array.from(requiredKeys); + if (def.catchall?._zod.def.type === "never") json.additionalProperties = false; + else if (def.catchall) { + if (def.catchall) json.additionalProperties = to_json_schema_process(def.catchall, ctx, { + ...params, + path: [ + ...params.path, + "additionalProperties" + ] + }); + } else if ("output" === ctx.io) json.additionalProperties = false; + }; + const unionProcessor = (schema, ctx, json, params)=>{ + const def = schema._zod.def; + const isExclusive = false === def.inclusive; + const options1 = def.options.map((x, i)=>to_json_schema_process(x, ctx, { + ...params, + path: [ + ...params.path, + isExclusive ? "oneOf" : "anyOf", + i + ] + })); + if (isExclusive) json.oneOf = options1; + else json.anyOf = options1; + }; + const intersectionProcessor = (schema, ctx, json, params)=>{ + const def = schema._zod.def; + const a = to_json_schema_process(def.left, ctx, { + ...params, + path: [ + ...params.path, + "allOf", + 0 + ] + }); + const b = to_json_schema_process(def.right, ctx, { + ...params, + path: [ + ...params.path, + "allOf", + 1 + ] + }); + const isSimpleIntersection = (val)=>"allOf" in val && 1 === Object.keys(val).length; + const allOf = [ + ...isSimpleIntersection(a) ? a.allOf : [ + a + ], + ...isSimpleIntersection(b) ? b.allOf : [ + b + ] + ]; + json.allOf = allOf; + }; + const tupleProcessor = (schema, ctx, _json, params)=>{ + const json = _json; + const def = schema._zod.def; + json.type = "array"; + const prefixPath = "draft-2020-12" === ctx.target ? "prefixItems" : "items"; + const restPath = "draft-2020-12" === ctx.target ? "items" : "openapi-3.0" === ctx.target ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i)=>to_json_schema_process(x, ctx, { + ...params, + path: [ + ...params.path, + prefixPath, + i + ] + })); + const rest = def.rest ? to_json_schema_process(def.rest, ctx, { + ...params, + path: [ + ...params.path, + restPath, + ..."openapi-3.0" === ctx.target ? [ + def.items.length + ] : [] + ] + }) : null; + if ("draft-2020-12" === ctx.target) { + json.prefixItems = prefixItems; + if (rest) json.items = rest; + } else if ("openapi-3.0" === ctx.target) { + json.items = { + anyOf: prefixItems + }; + if (rest) json.items.anyOf.push(rest); + json.minItems = prefixItems.length; + if (!rest) json.maxItems = prefixItems.length; + } else { + json.items = prefixItems; + if (rest) json.additionalItems = rest; + } + const { minimum, maximum } = schema._zod.bag; + if ("number" == typeof minimum) json.minItems = minimum; + if ("number" == typeof maximum) json.maxItems = maximum; + }; + const recordProcessor = (schema, ctx, _json, params)=>{ + const json = _json; + const def = schema._zod.def; + json.type = "object"; + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if ("loose" === def.mode && patterns && patterns.size > 0) { + const valueSchema = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [ + ...params.path, + "patternProperties", + "*" + ] + }); + json.patternProperties = {}; + for (const pattern of patterns)json.patternProperties[pattern.source] = valueSchema; + } else { + if ("draft-07" === ctx.target || "draft-2020-12" === ctx.target) json.propertyNames = to_json_schema_process(def.keyType, ctx, { + ...params, + path: [ + ...params.path, + "propertyNames" + ] + }); + json.additionalProperties = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [ + ...params.path, + "additionalProperties" + ] + }); + } + const keyValues = keyType._zod.values; + if (keyValues) { + const validKeyValues = [ + ...keyValues + ].filter((v)=>"string" == typeof v || "number" == typeof v); + if (validKeyValues.length > 0) json.required = validKeyValues; + } + }; + const nullableProcessor = (schema, ctx, json, params)=>{ + const def = schema._zod.def; + const inner = to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if ("openapi-3.0" === ctx.target) { + seen.ref = def.innerType; + json.nullable = true; + } else json.anyOf = [ + inner, + { + type: "null" + } + ]; + }; + const nonoptionalProcessor = (schema, ctx, _json, params)=>{ + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + }; + const defaultProcessor = (schema, ctx, json, params)=>{ + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.default = JSON.parse(JSON.stringify(def.defaultValue)); + }; + const prefaultProcessor = (schema, ctx, json, params)=>{ + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if ("input" === ctx.io) json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + }; + const catchProcessor = (schema, ctx, json, params)=>{ + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + json.default = catchValue; + }; + const pipeProcessor = (schema, ctx, _json, params)=>{ + const def = schema._zod.def; + const innerType = "input" === ctx.io ? "transform" === def.in._zod.def.type ? def.out : def.in : def.out; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; + }; + const readonlyProcessor = (schema, ctx, json, params)=>{ + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; + }; + const promiseProcessor = (schema, ctx, _json, params)=>{ + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + }; + const optionalProcessor = (schema, ctx, _json, params)=>{ + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + }; + const lazyProcessor = (schema, ctx, _json, params)=>{ + const innerType = schema._zod.innerType; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; + }; + const allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor + }; + function toJSONSchema(input, params) { + if ("_idmap" in input) { + const registry = input; + const ctx = initializeContext({ + ...params, + processors: allProcessors + }); + const defs = {}; + for (const entry of registry._idmap.entries()){ + const [_1, schema] = entry; + to_json_schema_process(schema, ctx); + } + const schemas = {}; + const external = { + registry, + uri: params?.uri, + defs + }; + ctx.external = external; + for (const entry of registry._idmap.entries()){ + const [key, schema] = entry; + extractDefs(ctx, schema); + schemas[key] = finalize(ctx, schema); + } + if (Object.keys(defs).length > 0) { + const defsSegment = "draft-2020-12" === ctx.target ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs + }; + } + return { + schemas + }; + } + const ctx = initializeContext({ + ...params, + processors: allProcessors + }); + to_json_schema_process(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); + } + const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def)=>{ + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function iso_datetime(params) { + return _isoDateTime(ZodISODateTime, params); + } + const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def)=>{ + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function iso_date(params) { + return _isoDate(ZodISODate, params); + } + const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def)=>{ + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function iso_time(params) { + return _isoTime(ZodISOTime, params); + } + const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def)=>{ + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function iso_duration(params) { + return _isoDuration(ZodISODuration, params); + } + const classic_errors_initializer = (inst, issues)=>{ + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper)=>formatError(inst, mapper) + }, + flatten: { + value: (mapper)=>flattenError(inst, mapper) + }, + addIssue: { + value: (issue)=>{ + inst.issues.push(issue); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + }, + addIssues: { + value: (issues)=>{ + inst.issues.push(...issues); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + }, + isEmpty: { + get () { + return 0 === inst.issues.length; + } + } + }); + }; + $constructor("ZodError", classic_errors_initializer); + const ZodRealError = $constructor("ZodError", classic_errors_initializer, { + Parent: Error + }); + const parse_parse = /* @__PURE__ */ _parse(ZodRealError); + const parse_parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError); + const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); + const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); + const parse_encode = /* @__PURE__ */ _encode(ZodRealError); + const parse_decode = /* @__PURE__ */ _decode(ZodRealError); + const parse_encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError); + const parse_decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError); + const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); + const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); + const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); + const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def)=>{ + $ZodType.init(inst, def); + Object.assign(inst["~standard"], { + jsonSchema: { + input: createStandardJSONSchemaMethod(inst, "input"), + output: createStandardJSONSchemaMethod(inst, "output") + } + }); + inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); + inst.def = def; + inst.type = def.type; + Object.defineProperty(inst, "_def", { + value: def + }); + inst.check = (...checks)=>inst.clone(mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...checks.map((ch)=>"function" == typeof ch ? { + _zod: { + check: ch, + def: { + check: "custom" + }, + onattach: [] + } + } : ch) + ] + }), { + parent: true + }); + inst.with = inst.check; + inst.clone = (def, params)=>clone(inst, def, params); + inst.brand = ()=>inst; + inst.register = (reg, meta)=>{ + reg.add(inst, meta); + return inst; + }; + inst.parse = (data, params)=>parse_parse(inst, data, params, { + callee: inst.parse + }); + inst.safeParse = (data, params)=>parse_safeParse(inst, data, params); + inst.parseAsync = async (data, params)=>parse_parseAsync(inst, data, params, { + callee: inst.parseAsync + }); + inst.safeParseAsync = async (data, params)=>parse_safeParseAsync(inst, data, params); + inst.spa = inst.safeParseAsync; + inst.encode = (data, params)=>parse_encode(inst, data, params); + inst.decode = (data, params)=>parse_decode(inst, data, params); + inst.encodeAsync = async (data, params)=>parse_encodeAsync(inst, data, params); + inst.decodeAsync = async (data, params)=>parse_decodeAsync(inst, data, params); + inst.safeEncode = (data, params)=>parse_safeEncode(inst, data, params); + inst.safeDecode = (data, params)=>parse_safeDecode(inst, data, params); + inst.safeEncodeAsync = async (data, params)=>parse_safeEncodeAsync(inst, data, params); + inst.safeDecodeAsync = async (data, params)=>parse_safeDecodeAsync(inst, data, params); + inst.refine = (check, params)=>inst.check(refine(check, params)); + inst.superRefine = (refinement)=>inst.check(superRefine(refinement)); + inst.overwrite = (fn)=>inst.check(_overwrite(fn)); + inst.optional = ()=>optional(inst); + inst.exactOptional = ()=>exactOptional(inst); + inst.nullable = ()=>nullable(inst); + inst.nullish = ()=>optional(nullable(inst)); + inst.nonoptional = (params)=>nonoptional(inst, params); + inst.array = ()=>schemas_array(inst); + inst.or = (arg)=>union([ + inst, + arg + ]); + inst.and = (arg)=>intersection(inst, arg); + inst.transform = (tx)=>pipe(inst, schemas_transform(tx)); + inst.default = (def)=>schemas_default(inst, def); + inst.prefault = (def)=>prefault(inst, def); + inst.catch = (params)=>schemas_catch(inst, params); + inst.pipe = (target)=>pipe(inst, target); + inst.readonly = ()=>readonly(inst); + inst.describe = (description)=>{ + const cl = inst.clone(); + globalRegistry.add(cl, { + description + }); + return cl; + }; + Object.defineProperty(inst, "description", { + get () { + return globalRegistry.get(inst)?.description; + }, + configurable: true + }); + inst.meta = (...args)=>{ + if (0 === args.length) return globalRegistry.get(inst); + const cl = inst.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }; + inst.isOptional = ()=>inst.safeParse(void 0).success; + inst.isNullable = ()=>inst.safeParse(null).success; + inst.apply = (fn)=>fn(inst); + return inst; + }); + const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def)=>{ + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>stringProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + inst.regex = (...args)=>inst.check(_regex(...args)); + inst.includes = (...args)=>inst.check(_includes(...args)); + inst.startsWith = (...args)=>inst.check(_startsWith(...args)); + inst.endsWith = (...args)=>inst.check(_endsWith(...args)); + inst.min = (...args)=>inst.check(_minLength(...args)); + inst.max = (...args)=>inst.check(_maxLength(...args)); + inst.length = (...args)=>inst.check(_length(...args)); + inst.nonempty = (...args)=>inst.check(_minLength(1, ...args)); + inst.lowercase = (params)=>inst.check(_lowercase(params)); + inst.uppercase = (params)=>inst.check(_uppercase(params)); + inst.trim = ()=>inst.check(_trim()); + inst.normalize = (...args)=>inst.check(_normalize(...args)); + inst.toLowerCase = ()=>inst.check(_toLowerCase()); + inst.toUpperCase = ()=>inst.check(_toUpperCase()); + inst.slugify = ()=>inst.check(_slugify()); + }); + const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def)=>{ + $ZodString.init(inst, def); + _ZodString.init(inst, def); + inst.email = (params)=>inst.check(_email(ZodEmail, params)); + inst.url = (params)=>inst.check(_url(ZodURL, params)); + inst.jwt = (params)=>inst.check(_jwt(ZodJWT, params)); + inst.emoji = (params)=>inst.check(api_emoji(ZodEmoji, params)); + inst.guid = (params)=>inst.check(_guid(ZodGUID, params)); + inst.uuid = (params)=>inst.check(_uuid(ZodUUID, params)); + inst.uuidv4 = (params)=>inst.check(_uuidv4(ZodUUID, params)); + inst.uuidv6 = (params)=>inst.check(_uuidv6(ZodUUID, params)); + inst.uuidv7 = (params)=>inst.check(_uuidv7(ZodUUID, params)); + inst.nanoid = (params)=>inst.check(_nanoid(ZodNanoID, params)); + inst.guid = (params)=>inst.check(_guid(ZodGUID, params)); + inst.cuid = (params)=>inst.check(_cuid(ZodCUID, params)); + inst.cuid2 = (params)=>inst.check(_cuid2(ZodCUID2, params)); + inst.ulid = (params)=>inst.check(_ulid(ZodULID, params)); + inst.base64 = (params)=>inst.check(_base64(ZodBase64, params)); + inst.base64url = (params)=>inst.check(_base64url(ZodBase64URL, params)); + inst.xid = (params)=>inst.check(_xid(ZodXID, params)); + inst.ksuid = (params)=>inst.check(_ksuid(ZodKSUID, params)); + inst.ipv4 = (params)=>inst.check(_ipv4(ZodIPv4, params)); + inst.ipv6 = (params)=>inst.check(_ipv6(ZodIPv6, params)); + inst.cidrv4 = (params)=>inst.check(_cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params)=>inst.check(_cidrv6(ZodCIDRv6, params)); + inst.e164 = (params)=>inst.check(_e164(ZodE164, params)); + inst.datetime = (params)=>inst.check(iso_datetime(params)); + inst.date = (params)=>inst.check(iso_date(params)); + inst.time = (params)=>inst.check(iso_time(params)); + inst.duration = (params)=>inst.check(iso_duration(params)); + }); + function schemas_string(params) { + return _string(ZodString, params); + } + const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def)=>{ + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); + }); + const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def)=>{ + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_email(params) { + return _email(ZodEmail, params); + } + const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def)=>{ + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_guid(params) { + return _guid(ZodGUID, params); + } + const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def)=>{ + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_uuid(params) { + return _uuid(ZodUUID, params); + } + function uuidv4(params) { + return _uuidv4(ZodUUID, params); + } + function uuidv6(params) { + return _uuidv6(ZodUUID, params); + } + function uuidv7(params) { + return _uuidv7(ZodUUID, params); + } + const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def)=>{ + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_url(params) { + return _url(ZodURL, params); + } + function httpUrl(params) { + return _url(ZodURL, { + protocol: /^https?$/, + hostname: domain, + ...normalizeParams(params) + }); + } + const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def)=>{ + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_emoji(params) { + return api_emoji(ZodEmoji, params); + } + const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def)=>{ + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_nanoid(params) { + return _nanoid(ZodNanoID, params); + } + const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def)=>{ + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_cuid(params) { + return _cuid(ZodCUID, params); + } + const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def)=>{ + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_cuid2(params) { + return _cuid2(ZodCUID2, params); + } + const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def)=>{ + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_ulid(params) { + return _ulid(ZodULID, params); + } + const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def)=>{ + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_xid(params) { + return _xid(ZodXID, params); + } + const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def)=>{ + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_ksuid(params) { + return _ksuid(ZodKSUID, params); + } + const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def)=>{ + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_ipv4(params) { + return _ipv4(ZodIPv4, params); + } + const ZodMAC = /*@__PURE__*/ $constructor("ZodMAC", (inst, def)=>{ + $ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_mac(params) { + return _mac(ZodMAC, params); + } + const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def)=>{ + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_ipv6(params) { + return _ipv6(ZodIPv6, params); + } + const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def)=>{ + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_cidrv4(params) { + return _cidrv4(ZodCIDRv4, params); + } + const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def)=>{ + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_cidrv6(params) { + return _cidrv6(ZodCIDRv6, params); + } + const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def)=>{ + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_base64(params) { + return _base64(ZodBase64, params); + } + const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def)=>{ + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_base64url(params) { + return _base64url(ZodBase64URL, params); + } + const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def)=>{ + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_e164(params) { + return _e164(ZodE164, params); + } + const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def)=>{ + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function schemas_jwt(params) { + return _jwt(ZodJWT, params); + } + const ZodCustomStringFormat = /*@__PURE__*/ $constructor("ZodCustomStringFormat", (inst, def)=>{ + $ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); + }); + function stringFormat(format, fnOrRegex, _params = {}) { + return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); + } + function schemas_hostname(_params) { + return _stringFormat(ZodCustomStringFormat, "hostname", regexes_hostname, _params); + } + function schemas_hex(_params) { + return _stringFormat(ZodCustomStringFormat, "hex", regexes_hex, _params); + } + function schemas_hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = regexes_namespaceObject[format]; + if (!regex) throw new Error(`Unrecognized hash format: ${format}`); + return _stringFormat(ZodCustomStringFormat, format, regex, params); + } + const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def)=>{ + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>numberProcessor(inst, ctx, json, params); + inst.gt = (value1, params)=>inst.check(_gt(value1, params)); + inst.gte = (value1, params)=>inst.check(_gte(value1, params)); + inst.min = (value1, params)=>inst.check(_gte(value1, params)); + inst.lt = (value1, params)=>inst.check(_lt(value1, params)); + inst.lte = (value1, params)=>inst.check(_lte(value1, params)); + inst.max = (value1, params)=>inst.check(_lte(value1, params)); + inst.int = (params)=>inst.check(schemas_int(params)); + inst.safe = (params)=>inst.check(schemas_int(params)); + inst.positive = (params)=>inst.check(_gt(0, params)); + inst.nonnegative = (params)=>inst.check(_gte(0, params)); + inst.negative = (params)=>inst.check(_lt(0, params)); + inst.nonpositive = (params)=>inst.check(_lte(0, params)); + inst.multipleOf = (value1, params)=>inst.check(_multipleOf(value1, params)); + inst.step = (value1, params)=>inst.check(_multipleOf(value1, params)); + inst.finite = ()=>inst; + const bag = inst._zod.bag; + inst.minValue = Math.max(bag.minimum ?? -1 / 0, bag.exclusiveMinimum ?? -1 / 0) ?? null; + inst.maxValue = Math.min(bag.maximum ?? 1 / 0, bag.exclusiveMaximum ?? 1 / 0) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; + }); + function schemas_number(params) { + return _number(ZodNumber, params); + } + const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def)=>{ + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); + }); + function schemas_int(params) { + return _int(ZodNumberFormat, params); + } + function float32(params) { + return _float32(ZodNumberFormat, params); + } + function float64(params) { + return _float64(ZodNumberFormat, params); + } + function int32(params) { + return _int32(ZodNumberFormat, params); + } + function uint32(params) { + return _uint32(ZodNumberFormat, params); + } + const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def)=>{ + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>booleanProcessor(inst, ctx, json, params); + }); + function schemas_boolean(params) { + return _boolean(ZodBoolean, params); + } + const ZodBigInt = /*@__PURE__*/ $constructor("ZodBigInt", (inst, def)=>{ + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>bigintProcessor(inst, ctx, json, params); + inst.gte = (value1, params)=>inst.check(_gte(value1, params)); + inst.min = (value1, params)=>inst.check(_gte(value1, params)); + inst.gt = (value1, params)=>inst.check(_gt(value1, params)); + inst.gte = (value1, params)=>inst.check(_gte(value1, params)); + inst.min = (value1, params)=>inst.check(_gte(value1, params)); + inst.lt = (value1, params)=>inst.check(_lt(value1, params)); + inst.lte = (value1, params)=>inst.check(_lte(value1, params)); + inst.max = (value1, params)=>inst.check(_lte(value1, params)); + inst.positive = (params)=>inst.check(_gt(BigInt(0), params)); + inst.negative = (params)=>inst.check(_lt(BigInt(0), params)); + inst.nonpositive = (params)=>inst.check(_lte(BigInt(0), params)); + inst.nonnegative = (params)=>inst.check(_gte(BigInt(0), params)); + inst.multipleOf = (value1, params)=>inst.check(_multipleOf(value1, params)); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; + }); + function schemas_bigint(params) { + return _bigint(ZodBigInt, params); + } + const ZodBigIntFormat = /*@__PURE__*/ $constructor("ZodBigIntFormat", (inst, def)=>{ + $ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); + }); + function int64(params) { + return _int64(ZodBigIntFormat, params); + } + function uint64(params) { + return _uint64(ZodBigIntFormat, params); + } + const ZodSymbol = /*@__PURE__*/ $constructor("ZodSymbol", (inst, def)=>{ + $ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>symbolProcessor(inst, ctx, json, params); + }); + function schemas_symbol(params) { + return _symbol(ZodSymbol, params); + } + const ZodUndefined = /*@__PURE__*/ $constructor("ZodUndefined", (inst, def)=>{ + $ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>undefinedProcessor(inst, ctx, json, params); + }); + function schemas_undefined(params) { + return api_undefined(ZodUndefined, params); + } + const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def)=>{ + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>nullProcessor(inst, ctx, json, params); + }); + function schemas_null(params) { + return api_null(ZodNull, params); + } + const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def)=>{ + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>anyProcessor(inst, ctx, json, params); + }); + function any() { + return _any(ZodAny); + } + const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def)=>{ + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>unknownProcessor(inst, ctx, json, params); + }); + function unknown() { + return _unknown(ZodUnknown); + } + const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def)=>{ + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>neverProcessor(inst, ctx, json, params); + }); + function never(params) { + return _never(ZodNever, params); + } + const ZodVoid = /*@__PURE__*/ $constructor("ZodVoid", (inst, def)=>{ + $ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>voidProcessor(inst, ctx, json, params); + }); + function schemas_void(params) { + return _void(ZodVoid, params); + } + const ZodDate = /*@__PURE__*/ $constructor("ZodDate", (inst, def)=>{ + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>dateProcessor(inst, ctx, json, params); + inst.min = (value1, params)=>inst.check(_gte(value1, params)); + inst.max = (value1, params)=>inst.check(_lte(value1, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; + }); + function schemas_date(params) { + return _date(ZodDate, params); + } + const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def)=>{ + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>arrayProcessor(inst, ctx, json, params); + inst.element = def.element; + inst.min = (minLength, params)=>inst.check(_minLength(minLength, params)); + inst.nonempty = (params)=>inst.check(_minLength(1, params)); + inst.max = (maxLength, params)=>inst.check(_maxLength(maxLength, params)); + inst.length = (len, params)=>inst.check(_length(len, params)); + inst.unwrap = ()=>inst.element; + }); + function schemas_array(element, params) { + return _array(ZodArray, element, params); + } + function keyof(schema) { + const shape = schema._zod.def.shape; + return schemas_enum(Object.keys(shape)); + } + const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def)=>{ + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>objectProcessor(inst, ctx, json, params); + defineLazy(inst, "shape", ()=>def.shape); + inst.keyof = ()=>schemas_enum(Object.keys(inst._zod.def.shape)); + inst.catchall = (catchall)=>inst.clone({ + ...inst._zod.def, + catchall: catchall + }); + inst.passthrough = ()=>inst.clone({ + ...inst._zod.def, + catchall: unknown() + }); + inst.loose = ()=>inst.clone({ + ...inst._zod.def, + catchall: unknown() + }); + inst.strict = ()=>inst.clone({ + ...inst._zod.def, + catchall: never() + }); + inst.strip = ()=>inst.clone({ + ...inst._zod.def, + catchall: void 0 + }); + inst.extend = (incoming)=>extend(inst, incoming); + inst.safeExtend = (incoming)=>safeExtend(inst, incoming); + inst.merge = (other)=>merge(inst, other); + inst.pick = (mask)=>pick(inst, mask); + inst.omit = (mask)=>omit(inst, mask); + inst.partial = (...args)=>partial(ZodOptional, inst, args[0]); + inst.required = (...args)=>util_required(ZodNonOptional, inst, args[0]); + }); + function schemas_object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...normalizeParams(params) + }; + return new ZodObject(def); + } + function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...normalizeParams(params) + }); + } + function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...normalizeParams(params) + }); + } + const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def)=>{ + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>unionProcessor(inst, ctx, json, params); + inst.options = def.options; + }); + function union(options1, params) { + return new ZodUnion({ + type: "union", + options: options1, + ...normalizeParams(params) + }); + } + const ZodXor = /*@__PURE__*/ $constructor("ZodXor", (inst, def)=>{ + ZodUnion.init(inst, def); + $ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>unionProcessor(inst, ctx, json, params); + inst.options = def.options; + }); + function xor(options1, params) { + return new ZodXor({ + type: "union", + options: options1, + inclusive: false, + ...normalizeParams(params) + }); + } + const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def)=>{ + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); + }); + function discriminatedUnion(discriminator, options1, params) { + return new ZodDiscriminatedUnion({ + type: "union", + options: options1, + discriminator, + ...normalizeParams(params) + }); + } + const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def)=>{ + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>intersectionProcessor(inst, ctx, json, params); + }); + function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left: left, + right: right + }); + } + const ZodTuple = /*@__PURE__*/ $constructor("ZodTuple", (inst, def)=>{ + $ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>tupleProcessor(inst, ctx, json, params); + inst.rest = (rest)=>inst.clone({ + ...inst._zod.def, + rest: rest + }); + }); + function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items: items, + rest, + ...normalizeParams(params) + }); + } + const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def)=>{ + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>recordProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + }); + function schemas_record(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...normalizeParams(params) + }); + } + function partialRecord(keyType, valueType, params) { + const k = clone(keyType); + k._zod.values = void 0; + return new ZodRecord({ + type: "record", + keyType: k, + valueType: valueType, + ...normalizeParams(params) + }); + } + function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + mode: "loose", + ...normalizeParams(params) + }); + } + const ZodMap = /*@__PURE__*/ $constructor("ZodMap", (inst, def)=>{ + $ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>mapProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args)=>inst.check(_minSize(...args)); + inst.nonempty = (params)=>inst.check(_minSize(1, params)); + inst.max = (...args)=>inst.check(_maxSize(...args)); + inst.size = (...args)=>inst.check(_size(...args)); + }); + function schemas_map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType: keyType, + valueType: valueType, + ...normalizeParams(params) + }); + } + const ZodSet = /*@__PURE__*/ $constructor("ZodSet", (inst, def)=>{ + $ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>setProcessor(inst, ctx, json, params); + inst.min = (...args)=>inst.check(_minSize(...args)); + inst.nonempty = (params)=>inst.check(_minSize(1, params)); + inst.max = (...args)=>inst.check(_maxSize(...args)); + inst.size = (...args)=>inst.check(_size(...args)); + }); + function schemas_set(valueType, params) { + return new ZodSet({ + type: "set", + valueType: valueType, + ...normalizeParams(params) + }); + } + const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def)=>{ + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>enumProcessor(inst, ctx, json, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params)=>{ + const newEntries = {}; + for (const value1 of values)if (keys.has(value1)) newEntries[value1] = def.entries[value1]; + else throw new Error(`Key ${value1} not found in enum`); + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values, params)=>{ + const newEntries = { + ...def.entries + }; + for (const value1 of values)if (keys.has(value1)) delete newEntries[value1]; + else throw new Error(`Key ${value1} not found in enum`); + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries + }); + }; + }); + function schemas_enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v)=>[ + v, + v + ])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params) + }); + } + function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params) + }); + } + const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def)=>{ + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>literalProcessor(inst, ctx, json, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get () { + if (def.values.length > 1) throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + return def.values[0]; + } + }); + }); + function schemas_literal(value1, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value1) ? value1 : [ + value1 + ], + ...normalizeParams(params) + }); + } + const ZodFile = /*@__PURE__*/ $constructor("ZodFile", (inst, def)=>{ + $ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>fileProcessor(inst, ctx, json, params); + inst.min = (size, params)=>inst.check(_minSize(size, params)); + inst.max = (size, params)=>inst.check(_maxSize(size, params)); + inst.mime = (types, params)=>inst.check(_mime(Array.isArray(types) ? types : [ + types + ], params)); + }); + function schemas_file(params) { + return _file(ZodFile, params); + } + const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def)=>{ + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>transformProcessor(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx)=>{ + if ("backward" === _ctx.direction) throw new $ZodEncodeError(inst.constructor.name); + payload.addIssue = (issue)=>{ + if ("string" == typeof issue) payload.issues.push(util_issue(issue, payload.value, def)); + else { + const _issue = issue; + if (_issue.fatal) _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + payload.issues.push(util_issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) return output.then((output)=>{ + payload.value = output; + return payload; + }); + payload.value = output; + return payload; + }; + }); + function schemas_transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn + }); + } + const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def)=>{ + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>optionalProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.innerType; + }); + function optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType: innerType + }); + } + const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def)=>{ + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>optionalProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.innerType; + }); + function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType: innerType + }); + } + const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def)=>{ + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>nullableProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.innerType; + }); + function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType: innerType + }); + } + function schemas_nullish(innerType) { + return optional(nullable(innerType)); + } + const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def)=>{ + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>defaultProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; + }); + function schemas_default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType: innerType, + get defaultValue () { + return "function" == typeof defaultValue ? defaultValue() : shallowClone(defaultValue); + } + }); + } + const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def)=>{ + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>prefaultProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.innerType; + }); + function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType: innerType, + get defaultValue () { + return "function" == typeof defaultValue ? defaultValue() : shallowClone(defaultValue); + } + }); + } + const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def)=>{ + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>nonoptionalProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.innerType; + }); + function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType, + ...normalizeParams(params) + }); + } + const ZodSuccess = /*@__PURE__*/ $constructor("ZodSuccess", (inst, def)=>{ + $ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>successProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.innerType; + }); + function schemas_success(innerType) { + return new ZodSuccess({ + type: "success", + innerType: innerType + }); + } + const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def)=>{ + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>catchProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; + }); + function schemas_catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType: innerType, + catchValue: "function" == typeof catchValue ? catchValue : ()=>catchValue + }); + } + const ZodNaN = /*@__PURE__*/ $constructor("ZodNaN", (inst, def)=>{ + $ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>nanProcessor(inst, ctx, json, params); + }); + function nan(params) { + return _nan(ZodNaN, params); + } + const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def)=>{ + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>pipeProcessor(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; + }); + function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out: out + }); + } + const ZodCodec = /*@__PURE__*/ $constructor("ZodCodec", (inst, def)=>{ + ZodPipe.init(inst, def); + $ZodCodec.init(inst, def); + }); + function schemas_codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out: out, + transform: params.decode, + reverseTransform: params.encode + }); + } + const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def)=>{ + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>readonlyProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.innerType; + }); + function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType: innerType + }); + } + const ZodTemplateLiteral = /*@__PURE__*/ $constructor("ZodTemplateLiteral", (inst, def)=>{ + $ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>templateLiteralProcessor(inst, ctx, json, params); + }); + function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...normalizeParams(params) + }); + } + const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def)=>{ + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>lazyProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.getter(); + }); + function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter: getter + }); + } + const ZodPromise = /*@__PURE__*/ $constructor("ZodPromise", (inst, def)=>{ + $ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>promiseProcessor(inst, ctx, json, params); + inst.unwrap = ()=>inst._zod.def.innerType; + }); + function schemas_promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType: innerType + }); + } + const ZodFunction = /*@__PURE__*/ $constructor("ZodFunction", (inst, def)=>{ + $ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>functionProcessor(inst, ctx, json, params); + }); + function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? schemas_array(unknown()), + output: params?.output ?? unknown() + }); + } + const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def)=>{ + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params)=>customProcessor(inst, ctx, json, params); + }); + function schemas_check(fn) { + const ch = new $ZodCheck({ + check: "custom" + }); + ch._zod.check = fn; + return ch; + } + function custom(fn, _params) { + return _custom(ZodCustom, fn ?? (()=>true), _params); + } + function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); + } + function superRefine(fn) { + return _superRefine(fn); + } + const schemas_describe = describe; + const schemas_meta = api_meta; + function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data)=>data instanceof cls, + abort: true, + ...normalizeParams(params) + }); + inst._zod.bag.Class = cls; + inst._zod.check = (payload)=>{ + if (!(payload.value instanceof cls)) payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [ + ...inst._zod.def.path ?? [] + ] + }); + }; + return inst; + } + const stringbool = (...args)=>_stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString + }, ...args); + function schemas_json(params) { + const jsonSchema = lazy(()=>union([ + schemas_string(params), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_array(jsonSchema), + schemas_record(schemas_string(), jsonSchema) + ])); + return jsonSchema; + } + function schemas_preprocess(fn, schema) { + return pipe(schemas_transform(fn), schema); + } + var compat_ZodFirstPartyTypeKind; + compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {}); + ({ + ...classic_schemas_namespaceObject, + ...classic_checks_namespaceObject, + iso: iso_namespaceObject + }); + new Set([ + "$schema", + "$ref", + "$defs", + "definitions", + "$id", + "id", + "$comment", + "$anchor", + "$vocabulary", + "$dynamicRef", + "$dynamicAnchor", + "type", + "enum", + "const", + "anyOf", + "oneOf", + "allOf", + "not", + "properties", + "required", + "additionalProperties", + "patternProperties", + "propertyNames", + "minProperties", + "maxProperties", + "items", + "prefixItems", + "additionalItems", + "minItems", + "maxItems", + "uniqueItems", + "contains", + "minContains", + "maxContains", + "minLength", + "maxLength", + "pattern", + "format", + "minimum", + "maximum", + "exclusiveMinimum", + "exclusiveMaximum", + "multipleOf", + "description", + "default", + "contentEncoding", + "contentMediaType", + "contentSchema", + "unevaluatedItems", + "unevaluatedProperties", + "if", + "then", + "else", + "dependentSchemas", + "dependentRequired", + "nullable", + "readOnly" + ]); + function coerce_number(params) { + return _coercedNumber(ZodNumber, params); + } + core_config(en()); + var util_util; + (function(util) { + util.assertEqual = (_1)=>{}; + function assertIs(_arg) {} + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items)=>{ + const obj = {}; + for (const item of items)obj[item] = item; + return obj; + }; + util.getValidEnumValues = (obj)=>{ + const validKeys = util.objectKeys(obj).filter((k)=>"number" != typeof obj[obj[k]]); + const filtered = {}; + for (const k of validKeys)filtered[k] = obj[k]; + return util.objectValues(filtered); + }; + util.objectValues = (obj)=>util.objectKeys(obj).map(function(e) { + return obj[e]; + }); + util.objectKeys = "function" == typeof Object.keys ? (obj)=>Object.keys(obj) : (object)=>{ + const keys = []; + for(const key in object)if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key); + return keys; + }; + util.find = (arr, checker)=>{ + for (const item of arr)if (checker(item)) return item; + }; + util.isInteger = "function" == typeof Number.isInteger ? (val)=>Number.isInteger(val) : (val)=>"number" == typeof val && Number.isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val)=>"string" == typeof val ? `'${val}'` : val).join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_1, value1)=>{ + if ("bigint" == typeof value1) return value1.toString(); + return value1; + }; + })(util_util || (util_util = {})); + var util_objectUtil; + (function(objectUtil) { + objectUtil.mergeShapes = (first, second)=>({ + ...first, + ...second + }); + })(util_objectUtil || (util_objectUtil = {})); + const ZodParsedType = util_util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" + ]); + const util_getParsedType = (data)=>{ + const t = typeof data; + switch(t){ + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) return ZodParsedType.array; + if (null === data) return ZodParsedType.null; + if (data.then && "function" == typeof data.then && data.catch && "function" == typeof data.catch) return ZodParsedType.promise; + if ("undefined" != typeof Map && data instanceof Map) return ZodParsedType.map; + if ("undefined" != typeof Set && data instanceof Set) return ZodParsedType.set; + if ("undefined" != typeof Date && data instanceof Date) return ZodParsedType.date; + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } + }; + const ZodError_ZodIssueCode = util_util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" + ]); + class ZodError_ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues){ + super(); + this.issues = []; + this.addIssue = (sub)=>{ + this.issues = [ + ...this.issues, + sub + ]; + }; + this.addIssues = (subs = [])=>{ + this.issues = [ + ...this.issues, + ...subs + ]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto); + else this.__proto__ = actualProto; + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue) { + return issue.message; + }; + const fieldErrors = { + _errors: [] + }; + const processError = (error)=>{ + for (const issue of error.issues)if ("invalid_union" === issue.code) issue.unionErrors.map(processError); + else if ("invalid_return_type" === issue.code) processError(issue.returnTypeError); + else if ("invalid_arguments" === issue.code) processError(issue.argumentsError); + else if (0 === issue.path.length) fieldErrors._errors.push(mapper(issue)); + else { + let curr = fieldErrors; + let i = 0; + while(i < issue.path.length){ + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (terminal) { + curr[el] = curr[el] || { + _errors: [] + }; + curr[el]._errors.push(mapper(issue)); + } else curr[el] = curr[el] || { + _errors: [] + }; + curr = curr[el]; + i++; + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value1) { + if (!(value1 instanceof ZodError_ZodError)) throw new Error(`Not a ZodError: ${value1}`); + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util_util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return 0 === this.issues.length; + } + flatten(mapper = (issue)=>issue.message) { + const fieldErrors = Object.create(null); + const formErrors = []; + for (const sub of this.issues)if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else formErrors.push(mapper(sub)); + return { + formErrors, + fieldErrors + }; + } + get formErrors() { + return this.flatten(); + } + } + ZodError_ZodError.create = (issues)=>{ + const error = new ZodError_ZodError(issues); + return error; + }; + const en_errorMap = (issue, _ctx)=>{ + let message; + switch(issue.code){ + case ZodError_ZodIssueCode.invalid_type: + message = issue.received === ZodParsedType.undefined ? "Required" : `Expected ${issue.expected}, received ${issue.received}`; + break; + case ZodError_ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_util.jsonStringifyReplacer)}`; + break; + case ZodError_ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util_util.joinValues(issue.keys, ", ")}`; + break; + case ZodError_ZodIssueCode.invalid_union: + message = "Invalid input"; + break; + case ZodError_ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util_util.joinValues(issue.options)}`; + break; + case ZodError_ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util_util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodError_ZodIssueCode.invalid_arguments: + message = "Invalid function arguments"; + break; + case ZodError_ZodIssueCode.invalid_return_type: + message = "Invalid function return type"; + break; + case ZodError_ZodIssueCode.invalid_date: + message = "Invalid date"; + break; + case ZodError_ZodIssueCode.invalid_string: + if ("object" == typeof issue.validation) if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if ("number" == typeof issue.validation.position) message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } else if ("startsWith" in issue.validation) message = `Invalid input: must start with "${issue.validation.startsWith}"`; + else if ("endsWith" in issue.validation) message = `Invalid input: must end with "${issue.validation.endsWith}"`; + else util_util.assertNever(issue.validation); + else message = "regex" !== issue.validation ? `Invalid ${issue.validation}` : "Invalid"; + break; + case ZodError_ZodIssueCode.too_small: + message = "array" === issue.type ? `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "more than"} ${issue.minimum} element(s)` : "string" === issue.type ? `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "over"} ${issue.minimum} character(s)` : "number" === issue.type ? `Number must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${issue.minimum}` : "bigint" === issue.type ? `Number must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${issue.minimum}` : "date" === issue.type ? `Date must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number(issue.minimum))}` : "Invalid input"; + break; + case ZodError_ZodIssueCode.too_big: + message = "array" === issue.type ? `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "less than"} ${issue.maximum} element(s)` : "string" === issue.type ? `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "under"} ${issue.maximum} character(s)` : "number" === issue.type ? `Number must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : "bigint" === issue.type ? `BigInt must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : "date" === issue.type ? `Date must be ${issue.exact ? "exactly" : issue.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(issue.maximum))}` : "Invalid input"; + break; + case ZodError_ZodIssueCode.custom: + message = "Invalid input"; + break; + case ZodError_ZodIssueCode.invalid_intersection_types: + message = "Intersection results could not be merged"; + break; + case ZodError_ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodError_ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util_util.assertNever(issue); + } + return { + message + }; + }; + const locales_en = en_errorMap; + let overrideErrorMap = locales_en; + function errors_getErrorMap() { + return overrideErrorMap; + } + const makeIssue = (params)=>{ + const { data, path, errorMaps, issueData } = params; + const fullPath = [ + ...path, + ...issueData.path || [] + ]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (void 0 !== issueData.message) return { + ...issueData, + path: fullPath, + message: issueData.message + }; + let errorMessage = ""; + const maps = errorMaps.filter((m)=>!!m).slice().reverse(); + for (const map of maps)errorMessage = map(fullIssue, { + data, + defaultError: errorMessage + }).message; + return { + ...issueData, + path: fullPath, + message: errorMessage + }; + }; + function addIssueToContext(ctx, issueData) { + const overrideMap = errors_getErrorMap(); + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + overrideMap, + overrideMap === locales_en ? void 0 : locales_en + ].filter((x)=>!!x) + }); + ctx.common.issues.push(issue); + } + class ParseStatus { + constructor(){ + this.value = "valid"; + } + dirty() { + if ("valid" === this.value) this.value = "dirty"; + } + abort() { + if ("aborted" !== this.value) this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results){ + if ("aborted" === s.status) return parseUtil_INVALID; + if ("dirty" === s.status) status.dirty(); + arrayValue.push(s.value); + } + return { + status: status.value, + value: arrayValue + }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs){ + const key = await pair.key; + const value1 = await pair.value; + syncPairs.push({ + key, + value: value1 + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs){ + const { key, value: value1 } = pair; + if ("aborted" === key.status) return parseUtil_INVALID; + if ("aborted" === value1.status) return parseUtil_INVALID; + if ("dirty" === key.status) status.dirty(); + if ("dirty" === value1.status) status.dirty(); + if ("__proto__" !== key.value && (void 0 !== value1.value || pair.alwaysSet)) finalObject[key.value] = value1.value; + } + return { + status: status.value, + value: finalObject + }; + } + } + const parseUtil_INVALID = Object.freeze({ + status: "aborted" + }); + const DIRTY = (value1)=>({ + status: "dirty", + value: value1 + }); + const OK = (value1)=>({ + status: "valid", + value: value1 + }); + const parseUtil_isAborted = (x)=>"aborted" === x.status; + const isDirty = (x)=>"dirty" === x.status; + const isValid = (x)=>"valid" === x.status; + const isAsync = (x)=>"undefined" != typeof Promise && x instanceof Promise; + var errorUtil_errorUtil; + (function(errorUtil) { + errorUtil.errToObj = (message)=>"string" == typeof message ? { + message + } : message || {}; + errorUtil.toString = (message)=>"string" == typeof message ? message : message?.message; + })(errorUtil_errorUtil || (errorUtil_errorUtil = {})); + class ParseInputLazyPath { + constructor(parent, value1, path, key){ + this._cachedPath = []; + this.parent = parent; + this.data = value1; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key); + else this._cachedPath.push(...this._path, this._key); + return this._cachedPath; + } + } + const handleResult = (ctx, result)=>{ + if (isValid(result)) return { + success: true, + data: result.value + }; + if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected."); + return { + success: false, + get error () { + if (this._error) return this._error; + const error = new ZodError_ZodError(ctx.common.issues); + this._error = error; + return this._error; + } + }; + }; + function processCreateParams(params) { + if (!params) return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.'); + if (errorMap) return { + errorMap: errorMap, + description + }; + const customMap = (iss, ctx)=>{ + const { message } = params; + if ("invalid_enum_value" === iss.code) return { + message: message ?? ctx.defaultError + }; + if (void 0 === ctx.data) return { + message: message ?? required_error ?? ctx.defaultError + }; + if ("invalid_type" !== iss.code) return { + message: ctx.defaultError + }; + return { + message: message ?? invalid_type_error ?? ctx.defaultError + }; + }; + return { + errorMap: customMap, + description + }; + } + class types_ZodType { + get description() { + return this._def.description; + } + _getType(input) { + return util_getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: util_getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: util_getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) throw new Error("Synchronous parse encountered promise."); + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: util_getParsedType(data) + }; + const result = this._parseSync({ + data, + path: ctx.path, + parent: ctx + }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: util_getParsedType(data) + }; + if (!this["~standard"].async) try { + const result = this._parseSync({ + data, + path: [], + parent: ctx + }); + return isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true; + ctx.common = { + issues: [], + async: true + }; + } + return this._parseAsync({ + data, + path: [], + parent: ctx + }).then((result)=>isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: util_getParsedType(data) + }; + const maybeAsyncResult = this._parse({ + data, + path: ctx.path, + parent: ctx + }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val)=>{ + if ("string" == typeof message || void 0 === message) return { + message + }; + if ("function" == typeof message) return message(val); + return message; + }; + return this._refinement((val, ctx)=>{ + const result = check(val); + const setError = ()=>ctx.addIssue({ + code: ZodError_ZodIssueCode.custom, + ...getIssueProperties(val) + }); + if ("undefined" != typeof Promise && result instanceof Promise) return result.then((data)=>{ + if (data) return true; + setError(); + return false; + }); + if (result) return true; + setError(); + return false; + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx)=>{ + if (check(val)) return true; + ctx.addIssue("function" == typeof refinementData ? refinementData(val, ctx) : refinementData); + return false; + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: types_ZodFirstPartyTypeKind.ZodEffects, + effect: { + type: "refinement", + refinement + } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def){ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data)=>this["~validate"](data) + }; + } + optional() { + return types_ZodOptional.create(this, this._def); + } + nullable() { + return types_ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return types_ZodArray.create(this); + } + promise() { + return types_ZodPromise.create(this, this._def); + } + or(option) { + return types_ZodUnion.create([ + this, + option + ], this._def); + } + and(incoming) { + return types_ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: types_ZodFirstPartyTypeKind.ZodEffects, + effect: { + type: "transform", + transform + } + }); + } + default(def) { + const defaultValueFunc = "function" == typeof def ? def : ()=>def; + return new types_ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: types_ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: types_ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = "function" == typeof def ? def : ()=>def; + return new types_ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: types_ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return types_ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } + } + const cuidRegex = /^c[^\s-]{8,}$/i; + const cuid2Regex = /^[0-9a-z]+$/; + const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; + const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + const nanoidRegex = /^[a-z0-9_-]{21}$/i; + const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; + const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + const _emojiRegex = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$"; + let emojiRegex; + const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; + const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; + const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; + const dateRegexSource = "((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))"; + const dateRegex = new RegExp(`^${dateRegexSource}$`); + function timeRegexSource(args) { + let secondsRegexSource = "[0-5]\\d"; + if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + else if (null == args.precision) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; + } + function types_timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); + } + function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? "Z?" : "Z"); + if (args.offset) opts.push("([+-]\\d{2}:?\\d{2})"); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); + } + function isValidIP(ip, version) { + if (("v4" === version || !version) && ipv4Regex.test(ip)) return true; + if (("v6" === version || !version) && ipv6Regex.test(ip)) return true; + return false; + } + function types_isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) return false; + try { + const [header] = jwt.split("."); + if (!header) return false; + const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base64)); + if ("object" != typeof decoded || null === decoded) return false; + if ("typ" in decoded && decoded?.typ !== "JWT") return false; + if (!decoded.alg) return false; + if (alg && decoded.alg !== alg) return false; + return true; + } catch { + return false; + } + } + function isValidCidr(ip, version) { + if (("v4" === version || !version) && ipv4CidrRegex.test(ip)) return true; + if (("v6" === version || !version) && ipv6CidrRegex.test(ip)) return true; + return false; + } + class types_ZodString extends types_ZodType { + _parse(input) { + if (this._def.coerce) input.data = String(input.data); + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + const status = new ParseStatus(); + let ctx; + for (const check of this._def.checks)if ("min" === check.kind) { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if ("max" === check.kind) { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if ("length" === check.kind) { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + else if (tooSmall) addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + status.dirty(); + } + } else if ("email" === check.kind) { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("emoji" === check.kind) { + if (!emojiRegex) emojiRegex = new RegExp(_emojiRegex, "u"); + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("uuid" === check.kind) { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("nanoid" === check.kind) { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("cuid" === check.kind) { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("cuid2" === check.kind) { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("ulid" === check.kind) { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("url" === check.kind) try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + else if ("regex" === check.kind) { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("trim" === check.kind) input.data = input.data.trim(); + else if ("includes" === check.kind) { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_string, + validation: { + includes: check.value, + position: check.position + }, + message: check.message + }); + status.dirty(); + } + } else if ("toLowerCase" === check.kind) input.data = input.data.toLowerCase(); + else if ("toUpperCase" === check.kind) input.data = input.data.toUpperCase(); + else if ("startsWith" === check.kind) { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_string, + validation: { + startsWith: check.value + }, + message: check.message + }); + status.dirty(); + } + } else if ("endsWith" === check.kind) { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_string, + validation: { + endsWith: check.value + }, + message: check.message + }); + status.dirty(); + } + } else if ("datetime" === check.kind) { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }); + status.dirty(); + } + } else if ("date" === check.kind) { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_string, + validation: "date", + message: check.message + }); + status.dirty(); + } + } else if ("time" === check.kind) { + const regex = types_timeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_string, + validation: "time", + message: check.message + }); + status.dirty(); + } + } else if ("duration" === check.kind) { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("ip" === check.kind) { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("jwt" === check.kind) { + if (!types_isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("cidr" === check.kind) { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("base64" === check.kind) { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if ("base64url" === check.kind) { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodError_ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else util_util.assertNever(check); + return { + status: status.value, + value: input.data + }; + } + _regex(regex, validation, message) { + return this.refinement((data)=>regex.test(data), { + validation, + code: ZodError_ZodIssueCode.invalid_string, + ...errorUtil_errorUtil.errToObj(message) + }); + } + _addCheck(check) { + return new types_ZodString({ + ...this._def, + checks: [ + ...this._def.checks, + check + ] + }); + } + email(message) { + return this._addCheck({ + kind: "email", + ...errorUtil_errorUtil.errToObj(message) + }); + } + url(message) { + return this._addCheck({ + kind: "url", + ...errorUtil_errorUtil.errToObj(message) + }); + } + emoji(message) { + return this._addCheck({ + kind: "emoji", + ...errorUtil_errorUtil.errToObj(message) + }); + } + uuid(message) { + return this._addCheck({ + kind: "uuid", + ...errorUtil_errorUtil.errToObj(message) + }); + } + nanoid(message) { + return this._addCheck({ + kind: "nanoid", + ...errorUtil_errorUtil.errToObj(message) + }); + } + cuid(message) { + return this._addCheck({ + kind: "cuid", + ...errorUtil_errorUtil.errToObj(message) + }); + } + cuid2(message) { + return this._addCheck({ + kind: "cuid2", + ...errorUtil_errorUtil.errToObj(message) + }); + } + ulid(message) { + return this._addCheck({ + kind: "ulid", + ...errorUtil_errorUtil.errToObj(message) + }); + } + base64(message) { + return this._addCheck({ + kind: "base64", + ...errorUtil_errorUtil.errToObj(message) + }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil_errorUtil.errToObj(message) + }); + } + jwt(options1) { + return this._addCheck({ + kind: "jwt", + ...errorUtil_errorUtil.errToObj(options1) + }); + } + ip(options1) { + return this._addCheck({ + kind: "ip", + ...errorUtil_errorUtil.errToObj(options1) + }); + } + cidr(options1) { + return this._addCheck({ + kind: "cidr", + ...errorUtil_errorUtil.errToObj(options1) + }); + } + datetime(options1) { + if ("string" == typeof options1) return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options1 + }); + return this._addCheck({ + kind: "datetime", + precision: void 0 === options1?.precision ? null : options1?.precision, + offset: options1?.offset ?? false, + local: options1?.local ?? false, + ...errorUtil_errorUtil.errToObj(options1?.message) + }); + } + date(message) { + return this._addCheck({ + kind: "date", + message + }); + } + time(options1) { + if ("string" == typeof options1) return this._addCheck({ + kind: "time", + precision: null, + message: options1 + }); + return this._addCheck({ + kind: "time", + precision: void 0 === options1?.precision ? null : options1?.precision, + ...errorUtil_errorUtil.errToObj(options1?.message) + }); + } + duration(message) { + return this._addCheck({ + kind: "duration", + ...errorUtil_errorUtil.errToObj(message) + }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil_errorUtil.errToObj(message) + }); + } + includes(value1, options1) { + return this._addCheck({ + kind: "includes", + value: value1, + position: options1?.position, + ...errorUtil_errorUtil.errToObj(options1?.message) + }); + } + startsWith(value1, message) { + return this._addCheck({ + kind: "startsWith", + value: value1, + ...errorUtil_errorUtil.errToObj(message) + }); + } + endsWith(value1, message) { + return this._addCheck({ + kind: "endsWith", + value: value1, + ...errorUtil_errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil_errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil_errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil_errorUtil.errToObj(message) + }); + } + nonempty(message) { + return this.min(1, errorUtil_errorUtil.errToObj(message)); + } + trim() { + return new types_ZodString({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind: "trim" + } + ] + }); + } + toLowerCase() { + return new types_ZodString({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind: "toLowerCase" + } + ] + }); + } + toUpperCase() { + return new types_ZodString({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind: "toUpperCase" + } + ] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch)=>"datetime" === ch.kind); + } + get isDate() { + return !!this._def.checks.find((ch)=>"date" === ch.kind); + } + get isTime() { + return !!this._def.checks.find((ch)=>"time" === ch.kind); + } + get isDuration() { + return !!this._def.checks.find((ch)=>"duration" === ch.kind); + } + get isEmail() { + return !!this._def.checks.find((ch)=>"email" === ch.kind); + } + get isURL() { + return !!this._def.checks.find((ch)=>"url" === ch.kind); + } + get isEmoji() { + return !!this._def.checks.find((ch)=>"emoji" === ch.kind); + } + get isUUID() { + return !!this._def.checks.find((ch)=>"uuid" === ch.kind); + } + get isNANOID() { + return !!this._def.checks.find((ch)=>"nanoid" === ch.kind); + } + get isCUID() { + return !!this._def.checks.find((ch)=>"cuid" === ch.kind); + } + get isCUID2() { + return !!this._def.checks.find((ch)=>"cuid2" === ch.kind); + } + get isULID() { + return !!this._def.checks.find((ch)=>"ulid" === ch.kind); + } + get isIP() { + return !!this._def.checks.find((ch)=>"ip" === ch.kind); + } + get isCIDR() { + return !!this._def.checks.find((ch)=>"cidr" === ch.kind); + } + get isBase64() { + return !!this._def.checks.find((ch)=>"base64" === ch.kind); + } + get isBase64url() { + return !!this._def.checks.find((ch)=>"base64url" === ch.kind); + } + get minLength() { + let min = null; + for (const ch of this._def.checks)if ("min" === ch.kind) { + if (null === min || ch.value > min) min = ch.value; + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks)if ("max" === ch.kind) { + if (null === max || ch.value < max) max = ch.value; + } + return max; + } + } + types_ZodString.create = (params)=>new types_ZodString({ + checks: [], + typeName: types_ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); + function types_floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; + } + class types_ZodNumber extends types_ZodType { + constructor(){ + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) input.data = Number(input.data); + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + let ctx; + const status = new ParseStatus(); + for (const check of this._def.checks)if ("int" === check.kind) { + if (!util_util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message + }); + status.dirty(); + } + } else if ("min" === check.kind) { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if ("max" === check.kind) { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if ("multipleOf" === check.kind) { + if (0 !== types_floatSafeRemainder(input.data, check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else if ("finite" === check.kind) { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.not_finite, + message: check.message + }); + status.dirty(); + } + } else util_util.assertNever(check); + return { + status: status.value, + value: input.data + }; + } + gte(value1, message) { + return this.setLimit("min", value1, true, errorUtil_errorUtil.toString(message)); + } + gt(value1, message) { + return this.setLimit("min", value1, false, errorUtil_errorUtil.toString(message)); + } + lte(value1, message) { + return this.setLimit("max", value1, true, errorUtil_errorUtil.toString(message)); + } + lt(value1, message) { + return this.setLimit("max", value1, false, errorUtil_errorUtil.toString(message)); + } + setLimit(kind, value1, inclusive, message) { + return new types_ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value: value1, + inclusive, + message: errorUtil_errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new types_ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + check + ] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil_errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil_errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil_errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil_errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil_errorUtil.toString(message) + }); + } + multipleOf(value1, message) { + return this._addCheck({ + kind: "multipleOf", + value: value1, + message: errorUtil_errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil_errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil_errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil_errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks)if ("min" === ch.kind) { + if (null === min || ch.value > min) min = ch.value; + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks)if ("max" === ch.kind) { + if (null === max || ch.value < max) max = ch.value; + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch)=>"int" === ch.kind || "multipleOf" === ch.kind && util_util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks)if ("finite" === ch.kind || "int" === ch.kind || "multipleOf" === ch.kind) return true; + else if ("min" === ch.kind) { + if (null === min || ch.value > min) min = ch.value; + } else if ("max" === ch.kind) { + if (null === max || ch.value < max) max = ch.value; + } + return Number.isFinite(min) && Number.isFinite(max); + } + } + types_ZodNumber.create = (params)=>new types_ZodNumber({ + checks: [], + typeName: types_ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); + class types_ZodBigInt extends types_ZodType { + constructor(){ + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) return this._getInvalidInput(input); + let ctx; + const status = new ParseStatus(); + for (const check of this._def.checks)if ("min" === check.kind) { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if ("max" === check.kind) { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if ("multipleOf" === check.kind) { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else util_util.assertNever(check); + return { + status: status.value, + value: input.data + }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + gte(value1, message) { + return this.setLimit("min", value1, true, errorUtil_errorUtil.toString(message)); + } + gt(value1, message) { + return this.setLimit("min", value1, false, errorUtil_errorUtil.toString(message)); + } + lte(value1, message) { + return this.setLimit("max", value1, true, errorUtil_errorUtil.toString(message)); + } + lt(value1, message) { + return this.setLimit("max", value1, false, errorUtil_errorUtil.toString(message)); + } + setLimit(kind, value1, inclusive, message) { + return new types_ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value: value1, + inclusive, + message: errorUtil_errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new types_ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + check + ] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil_errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil_errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil_errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil_errorUtil.toString(message) + }); + } + multipleOf(value1, message) { + return this._addCheck({ + kind: "multipleOf", + value: value1, + message: errorUtil_errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks)if ("min" === ch.kind) { + if (null === min || ch.value > min) min = ch.value; + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks)if ("max" === ch.kind) { + if (null === max || ch.value < max) max = ch.value; + } + return max; + } + } + types_ZodBigInt.create = (params)=>new types_ZodBigInt({ + checks: [], + typeName: types_ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); + class types_ZodBoolean extends types_ZodType { + _parse(input) { + if (this._def.coerce) input.data = Boolean(input.data); + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + return OK(input.data); + } + } + types_ZodBoolean.create = (params)=>new types_ZodBoolean({ + typeName: types_ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); + class types_ZodDate extends types_ZodType { + _parse(input) { + if (this._def.coerce) input.data = new Date(input.data); + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_date + }); + return parseUtil_INVALID; + } + const status = new ParseStatus(); + let ctx; + for (const check of this._def.checks)if ("min" === check.kind) { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date" + }); + status.dirty(); + } + } else if ("max" === check.kind) { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date" + }); + status.dirty(); + } + } else util_util.assertNever(check); + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check) { + return new types_ZodDate({ + ...this._def, + checks: [ + ...this._def.checks, + check + ] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil_errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil_errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks)if ("min" === ch.kind) { + if (null === min || ch.value > min) min = ch.value; + } + return null != min ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks)if ("max" === ch.kind) { + if (null === max || ch.value < max) max = ch.value; + } + return null != max ? new Date(max) : null; + } + } + types_ZodDate.create = (params)=>new types_ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: types_ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); + class types_ZodSymbol extends types_ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + return OK(input.data); + } + } + types_ZodSymbol.create = (params)=>new types_ZodSymbol({ + typeName: types_ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) + }); + class types_ZodUndefined extends types_ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + return OK(input.data); + } + } + types_ZodUndefined.create = (params)=>new types_ZodUndefined({ + typeName: types_ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) + }); + class types_ZodNull extends types_ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType["null"]) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType["null"], + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + return OK(input.data); + } + } + types_ZodNull.create = (params)=>new types_ZodNull({ + typeName: types_ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) + }); + class types_ZodAny extends types_ZodType { + constructor(){ + super(...arguments); + this._any = true; + } + _parse(input) { + return OK(input.data); + } + } + types_ZodAny.create = (params)=>new types_ZodAny({ + typeName: types_ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) + }); + class types_ZodUnknown extends types_ZodType { + constructor(){ + super(...arguments); + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } + } + types_ZodUnknown.create = (params)=>new types_ZodUnknown({ + typeName: types_ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) + }); + class types_ZodNever extends types_ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + } + types_ZodNever.create = (params)=>new types_ZodNever({ + typeName: types_ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) + }); + class types_ZodVoid extends types_ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType["void"], + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + return OK(input.data); + } + } + types_ZodVoid.create = (params)=>new types_ZodVoid({ + typeName: types_ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) + }); + class types_ZodArray extends types_ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + if (null !== def.exactLength) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodError_ZodIssueCode.too_big : ZodError_ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (null !== def.minLength) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (null !== def.maxLength) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) return Promise.all([ + ...ctx.data + ].map((item, i)=>def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)))).then((result)=>ParseStatus.mergeArray(status, result)); + const result = [ + ...ctx.data + ].map((item, i)=>def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i))); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new types_ZodArray({ + ...this._def, + minLength: { + value: minLength, + message: errorUtil_errorUtil.toString(message) + } + }); + } + max(maxLength, message) { + return new types_ZodArray({ + ...this._def, + maxLength: { + value: maxLength, + message: errorUtil_errorUtil.toString(message) + } + }); + } + length(len, message) { + return new types_ZodArray({ + ...this._def, + exactLength: { + value: len, + message: errorUtil_errorUtil.toString(message) + } + }); + } + nonempty(message) { + return this.min(1, message); + } + } + types_ZodArray.create = (schema, params)=>new types_ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: types_ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); + function deepPartialify(schema) { + if (schema instanceof types_ZodObject) { + const newShape = {}; + for(const key in schema.shape){ + const fieldSchema = schema.shape[key]; + newShape[key] = types_ZodOptional.create(deepPartialify(fieldSchema)); + } + return new types_ZodObject({ + ...schema._def, + shape: ()=>newShape + }); + } + if (schema instanceof types_ZodArray) return new types_ZodArray({ + ...schema._def, + type: deepPartialify(schema.element) + }); + if (schema instanceof types_ZodOptional) return types_ZodOptional.create(deepPartialify(schema.unwrap())); + if (schema instanceof types_ZodNullable) return types_ZodNullable.create(deepPartialify(schema.unwrap())); + if (schema instanceof types_ZodTuple) return types_ZodTuple.create(schema.items.map((item)=>deepPartialify(item))); + else return schema; + } + class types_ZodObject extends types_ZodType { + constructor(){ + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (null !== this._cached) return this._cached; + const shape = this._def.shape(); + const keys = util_util.objectKeys(shape); + this._cached = { + shape, + keys + }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof types_ZodNever && "strip" === this._def.unknownKeys)) { + for(const key in ctx.data)if (!shapeKeys.includes(key)) extraKeys.push(key); + } + const pairs = []; + for (const key of shapeKeys){ + const keyValidator = shape[key]; + const value1 = ctx.data[key]; + pairs.push({ + key: { + status: "valid", + value: key + }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value1, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof types_ZodNever) { + const unknownKeys = this._def.unknownKeys; + if ("passthrough" === unknownKeys) for (const key of extraKeys)pairs.push({ + key: { + status: "valid", + value: key + }, + value: { + status: "valid", + value: ctx.data[key] + } + }); + else if ("strict" === unknownKeys) { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if ("strip" === unknownKeys) ; + else throw new Error("Internal ZodObject error: invalid unknownKeys value."); + } else { + const catchall = this._def.catchall; + for (const key of extraKeys){ + const value1 = ctx.data[key]; + pairs.push({ + key: { + status: "valid", + value: key + }, + value: catchall._parse(new ParseInputLazyPath(ctx, value1, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) return Promise.resolve().then(async ()=>{ + const syncPairs = []; + for (const pair of pairs){ + const key = await pair.key; + const value1 = await pair.value; + syncPairs.push({ + key, + value: value1, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs)=>ParseStatus.mergeObjectSync(status, syncPairs)); + return ParseStatus.mergeObjectSync(status, pairs); + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil_errorUtil.errToObj; + return new types_ZodObject({ + ...this._def, + unknownKeys: "strict", + ...void 0 !== message ? { + errorMap: (issue, ctx)=>{ + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if ("unrecognized_keys" === issue.code) return { + message: errorUtil_errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new types_ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new types_ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + extend(augmentation) { + return new types_ZodObject({ + ...this._def, + shape: ()=>({ + ...this._def.shape(), + ...augmentation + }) + }); + } + merge(merging) { + const merged = new types_ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: ()=>({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: types_ZodFirstPartyTypeKind.ZodObject + }); + return merged; + } + setKey(key, schema) { + return this.augment({ + [key]: schema + }); + } + catchall(index) { + return new types_ZodObject({ + ...this._def, + catchall: index + }); + } + pick(mask) { + const shape = {}; + for (const key of util_util.objectKeys(mask))if (mask[key] && this.shape[key]) shape[key] = this.shape[key]; + return new types_ZodObject({ + ...this._def, + shape: ()=>shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util_util.objectKeys(this.shape))if (!mask[key]) shape[key] = this.shape[key]; + return new types_ZodObject({ + ...this._def, + shape: ()=>shape + }); + } + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util_util.objectKeys(this.shape)){ + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) newShape[key] = fieldSchema; + else newShape[key] = fieldSchema.optional(); + } + return new types_ZodObject({ + ...this._def, + shape: ()=>newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util_util.objectKeys(this.shape))if (mask && !mask[key]) newShape[key] = this.shape[key]; + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while(newField instanceof types_ZodOptional)newField = newField._def.innerType; + newShape[key] = newField; + } + return new types_ZodObject({ + ...this._def, + shape: ()=>newShape + }); + } + keyof() { + return createZodEnum(util_util.objectKeys(this.shape)); + } + } + types_ZodObject.create = (shape, params)=>new types_ZodObject({ + shape: ()=>shape, + unknownKeys: "strip", + catchall: types_ZodNever.create(), + typeName: types_ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); + types_ZodObject.strictCreate = (shape, params)=>new types_ZodObject({ + shape: ()=>shape, + unknownKeys: "strict", + catchall: types_ZodNever.create(), + typeName: types_ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); + types_ZodObject.lazycreate = (shape, params)=>new types_ZodObject({ + shape, + unknownKeys: "strip", + catchall: types_ZodNever.create(), + typeName: types_ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); + class types_ZodUnion extends types_ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options1 = this._def.options; + function handleResults(results) { + for (const result of results)if ("valid" === result.result.status) return result.result; + for (const result of results)if ("dirty" === result.result.status) { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + const unionErrors = results.map((result)=>new ZodError_ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_union, + unionErrors + }); + return parseUtil_INVALID; + } + if (ctx.common.async) return Promise.all(options1.map(async (option)=>{ + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + { + let dirty; + const issues = []; + for (const option of options1){ + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if ("valid" === result.status) return result; + if ("dirty" === result.status && !dirty) dirty = { + result, + ctx: childCtx + }; + if (childCtx.common.issues.length) issues.push(childCtx.common.issues); + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues)=>new ZodError_ZodError(issues)); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_union, + unionErrors + }); + return parseUtil_INVALID; + } + } + get options() { + return this._def.options; + } + } + types_ZodUnion.create = (types, params)=>new types_ZodUnion({ + options: types, + typeName: types_ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); + const getDiscriminator = (type)=>{ + if (type instanceof types_ZodLazy) return getDiscriminator(type.schema); + if (type instanceof ZodEffects) return getDiscriminator(type.innerType()); + if (type instanceof types_ZodLiteral) return [ + type.value + ]; + if (type instanceof types_ZodEnum) return type.options; + if (type instanceof ZodNativeEnum) return util_util.objectValues(type.enum); + else if (type instanceof types_ZodDefault) return getDiscriminator(type._def.innerType); + else if (type instanceof types_ZodUndefined) return [ + void 0 + ]; + else if (type instanceof types_ZodNull) return [ + null + ]; + else if (type instanceof types_ZodOptional) return [ + void 0, + ...getDiscriminator(type.unwrap()) + ]; + else if (type instanceof types_ZodNullable) return [ + null, + ...getDiscriminator(type.unwrap()) + ]; + else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap()); + else if (type instanceof types_ZodReadonly) return getDiscriminator(type.unwrap()); + else if (type instanceof types_ZodCatch) return getDiscriminator(type._def.innerType); + else return []; + }; + class types_ZodDiscriminatedUnion extends types_ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [ + discriminator + ] + }); + return parseUtil_INVALID; + } + if (ctx.common.async) return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + static create(discriminator, options1, params) { + const optionsMap = new Map(); + for (const type of options1){ + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + for (const value1 of discriminatorValues){ + if (optionsMap.has(value1)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value1)}`); + optionsMap.set(value1, type); + } + } + return new types_ZodDiscriminatedUnion({ + typeName: types_ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options: options1, + optionsMap, + ...processCreateParams(params) + }); + } + } + function types_mergeValues(a, b) { + const aType = util_getParsedType(a); + const bType = util_getParsedType(b); + if (a === b) return { + valid: true, + data: a + }; + if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util_util.objectKeys(b); + const sharedKeys = util_util.objectKeys(a).filter((key)=>-1 !== bKeys.indexOf(key)); + const newObj = { + ...a, + ...b + }; + for (const key of sharedKeys){ + const sharedValue = types_mergeValues(a[key], b[key]); + if (!sharedValue.valid) return { + valid: false + }; + newObj[key] = sharedValue.data; + } + return { + valid: true, + data: newObj + }; + } + if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) return { + valid: false + }; + const newArray = []; + for(let index = 0; index < a.length; index++){ + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = types_mergeValues(itemA, itemB); + if (!sharedValue.valid) return { + valid: false + }; + newArray.push(sharedValue.data); + } + return { + valid: true, + data: newArray + }; + } + if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) return { + valid: true, + data: a + }; + return { + valid: false + }; + } + class types_ZodIntersection extends types_ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight)=>{ + if (parseUtil_isAborted(parsedLeft) || parseUtil_isAborted(parsedRight)) return parseUtil_INVALID; + const merged = types_mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_intersection_types + }); + return parseUtil_INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) status.dirty(); + return { + status: status.value, + value: merged.data + }; + }; + if (ctx.common.async) return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right])=>handleParsed(left, right)); + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } + types_ZodIntersection.create = (left, right, params)=>new types_ZodIntersection({ + left: left, + right: right, + typeName: types_ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) + }); + class types_ZodTuple extends types_ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return parseUtil_INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [ + ...ctx.data + ].map((item, itemIndex)=>{ + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x)=>!!x); + if (ctx.common.async) return Promise.all(items).then((results)=>ParseStatus.mergeArray(status, results)); + return ParseStatus.mergeArray(status, items); + } + get items() { + return this._def.items; + } + rest(rest) { + return new types_ZodTuple({ + ...this._def, + rest + }); + } + } + types_ZodTuple.create = (schemas, params)=>{ + if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + return new types_ZodTuple({ + items: schemas, + typeName: types_ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); + }; + class types_ZodRecord extends types_ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for(const key in ctx.data)pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + if (ctx.common.async) return ParseStatus.mergeObjectAsync(status, pairs); + return ParseStatus.mergeObjectSync(status, pairs); + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof types_ZodType) return new types_ZodRecord({ + keyType: first, + valueType: second, + typeName: types_ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); + return new types_ZodRecord({ + keyType: types_ZodString.create(), + valueType: first, + typeName: types_ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } + } + class types_ZodMap extends types_ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [ + ...ctx.data.entries() + ].map(([key, value1], index)=>({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [ + index, + "key" + ])), + value: valueType._parse(new ParseInputLazyPath(ctx, value1, ctx.path, [ + index, + "value" + ])) + })); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async ()=>{ + for (const pair of pairs){ + const key = await pair.key; + const value1 = await pair.value; + if ("aborted" === key.status || "aborted" === value1.status) return parseUtil_INVALID; + if ("dirty" === key.status || "dirty" === value1.status) status.dirty(); + finalMap.set(key.value, value1.value); + } + return { + status: status.value, + value: finalMap + }; + }); + } + { + const finalMap = new Map(); + for (const pair of pairs){ + const key = pair.key; + const value1 = pair.value; + if ("aborted" === key.status || "aborted" === value1.status) return parseUtil_INVALID; + if ("dirty" === key.status || "dirty" === value1.status) status.dirty(); + finalMap.set(key.value, value1.value); + } + return { + status: status.value, + value: finalMap + }; + } + } + } + types_ZodMap.create = (keyType, valueType, params)=>new types_ZodMap({ + valueType, + keyType, + typeName: types_ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); + class types_ZodSet extends types_ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + const def = this._def; + if (null !== def.minSize) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (null !== def.maxSize) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements){ + if ("aborted" === element.status) return parseUtil_INVALID; + if ("dirty" === element.status) status.dirty(); + parsedSet.add(element.value); + } + return { + status: status.value, + value: parsedSet + }; + } + const elements = [ + ...ctx.data.values() + ].map((item, i)=>valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) return Promise.all(elements).then((elements)=>finalizeSet(elements)); + return finalizeSet(elements); + } + min(minSize, message) { + return new types_ZodSet({ + ...this._def, + minSize: { + value: minSize, + message: errorUtil_errorUtil.toString(message) + } + }); + } + max(maxSize, message) { + return new types_ZodSet({ + ...this._def, + maxSize: { + value: maxSize, + message: errorUtil_errorUtil.toString(message) + } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } + } + types_ZodSet.create = (valueType, params)=>new types_ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: types_ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) + }); + class types_ZodFunction extends types_ZodType { + constructor(){ + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType["function"]) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType["function"], + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + errors_getErrorMap(), + locales_en + ].filter((x)=>!!x), + issueData: { + code: ZodError_ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + errors_getErrorMap(), + locales_en + ].filter((x)=>!!x), + issueData: { + code: ZodError_ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { + errorMap: ctx.common.contextualErrorMap + }; + const fn = ctx.data; + if (this._def.returns instanceof types_ZodPromise) { + const me = this; + return OK(async function(...args) { + const error = new ZodError_ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e)=>{ + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e)=>{ + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) throw new ZodError_ZodError([ + makeArgsIssue(args, parsedArgs.error) + ]); + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) throw new ZodError_ZodError([ + makeReturnsIssue(result, parsedReturns.error) + ]); + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new types_ZodFunction({ + ...this._def, + args: types_ZodTuple.create(items).rest(types_ZodUnknown.create()) + }); + } + returns(returnType) { + return new types_ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new types_ZodFunction({ + args: args ? args : types_ZodTuple.create([]).rest(types_ZodUnknown.create()), + returns: returns || types_ZodUnknown.create(), + typeName: types_ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } + } + class types_ZodLazy extends types_ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + types_ZodLazy.create = (getter, params)=>new types_ZodLazy({ + getter: getter, + typeName: types_ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); + class types_ZodLiteral extends types_ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodError_ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return parseUtil_INVALID; + } + return { + status: "valid", + value: input.data + }; + } + get value() { + return this._def.value; + } + } + types_ZodLiteral.create = (value1, params)=>new types_ZodLiteral({ + value: value1, + typeName: types_ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) + }); + function createZodEnum(values, params) { + return new types_ZodEnum({ + values, + typeName: types_ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); + } + class types_ZodEnum extends types_ZodType { + _parse(input) { + if ("string" != typeof input.data) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util_util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_ZodIssueCode.invalid_type + }); + return parseUtil_INVALID; + } + if (!this._cache) this._cache = new Set(this._def.values); + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodError_ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return parseUtil_INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values)enumValues[val] = val; + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values)enumValues[val] = val; + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values)enumValues[val] = val; + return enumValues; + } + extract(values, newDef = this._def) { + return types_ZodEnum.create(values, { + ...this._def, + ...newDef + }); + } + exclude(values, newDef = this._def) { + return types_ZodEnum.create(this.options.filter((opt)=>!values.includes(opt)), { + ...this._def, + ...newDef + }); + } + } + types_ZodEnum.create = createZodEnum; + class ZodNativeEnum extends types_ZodType { + _parse(input) { + const nativeEnumValues = util_util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util_util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util_util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_ZodIssueCode.invalid_type + }); + return parseUtil_INVALID; + } + if (!this._cache) this._cache = new Set(util_util.getValidEnumValues(this._def.values)); + if (!this._cache.has(input.data)) { + const expectedValues = util_util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodError_ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return parseUtil_INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } + } + ZodNativeEnum.create = (values, params)=>new ZodNativeEnum({ + values: values, + typeName: types_ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); + class types_ZodPromise extends types_ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && false === ctx.common.async) { + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data)=>this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }))); + } + } + types_ZodPromise.create = (schema, params)=>new types_ZodPromise({ + type: schema, + typeName: types_ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); + class ZodEffects extends types_ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === types_ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg)=>{ + addIssueToContext(ctx, arg); + if (arg.fatal) status.abort(); + else status.dirty(); + }, + get path () { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if ("preprocess" === effect.type) { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) return Promise.resolve(processed).then(async (processed)=>{ + if ("aborted" === status.value) return parseUtil_INVALID; + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if ("aborted" === result.status) return parseUtil_INVALID; + if ("dirty" === result.status) return DIRTY(result.value); + if ("dirty" === status.value) return DIRTY(result.value); + return result; + }); + { + if ("aborted" === status.value) return parseUtil_INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if ("aborted" === result.status) return parseUtil_INVALID; + if ("dirty" === result.status) return DIRTY(result.value); + if ("dirty" === status.value) return DIRTY(result.value); + return result; + } + } + if ("refinement" === effect.type) { + const executeRefinement = (acc)=>{ + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) return Promise.resolve(result); + if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + return acc; + }; + if (false !== ctx.common.async) return this._def.schema._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }).then((inner)=>{ + if ("aborted" === inner.status) return parseUtil_INVALID; + if ("dirty" === inner.status) status.dirty(); + return executeRefinement(inner.value).then(()=>({ + status: status.value, + value: inner.value + })); + }); + { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if ("aborted" === inner.status) return parseUtil_INVALID; + if ("dirty" === inner.status) status.dirty(); + executeRefinement(inner.value); + return { + status: status.value, + value: inner.value + }; + } + } + if ("transform" === effect.type) if (false !== ctx.common.async) return this._def.schema._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }).then((base)=>{ + if (!isValid(base)) return parseUtil_INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result)=>({ + status: status.value, + value: result + })); + }); + else { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) return parseUtil_INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead."); + return { + status: status.value, + value: result + }; + } + util_util.assertNever(effect); + } + } + ZodEffects.create = (schema, effect, params)=>new ZodEffects({ + schema, + typeName: types_ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); + ZodEffects.createWithPreprocess = (preprocess, schema, params)=>new ZodEffects({ + schema, + effect: { + type: "preprocess", + transform: preprocess + }, + typeName: types_ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); + class types_ZodOptional extends types_ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) return OK(void 0); + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + } + types_ZodOptional.create = (type, params)=>new types_ZodOptional({ + innerType: type, + typeName: types_ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); + class types_ZodNullable extends types_ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType["null"]) return OK(null); + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + } + types_ZodNullable.create = (type, params)=>new types_ZodNullable({ + innerType: type, + typeName: types_ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); + class types_ZodDefault extends types_ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) data = this._def.defaultValue(); + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } + } + types_ZodDefault.create = (type, params)=>new types_ZodDefault({ + innerType: type, + typeName: types_ZodFirstPartyTypeKind.ZodDefault, + defaultValue: "function" == typeof params.default ? params.default : ()=>params.default, + ...processCreateParams(params) + }); + class types_ZodCatch extends types_ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync(result)) return result.then((result)=>({ + status: "valid", + value: "valid" === result.status ? result.value : this._def.catchValue({ + get error () { + return new ZodError_ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + })); + return { + status: "valid", + value: "valid" === result.status ? result.value : this._def.catchValue({ + get error () { + return new ZodError_ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + removeCatch() { + return this._def.innerType; + } + } + types_ZodCatch.create = (type, params)=>new types_ZodCatch({ + innerType: type, + typeName: types_ZodFirstPartyTypeKind.ZodCatch, + catchValue: "function" == typeof params.catch ? params.catch : ()=>params.catch, + ...processCreateParams(params) + }); + class types_ZodNaN extends types_ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodError_ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return parseUtil_INVALID; + } + return { + status: "valid", + value: input.data + }; + } + } + types_ZodNaN.create = (params)=>new types_ZodNaN({ + typeName: types_ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); + Symbol("zod_brand"); + class ZodBranded extends types_ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } + } + class ZodPipeline extends types_ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async ()=>{ + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if ("aborted" === inResult.status) return parseUtil_INVALID; + if ("dirty" !== inResult.status) return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + status.dirty(); + return DIRTY(inResult.value); + }; + return handleAsync(); + } + { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if ("aborted" === inResult.status) return parseUtil_INVALID; + if ("dirty" !== inResult.status) return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: types_ZodFirstPartyTypeKind.ZodPipeline + }); + } + } + class types_ZodReadonly extends types_ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data)=>{ + if (isValid(data)) data.value = Object.freeze(data.value); + return data; + }; + return isAsync(result) ? result.then((data)=>freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } + } + types_ZodReadonly.create = (type, params)=>new types_ZodReadonly({ + innerType: type, + typeName: types_ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) + }); + types_ZodObject.lazycreate; + var types_ZodFirstPartyTypeKind; + (function(ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; + })(types_ZodFirstPartyTypeKind || (types_ZodFirstPartyTypeKind = {})); + types_ZodString.create; + types_ZodNumber.create; + types_ZodNaN.create; + types_ZodBigInt.create; + types_ZodBoolean.create; + types_ZodDate.create; + types_ZodSymbol.create; + types_ZodUndefined.create; + types_ZodNull.create; + types_ZodAny.create; + types_ZodUnknown.create; + types_ZodNever.create; + types_ZodVoid.create; + types_ZodArray.create; + types_ZodObject.create; + types_ZodObject.strictCreate; + types_ZodUnion.create; + types_ZodDiscriminatedUnion.create; + types_ZodIntersection.create; + types_ZodTuple.create; + types_ZodRecord.create; + types_ZodMap.create; + types_ZodSet.create; + types_ZodFunction.create; + types_ZodLazy.create; + types_ZodLiteral.create; + types_ZodEnum.create; + ZodNativeEnum.create; + types_ZodPromise.create; + ZodEffects.create; + types_ZodOptional.create; + types_ZodNullable.create; + ZodEffects.createWithPreprocess; + ZodPipeline.create; + class ParseError extends Error { + constructor(message, options1){ + super(message), this.name = "ParseError", this.type = options1.type, this.field = options1.field, this.value = options1.value, this.line = options1.line; + } + } + function noop(_arg) {} + function createParser(callbacks) { + if ("function" == typeof callbacks) 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; + let incompleteLine = "", isFirstChunk = !0, id, data = "", eventType = ""; + function feed(newChunk) { + const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`); + for (const line of complete)parseLine(line); + incompleteLine = incomplete, isFirstChunk = !1; + } + function parseLine(line) { + if ("" === line) return void dispatchEvent(); + if (line.startsWith(":")) { + onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1)); + return; + } + const fieldSeparatorIndex = line.indexOf(":"); + if (-1 !== fieldSeparatorIndex) { + const field = line.slice(0, fieldSeparatorIndex), offset = " " === line[fieldSeparatorIndex + 1] ? 2 : 1, value1 = line.slice(fieldSeparatorIndex + offset); + processField(field, value1, line); + return; + } + processField(line, "", line); + } + function processField(field, value1, line) { + switch(field){ + case "event": + eventType = value1; + break; + case "data": + data = `${data}${value1} +`; + break; + case "id": + id = value1.includes("\0") ? void 0 : value1; + break; + case "retry": + /^\d+$/.test(value1) ? onRetry(parseInt(value1, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value1}"`, { + type: "invalid-retry", + value: value1, + line + })); + break; + default: + onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { + type: "unknown-field", + field, + value: value1, + line + })); + break; + } + } + function dispatchEvent() { + data.length > 0 && onEvent({ + id, + event: eventType || void 0, + data: data.endsWith(` +`) ? data.slice(0, -1) : data + }), id = void 0, data = "", eventType = ""; + } + function reset(options1 = {}) { + incompleteLine && options1.consume && parseLine(incompleteLine), isFirstChunk = !0, id = void 0, data = "", eventType = "", incompleteLine = ""; + } + return { + feed, + reset + }; + } + function splitLines(chunk) { + const lines = []; + let incompleteLine = "", searchIndex = 0; + for(; searchIndex < chunk.length;){ + const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` +`, searchIndex); + let lineEnd = -1; + if (-1 !== crIndex && -1 !== lfIndex ? lineEnd = Math.min(crIndex, lfIndex) : -1 !== crIndex ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : -1 !== lfIndex && (lineEnd = lfIndex), -1 === lineEnd) { + incompleteLine = chunk.slice(searchIndex); + break; + } + { + const line = chunk.slice(searchIndex, lineEnd); + lines.push(line), searchIndex = lineEnd + 1, "\r" === chunk[searchIndex - 1] && chunk[searchIndex] === ` +` && searchIndex++; + } + } + return [ + lines, + incompleteLine + ]; + } + class EventSourceParserStream extends TransformStream { + constructor({ onError, onRetry, onComment } = {}){ + let parser; + super({ + start (controller) { + parser = createParser({ + onEvent: (event)=>{ + controller.enqueue(event); + }, + onError (error) { + "terminate" === onError ? controller.error(error) : "function" == typeof onError && onError(error); + }, + onRetry, + onComment + }); + }, + transform (chunk) { + parser.feed(chunk); + } + }); + } + } + function combineHeaders(...headers) { + return headers.reduce((combinedHeaders, currentHeaders)=>({ + ...combinedHeaders, + ...null != currentHeaders ? currentHeaders : {} + }), {}); + } + function createToolNameMapping({ tools = [], providerToolNames, resolveProviderToolName }) { + var _a2; + const customToolNameToProviderToolName = {}; + const providerToolNameToCustomToolName = {}; + for (const tool2 of tools)if ("provider" === tool2.type) { + const providerToolName = null != (_a2 = null == resolveProviderToolName ? void 0 : resolveProviderToolName(tool2)) ? _a2 : tool2.id in providerToolNames ? providerToolNames[tool2.id] : void 0; + if (null == providerToolName) continue; + customToolNameToProviderToolName[tool2.name] = providerToolName; + providerToolNameToCustomToolName[providerToolName] = tool2.name; + } + return { + toProviderToolName: (customToolName)=>{ + var _a3; + return null != (_a3 = customToolNameToProviderToolName[customToolName]) ? _a3 : customToolName; + }, + toCustomToolName: (providerToolName)=>{ + var _a3; + return null != (_a3 = providerToolNameToCustomToolName[providerToolName]) ? _a3 : providerToolName; + } + }; + } + async function delay(delayInMs, options1) { + if (null == delayInMs) return Promise.resolve(); + const signal = null == options1 ? void 0 : options1.abortSignal; + return new Promise((resolve2, reject)=>{ + if (null == signal ? void 0 : signal.aborted) return void reject(createAbortError()); + const timeoutId = setTimeout(()=>{ + cleanup(); + resolve2(); + }, delayInMs); + const cleanup = ()=>{ + clearTimeout(timeoutId); + null == signal || signal.removeEventListener("abort", onAbort); + }; + const onAbort = ()=>{ + cleanup(); + reject(createAbortError()); + }; + null == signal || signal.addEventListener("abort", onAbort); + }); + } + function createAbortError() { + return new DOMException("Delay was aborted", "AbortError"); + } + function extractResponseHeaders(response) { + return Object.fromEntries([ + ...response.headers + ]); + } + var { btoa: dist_btoa, atob: dist_atob } = globalThis; + function convertBase64ToUint8Array(base64String) { + const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/"); + const latin1string = dist_atob(base64Url); + return Uint8Array.from(latin1string, (byte)=>byte.codePointAt(0)); + } + function convertUint8ArrayToBase64(array) { + let latin1string = ""; + for(let i = 0; i < array.length; i++)latin1string += String.fromCodePoint(array[i]); + return dist_btoa(latin1string); + } + function convertToBase64(value1) { + return value1 instanceof Uint8Array ? convertUint8ArrayToBase64(value1) : value1; + } + function convertToFormData(input, options1 = {}) { + const { useArrayBrackets = true } = options1; + const formData = new FormData(); + for (const [key, value1] of Object.entries(input))if (null != value1) { + if (Array.isArray(value1)) { + if (1 === value1.length) { + formData.append(key, value1[0]); + continue; + } + const arrayKey = useArrayBrackets ? `${key}[]` : key; + for (const item of value1)formData.append(arrayKey, item); + continue; + } + formData.append(key, value1); + } + return formData; + } + var provider_utils_dist_name = "AI_DownloadError"; + var dist_marker = `vercel.ai.error.${provider_utils_dist_name}`; + var dist_symbol = Symbol.for(dist_marker); + var provider_utils_dist_a, provider_utils_dist_b; + var DownloadError = class extends (provider_utils_dist_b = AISDKError, provider_utils_dist_a = dist_symbol, provider_utils_dist_b) { + constructor({ url, statusCode, statusText, cause, message = null == cause ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }){ + super({ + name: provider_utils_dist_name, + message, + cause + }); + this[provider_utils_dist_a] = true; + this.url = url; + this.statusCode = statusCode; + this.statusText = statusText; + } + static isInstance(error) { + return AISDKError.hasMarker(error, dist_marker); + } + }; + var DEFAULT_MAX_DOWNLOAD_SIZE = 2147483648; + async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) { + const contentLength = response.headers.get("content-length"); + if (null != contentLength) { + 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 (null == body) return new Uint8Array(0); + const reader = body.getReader(); + const chunks = []; + let totalBytes = 0; + try { + while(true){ + const { done, value: value1 } = await reader.read(); + if (done) break; + totalBytes += value1.length; + if (totalBytes > maxBytes) throw new DownloadError({ + url, + message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.` + }); + chunks.push(value1); + } + } 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 ("data:" === parsed.protocol) return; + if ("http:" !== parsed.protocol && "https:" !== parsed.protocol) 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 ("localhost" === hostname || 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 (4 !== parts.length) 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 (0 === a) return true; + if (10 === a) return true; + if (127 === a) return true; + if (169 === a && 254 === b) return true; + if (172 === a && b >= 16 && b <= 31) return true; + if (192 === a && 168 === b) return true; + return false; + } + function isPrivateIPv6(ip) { + const normalized = ip.toLowerCase(); + if ("::1" === normalized) 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 (2 === hexParts.length) { + const high = parseInt(hexParts[0], 16); + const low = parseInt(hexParts[1], 16); + if (!isNaN(high) && !isNaN(low)) { + const a = high >> 8 & 255; + const b = 255 & high; + const c = low >> 8 & 255; + const d = 255 & low; + return isPrivateIPv4(`${a}.${b}.${c}.${d}`); + } + } + } + if (normalized.startsWith("fc") || normalized.startsWith("fd")) return true; + if (normalized.startsWith("fe80")) return true; + return false; + } + async function downloadBlob(url, options1) { + var _a2, _b2; + validateDownloadUrl(url); + try { + const response = await fetch(url, { + signal: null == options1 ? void 0 : options1.abortSignal + }); + if (response.redirected) validateDownloadUrl(response.url); + if (!response.ok) throw new DownloadError({ + url, + statusCode: response.status, + statusText: response.statusText + }); + const data = await readResponseWithSizeLimit({ + response, + url, + maxBytes: null != (_a2 = null == options1 ? void 0 : options1.maxBytes) ? _a2 : DEFAULT_MAX_DOWNLOAD_SIZE + }); + const contentType = null != (_b2 = response.headers.get("content-type")) ? _b2 : void 0; + return new Blob([ + data + ], contentType ? { + type: contentType + } : void 0); + } catch (error) { + if (DownloadError.isInstance(error)) throw error; + throw new DownloadError({ + url, + cause: error + }); + } + } + 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 (null == prefix) 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()}`; + }; + var generateId = createIdGenerator(); + function dist_getErrorMessage(error) { + if (null == error) return "unknown error"; + if ("string" == typeof error) return error; + if (error instanceof Error) return error.message; + return JSON.stringify(error); + } + function isAbortError(error) { + return (error instanceof Error || error instanceof DOMException) && ("AbortError" === error.name || "ResponseAborted" === error.name || "TimeoutError" === error.name); + } + 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 ("string" == typeof code && 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 (null != cause) return new APICallError({ + message: `Cannot connect to API: ${cause.message}`, + cause, + url, + requestBodyValues, + isRetryable: true + }); + } + if (isBunNetworkError(error)) return new APICallError({ + message: `Cannot connect to API: ${error.message}`, + cause: error, + url, + requestBodyValues, + isRetryable: true + }); + return error; + } + function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) { + var _a2, _b2, _c; + if (globalThisAny.window) return "runtime/browser"; + if (null == (_a2 = globalThisAny.navigator) ? void 0 : _a2.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`; + if (null == (_c = null == (_b2 = globalThisAny.process) ? void 0 : _b2.versions) ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`; + if (globalThisAny.EdgeRuntime) return "runtime/vercel-edge"; + return "runtime/unknown"; + } + function dist_normalizeHeaders(headers) { + if (null == headers) return {}; + const normalized = {}; + if (headers instanceof Headers) headers.forEach((value1, key)=>{ + normalized[key.toLowerCase()] = value1; + }); + else { + if (!Array.isArray(headers)) headers = Object.entries(headers); + for (const [key, value1] of headers)if (null != value1) normalized[key.toLowerCase()] = value1; + } + return normalized; + } + function withUserAgentSuffix(headers, ...userAgentSuffixParts) { + const normalizedHeaders = new Headers(dist_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.23"; + 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 dist_isNonNullable(value1) { + return null != value1; + } + function isUrlSupported({ mediaType, url, supportedUrls }) { + url = url.toLowerCase(); + mediaType = mediaType.toLowerCase(); + return Object.entries(supportedUrls).map(([key, value1])=>{ + const mediaType2 = key.toLowerCase(); + return "*" === mediaType2 || "*/*" === mediaType2 ? { + mediaTypePrefix: "", + regexes: value1 + } : { + mediaTypePrefix: mediaType2.replace(/\*/, ""), + regexes: value1 + }; + }).filter(({ mediaTypePrefix })=>mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes })=>regexes).some((pattern)=>pattern.test(url)); + } + function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName = "apiKey", description }) { + if ("string" == typeof apiKey) return apiKey; + if (null != apiKey) throw new LoadAPIKeyError({ + message: `${description} API key must be a string.` + }); + if ("undefined" == typeof process) throw new LoadAPIKeyError({ + message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables are not supported in this environment.` + }); + apiKey = process.env[environmentVariableName]; + if (null == apiKey) throw new LoadAPIKeyError({ + message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` + }); + if ("string" != typeof apiKey) throw new LoadAPIKeyError({ + message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.` + }); + return apiKey; + } + function loadOptionalSetting({ settingValue, environmentVariableName }) { + if ("string" == typeof settingValue) return settingValue; + if (null != settingValue || "undefined" == typeof process) return; + settingValue = process.env[environmentVariableName]; + if (null == settingValue || "string" != typeof settingValue) return; + return settingValue; + } + function mediaTypeToExtension(mediaType) { + var _a2; + const [_type, subtype = ""] = mediaType.toLowerCase().split("/"); + return null != (_a2 = ({ + mpeg: "mp3", + "x-wav": "wav", + opus: "ogg", + mp4: "m4a", + "x-m4a": "m4a" + })[subtype]) ? _a2 : subtype; + } + 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 dist_parse(text) { + const obj = JSON.parse(text); + if (null === obj || "object" != typeof obj) return obj; + if (false === suspectProtoRx.test(text) && false === suspectConstructorRx.test(text)) return obj; + return dist_filter(obj); + } + function dist_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") && null !== node.constructor && "object" == typeof node.constructor && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) throw new SyntaxError("Object contains forbidden prototype property"); + for(const key in node){ + const value1 = node[key]; + if (value1 && "object" == typeof value1) next.push(value1); + } + } + } + return obj; + } + function secureJsonParse(text) { + const { stackTraceLimit } = Error; + try { + Error.stackTraceLimit = 0; + } catch (e) { + return dist_parse(text); + } + try { + return dist_parse(text); + } finally{ + Error.stackTraceLimit = stackTraceLimit; + } + } + function addAdditionalPropertiesToJsonSchema(jsonSchema2) { + if ("object" === jsonSchema2.type || Array.isArray(jsonSchema2.type) && jsonSchema2.type.includes("object")) { + jsonSchema2.additionalProperties = false; + const { properties } = jsonSchema2; + if (null != properties) for (const key of Object.keys(properties))properties[key] = visit(properties[key]); + } + if (null != jsonSchema2.items) jsonSchema2.items = Array.isArray(jsonSchema2.items) ? jsonSchema2.items.map(visit) : visit(jsonSchema2.items); + if (null != jsonSchema2.anyOf) jsonSchema2.anyOf = jsonSchema2.anyOf.map(visit); + if (null != jsonSchema2.allOf) jsonSchema2.allOf = jsonSchema2.allOf.map(visit); + if (null != jsonSchema2.oneOf) jsonSchema2.oneOf = jsonSchema2.oneOf.map(visit); + const { definitions } = jsonSchema2; + if (null != definitions) for (const key of Object.keys(definitions))definitions[key] = visit(definitions[key]); + return jsonSchema2; + } + function visit(def) { + if ("boolean" == typeof def) 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 = (options1)=>"string" == typeof options1 ? { + ...defaultOptions, + name: options1 + } : { + ...defaultOptions, + ...options1 + }; + function parseAnyDef() { + return {}; + } + function parseArrayDef(def, refs) { + var _a2, _b2, _c; + const res = { + type: "array" + }; + if ((null == (_a2 = def.type) ? void 0 : _a2._def) && (null == (_c = null == (_b2 = def.type) ? void 0 : _b2._def) ? void 0 : _c.typeName) !== types_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)=>parseDef(def.innerType._def, refs); + function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = null != overrideDateStrategy ? 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 "input" === refs.effectStrategy ? parseDef(_def.schema._def, refs) : parseAnyDef(); + } + function parseEnumDef(def) { + return { + type: "string", + enum: Array.from(def.values) + }; + } + var isJsonSchema7AllOfType = (type)=>{ + if ("type" in type && "string" === type.type) 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 && false === schema.additionalProperties) { + 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 ("bigint" !== parsedType && "number" !== parsedType && "boolean" !== parsedType && "string" !== parsedType) return { + type: Array.isArray(def.value) ? "array" : "object" + }; + return { + type: "bigint" === parsedType ? "integer" : parsedType, + const: def.value + }; + } + var dist_emojiRegex = void 0; + var zodPatterns = { + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + emoji: ()=>{ + if (void 0 === dist_emojiRegex) dist_emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + return dist_emojiRegex; + }, + 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}$/, + 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])$/, + 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 = "number" == typeof res.minLength ? Math.max(res.minLength, check.value) : check.value; + break; + case "max": + res.maxLength = "number" == typeof res.maxLength ? 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 = "number" == typeof res.minLength ? Math.max(res.minLength, check.value) : check.value; + res.maxLength = "number" == typeof res.maxLength ? 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 ("v6" !== check.version) addFormat(res, "ipv4", check.message, refs); + if ("v4" !== check.version) 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 ("v6" !== check.version) addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); + if ("v4" !== check.version) addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); + break; + case "emoji": + addPattern(res, zodPatterns.emoji(), check.message, refs); + break; + case "ulid": + addPattern(res, zodPatterns.ulid, check.message, refs); + break; + case "base64": + switch(refs.base64Strategy){ + case "format:binary": + addFormat(res, "binary", check.message, refs); + break; + case "contentEncoding:base64": + res.contentEncoding = "base64"; + break; + case "pattern:zod": + addPattern(res, zodPatterns.base64, check.message, refs); + break; + } + break; + case "nanoid": + addPattern(res, zodPatterns.nanoid, check.message, refs); + case "toLowerCase": + case "toUpperCase": + case "trim": + break; + default: + } + return res; + } + function escapeLiteralCheckValue(literal, refs) { + return "escape" === refs.patternStrategy ? 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, value1, message, refs) { + var _a2; + if (schema.format || (null == (_a2 = schema.anyOf) ? 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: value1, + ...message && refs.errorMessages && { + errorMessage: { + format: message + } + } + }); + } else schema.format = value1; + } + function addPattern(schema, regex, message, refs) { + var _a2; + if (schema.pattern || (null == (_a2 = schema.allOf) ? 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] && (null == (_a2 = source[i + 2]) ? 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: null != (_a2 = parseDef(def.valueType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "additionalProperties" + ] + })) ? _a2 : refs.allowedAdditionalProperties + }; + if ((null == (_b2 = def.keyType) ? void 0 : _b2._def.typeName) === types_ZodFirstPartyTypeKind.ZodString && (null == (_c = def.keyType._def.checks) ? void 0 : _c.length)) { + const { type, ...keyType } = parseStringDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } + if ((null == (_d = def.keyType) ? void 0 : _d._def.typeName) === types_ZodFirstPartyTypeKind.ZodEnum) return { + ...schema, + propertyNames: { + enum: def.keyType._def.values + } + }; + if ((null == (_e = def.keyType) ? void 0 : _e._def.typeName) === types_ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === types_ZodFirstPartyTypeKind.ZodString && (null == (_f = def.keyType._def.type._def.checks) ? void 0 : _f.length)) { + const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } + return schema; + } + function parseMapDef(def, refs) { + if ("record" === refs.mapStrategy) 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 object = def.values; + const actualKeys = Object.keys(def.values).filter((key)=>"number" != typeof object[object[key]]); + const actualValues = actualKeys.map((key)=>object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values)=>typeof values))); + return { + type: 1 === parsedTypes.length ? "string" === parsedTypes[0] ? "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 options1 = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + if (options1.every((x)=>x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { + const types = options1.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] + }; + } + if (options1.every((x)=>"ZodLiteral" === x._def.typeName && !x.description)) { + const types = options1.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 (null === x._def.value) return [ + ...acc, + "null" + ]; + case "symbol": + case "undefined": + case "function": + default: + return acc; + } + }, []); + if (types.length === options1.length) { + const uniqueTypes = types.filter((x, i, a)=>a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options1.reduce((acc, x)=>acc.includes(x._def.value) ? acc : [ + ...acc, + x._def.value + ], []) + }; + } + } else if (options1.every((x)=>"ZodEnum" === x._def.typeName)) return { + type: "string", + enum: options1.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 || "object" == typeof x && Object.keys(x).length > 0)); + return anyOf.length ? { + anyOf + } : void 0; + }; + function parseNullableDef(def, refs) { + if ([ + "ZodString", + "ZodNumber", + "ZodBigInt", + "ZodBoolean", + "ZodNull" + ].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) return { + type: [ + primitiveMappings[def.innerType._def.typeName], + "null" + ] + }; + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + "0" + ] + }); + return base && { + anyOf: [ + base, + { + type: "null" + } + ] + }; + } + function parseNumberDef(def) { + const res = { + type: "number" + }; + if (!def.checks) return res; + for (const check of def.checks)switch(check.kind){ + case "int": + res.type = "integer"; + break; + case "min": + if (check.inclusive) res.minimum = check.value; + else res.exclusiveMinimum = check.value; + break; + case "max": + if (check.inclusive) res.maximum = check.value; + else res.exclusiveMaximum = check.value; + break; + case "multipleOf": + res.multipleOf = check.value; + break; + } + return res; + } + function parseObjectDef(def, refs) { + const result = { + type: "object", + properties: {} + }; + const required = []; + const shape = def.shape(); + for(const propName in shape){ + let propDef = shape[propName]; + if (void 0 === propDef || void 0 === propDef._def) continue; + const propOptional = safeIsOptional(propDef); + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "properties", + propName + ], + propertyPath: [ + ...refs.currentPath, + "properties", + propName + ] + }); + if (void 0 !== parsedDef) { + result.properties[propName] = parsedDef; + if (!propOptional) required.push(propName); + } + } + if (required.length) result.required = required; + const additionalProperties = decideAdditionalProperties(def, refs); + if (void 0 !== additionalProperties) result.additionalProperties = additionalProperties; + return result; + } + function decideAdditionalProperties(def, refs) { + if ("ZodNever" !== def.catchall._def.typeName) 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 "strict" === refs.removeAdditionalStrategy ? 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() === (null == (_a2 = refs.propertyPath) ? 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 ("input" === refs.pipeStrategy) return parseDef(def.in._def, refs); + if ("output" === refs.pipeStrategy) return parseDef(def.out._def, refs); + const a = parseDef(def.in._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "0" + ] + }); + const b = parseDef(def.out._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + a ? "1" : "0" + ] + }); + return { + allOf: [ + a, + b + ].filter((x)=>void 0 !== x) + }; + }; + function parsePromiseDef(def, refs) { + return parseDef(def.type._def, refs); + } + function parseSetDef(def, refs) { + const items = parseDef(def.valueType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items" + ] + }); + const schema = { + type: "array", + uniqueItems: true, + 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)=>void 0 === x ? acc : [ + ...acc, + x + ], []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "additionalItems" + ] + }) + }; + 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)=>void 0 === x ? acc : [ + ...acc, + x + ], []) + }; + } + function parseUndefinedDef() { + return { + not: parseAnyDef() + }; + } + function parseUnknownDef() { + return parseAnyDef(); + } + var parseReadonlyDef = (def, refs)=>parseDef(def.innerType._def, refs); + var selectParser = (def, typeName, refs)=>{ + switch(typeName){ + case types_ZodFirstPartyTypeKind.ZodString: + return parseStringDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodNumber: + return parseNumberDef(def); + case types_ZodFirstPartyTypeKind.ZodObject: + return parseObjectDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodBigInt: + return parseBigintDef(def); + case types_ZodFirstPartyTypeKind.ZodBoolean: + return parseBooleanDef(); + case types_ZodFirstPartyTypeKind.ZodDate: + return parseDateDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodUndefined: + return parseUndefinedDef(); + case types_ZodFirstPartyTypeKind.ZodNull: + return parseNullDef(); + case types_ZodFirstPartyTypeKind.ZodArray: + return parseArrayDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodUnion: + case types_ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return parseUnionDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodIntersection: + return parseIntersectionDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodTuple: + return parseTupleDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodRecord: + return parseRecordDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodLiteral: + return parseLiteralDef(def); + case types_ZodFirstPartyTypeKind.ZodEnum: + return parseEnumDef(def); + case types_ZodFirstPartyTypeKind.ZodNativeEnum: + return parseNativeEnumDef(def); + case types_ZodFirstPartyTypeKind.ZodNullable: + return parseNullableDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodOptional: + return parseOptionalDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodMap: + return parseMapDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodSet: + return parseSetDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodLazy: + return ()=>def.getter()._def; + case types_ZodFirstPartyTypeKind.ZodPromise: + return parsePromiseDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodNaN: + case types_ZodFirstPartyTypeKind.ZodNever: + return parseNeverDef(); + case types_ZodFirstPartyTypeKind.ZodEffects: + return parseEffectsDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodAny: + return parseAnyDef(); + case types_ZodFirstPartyTypeKind.ZodUnknown: + return parseUnknownDef(); + case types_ZodFirstPartyTypeKind.ZodDefault: + return parseDefaultDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodBranded: + return parseBrandedDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodReadonly: + return parseReadonlyDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodCatch: + return parseCatchDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodPipeline: + return parsePipelineDef(def, refs); + case types_ZodFirstPartyTypeKind.ZodFunction: + case types_ZodFirstPartyTypeKind.ZodVoid: + case types_ZodFirstPartyTypeKind.ZodSymbol: + return; + default: + return /* @__PURE__ */ ((_1)=>void 0)(0); + } + }; + var getRelativePath = (pathA, pathB)=>{ + let i = 0; + for(; i < pathA.length && i < pathB.length && pathA[i] === pathB[i]; i++); + 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 = null == (_a2 = refs.override) ? void 0 : _a2.call(refs, def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) return overrideResult; + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (void 0 !== seenSchema) 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 = "function" == typeof jsonSchemaOrGetter ? 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((value1, index)=>refs.currentPath[index] === value1)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return parseAnyDef(); + } + return "seen" === refs.$refStrategy ? parseAnyDef() : void 0; + } + }; + var addMeta = (def, refs, jsonSchema2)=>{ + if (def.description) jsonSchema2.description = def.description; + return jsonSchema2; + }; + var getRefs = (options1)=>{ + const _options = getDefaultOptions(options1); + const currentPath = void 0 !== _options.name ? [ + ..._options.basePath, + _options.definitionPath, + _options.name + ] : _options.basePath; + return { + ..._options, + currentPath, + propertyPath: void 0, + seen: new Map(Object.entries(_options.definitions).map(([name2, def])=>[ + def._def, + { + def: def._def, + path: [ + ..._options.basePath, + _options.definitionPath, + name2 + ], + jsonSchema: void 0 + } + ])) + }; + }; + var zod3ToJsonSchema = (schema, options1)=>{ + var _a2; + const refs = getRefs(options1); + let definitions = "object" == typeof options1 && options1.definitions ? Object.entries(options1.definitions).reduce((acc, [name3, schema2])=>{ + var _a3; + return { + ...acc, + [name3]: null != (_a3 = parseDef(schema2._def, { + ...refs, + currentPath: [ + ...refs.basePath, + refs.definitionPath, + name3 + ] + }, true)) ? _a3 : parseAnyDef() + }; + }, {}) : void 0; + const name2 = "string" == typeof options1 ? options1 : (null == options1 ? void 0 : options1.nameStrategy) === "title" ? void 0 : null == options1 ? void 0 : options1.name; + const main = null != (_a2 = parseDef(schema._def, void 0 === name2 ? refs : { + ...refs, + currentPath: [ + ...refs.basePath, + refs.definitionPath, + name2 + ] + }, false)) ? _a2 : parseAnyDef(); + const title = "object" == typeof options1 && void 0 !== options1.name && "title" === options1.nameStrategy ? options1.name : void 0; + if (void 0 !== title) main.title = title; + const combined = void 0 === name2 ? definitions ? { + ...main, + [refs.definitionPath]: definitions + } : main : { + $ref: [ + ..."relative" === refs.$refStrategy ? [] : refs.basePath, + refs.definitionPath, + name2 + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name2]: main + } + }; + combined.$schema = "http://json-schema.org/draft-07/schema#"; + return combined; + }; + var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema"); + function dist_lazySchema(createSchema) { + let schema; + return ()=>{ + if (null == schema) schema = createSchema(); + return schema; + }; + } + function dist_jsonSchema(jsonSchema2, { validate } = {}) { + return { + [schemaSymbol]: true, + _type: void 0, + get jsonSchema () { + if ("function" == typeof jsonSchema2) jsonSchema2 = jsonSchema2(); + return jsonSchema2; + }, + validate + }; + } + function isSchema(value1) { + return "object" == typeof value1 && null !== value1 && schemaSymbol in value1 && true === value1[schemaSymbol] && "jsonSchema" in value1 && "validate" in value1; + } + function asSchema(schema) { + return null == schema ? dist_jsonSchema({ + properties: {}, + additionalProperties: false + }) : isSchema(schema) ? schema : "~standard" in schema ? "zod" === schema["~standard"].vendor ? dist_zodSchema(schema) : standardSchema(schema) : schema(); + } + function standardSchema(standardSchema2) { + return dist_jsonSchema(()=>addAdditionalPropertiesToJsonSchema(standardSchema2["~standard"].jsonSchema.input({ + target: "draft-07" + })), { + validate: async (value1)=>{ + const result = await standardSchema2["~standard"].validate(value1); + return "value" in result ? { + success: true, + value: result.value + } : { + success: false, + error: new TypeValidationError({ + value: value1, + cause: result.issues + }) + }; + } + }); + } + function zod3Schema(zodSchema2, options1) { + var _a2; + const useReferences = null != (_a2 = null == options1 ? void 0 : options1.useReferences) ? _a2 : false; + return dist_jsonSchema(()=>zod3ToJsonSchema(zodSchema2, { + $refStrategy: useReferences ? "root" : "none" + }), { + validate: async (value1)=>{ + const result = await zodSchema2.safeParseAsync(value1); + return result.success ? { + success: true, + value: result.data + } : { + success: false, + error: result.error + }; + } + }); + } + function zod4Schema(zodSchema2, options1) { + var _a2; + const useReferences = null != (_a2 = null == options1 ? void 0 : options1.useReferences) ? _a2 : false; + return dist_jsonSchema(()=>addAdditionalPropertiesToJsonSchema(toJSONSchema(zodSchema2, { + target: "draft-7", + io: "input", + reused: useReferences ? "ref" : "inline" + })), { + validate: async (value1)=>{ + const result = await parse_safeParseAsync(zodSchema2, value1); + return result.success ? { + success: true, + value: result.data + } : { + success: false, + error: result.error + }; + } + }); + } + function isZod4Schema(zodSchema2) { + return "_zod" in zodSchema2; + } + function dist_zodSchema(zodSchema2, options1) { + if (isZod4Schema(zodSchema2)) return zod4Schema(zodSchema2, options1); + return zod3Schema(zodSchema2, options1); + } + async function dist_validateTypes({ value: value1, schema, context }) { + const result = await safeValidateTypes({ + value: value1, + schema, + context + }); + if (!result.success) throw TypeValidationError.wrap({ + value: value1, + cause: result.error, + context + }); + return result.value; + } + async function safeValidateTypes({ value: value1, schema, context }) { + const actualSchema = asSchema(schema); + try { + if (null == actualSchema.validate) return { + success: true, + value: value1, + rawValue: value1 + }; + const result = await actualSchema.validate(value1); + if (result.success) return { + success: true, + value: result.value, + rawValue: value1 + }; + return { + success: false, + error: TypeValidationError.wrap({ + value: value1, + cause: result.error, + context + }), + rawValue: value1 + }; + } catch (error) { + return { + success: false, + error: TypeValidationError.wrap({ + value: value1, + cause: error, + context + }), + rawValue: value1 + }; + } + } + async function parseJSON({ text, schema }) { + try { + const value1 = secureJsonParse(text); + if (null == schema) return value1; + return dist_validateTypes({ + value: value1, + 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 value1 = secureJsonParse(text); + if (null == schema) return { + success: true, + value: value1, + rawValue: value1 + }; + return await safeValidateTypes({ + value: value1, + schema + }); + } catch (error) { + return { + success: false, + error: JSONParseError.isInstance(error) ? error : new JSONParseError({ + text, + cause: error + }), + rawValue: void 0 + }; + } + } + function isParsableJson(input) { + try { + secureJsonParse(input); + return true; + } catch (e) { + return false; + } + } + function dist_parseJsonEventStream({ stream, schema }) { + return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(new TransformStream({ + async transform ({ data }, controller) { + if ("[DONE]" === data) return; + controller.enqueue(await safeParseJSON({ + text: data, + schema + })); + } + })); + } + async function parseProviderOptions({ provider, providerOptions, schema }) { + if ((null == providerOptions ? void 0 : providerOptions[provider]) == null) return; + const parsedProviderOptions = await safeValidateTypes({ + value: providerOptions[provider], + schema + }); + if (!parsedProviderOptions.success) throw new InvalidArgumentError({ + argument: "providerOptions", + message: `invalid ${provider} provider options`, + cause: parsedProviderOptions.error + }); + return parsedProviderOptions.value; + } + var getOriginalFetch2 = ()=>globalThis.fetch; + var postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 })=>postToApi({ + url, + headers: { + "Content-Type": "application/json", + ...headers + }, + body: { + content: JSON.stringify(body), + values: body + }, + failedResponseHandler, + successfulResponseHandler, + abortSignal, + fetch: fetch2 + }); + var postFormDataToApi = async ({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 })=>postToApi({ + url, + headers, + body: { + content: formData, + values: Object.fromEntries(formData.entries()) + }, + failedResponseHandler, + successfulResponseHandler, + abortSignal, + fetch: fetch2 + }); + var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch2() })=>{ + try { + const response = await fetch2(url, { + method: "POST", + headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION}`, 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 dist_tool(tool2) { + return tool2; + } + function createProviderToolFactory({ id, inputSchema }) { + return ({ execute, outputSchema, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args })=>dist_tool({ + type: "provider", + id, + args, + inputSchema, + outputSchema, + execute, + needsApproval, + toModelOutput, + onInputStart, + onInputDelta, + onInputAvailable + }); + } + function createProviderToolFactoryWithOutputSchema({ id, inputSchema, outputSchema, supportsDeferredResults }) { + return ({ execute, needsApproval, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args })=>dist_tool({ + type: "provider", + id, + args, + inputSchema, + outputSchema, + execute, + needsApproval, + toModelOutput, + onInputStart, + onInputDelta, + onInputAvailable, + supportsDeferredResults + }); + } + async function dist_resolve(value1) { + if ("function" == typeof value1) value1 = value1(); + return Promise.resolve(value1); + } + var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable })=>async ({ response, url, requestBodyValues })=>{ + const responseBody = await response.text(); + const responseHeaders = extractResponseHeaders(response); + if ("" === responseBody.trim()) return { + responseHeaders, + value: new APICallError({ + message: response.statusText, + url, + requestBodyValues, + statusCode: response.status, + responseHeaders, + responseBody, + isRetryable: null == isRetryable ? 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: null == isRetryable ? void 0 : isRetryable(response, parsedError) + }) + }; + } catch (parseError) { + return { + responseHeaders, + value: new APICallError({ + message: response.statusText, + url, + requestBodyValues, + statusCode: response.status, + responseHeaders, + responseBody, + isRetryable: null == isRetryable ? void 0 : isRetryable(response) + }) + }; + } + }; + var createEventSourceResponseHandler = (chunkSchema)=>async ({ response })=>{ + const responseHeaders = extractResponseHeaders(response); + if (null == response.body) throw new EmptyResponseBodyError({}); + return { + responseHeaders, + value: dist_parseJsonEventStream({ + stream: response.body, + schema: chunkSchema + }) + }; + }; + var createJsonResponseHandler = (responseSchema)=>async ({ response, url, requestBodyValues })=>{ + const responseBody = await response.text(); + 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 createBinaryResponseHandler = ()=>async ({ response, url, requestBodyValues })=>{ + const responseHeaders = extractResponseHeaders(response); + if (!response.body) throw new APICallError({ + message: "Response body is empty", + url, + requestBodyValues, + statusCode: response.status, + responseHeaders, + responseBody: void 0 + }); + try { + const buffer = await response.arrayBuffer(); + return { + responseHeaders, + value: new Uint8Array(buffer) + }; + } catch (error) { + throw new APICallError({ + message: "Failed to read response as array buffer", + url, + requestBodyValues, + statusCode: response.status, + responseHeaders, + responseBody: void 0, + cause: error + }); + } + }; + function withoutTrailingSlash(url) { + return null == url ? void 0 : url.replace(/\/$/, ""); + } + function isAsyncIterable(obj) { + return null != obj && "function" == typeof obj[Symbol.asyncIterator]; + } + async function* executeTool({ execute, input, options: options1 }) { + const result = execute(input, options1); + if (isAsyncIterable(result)) { + let lastOutput; + for await (const output of result){ + lastOutput = output; + yield { + type: "preliminary", + output + }; + } + yield { + type: "final", + output: lastOutput + }; + } else yield { + type: "final", + output: await result + }; + } + var dist = __webpack_require__("./node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/index.js"); + var gateway_dist_marker = "vercel.ai.gateway.error"; + var gateway_dist_symbol = Symbol.for(gateway_dist_marker); + var gateway_dist_a, gateway_dist_b; + var GatewayError = class _GatewayError extends (gateway_dist_b = Error, gateway_dist_a = gateway_dist_symbol, gateway_dist_b) { + constructor({ message, statusCode = 500, cause, generationId }){ + super(generationId ? `${message} [${generationId}]` : message); + this[gateway_dist_a] = true; + this.statusCode = statusCode; + this.cause = cause; + this.generationId = generationId; + } + static isInstance(error) { + return _GatewayError.hasMarker(error); + } + static hasMarker(error) { + return "object" == typeof error && null !== error && gateway_dist_symbol in error && true === error[gateway_dist_symbol]; + } + }; + var gateway_dist_name = "GatewayAuthenticationError"; + var dist_marker2 = `vercel.ai.gateway.error.${gateway_dist_name}`; + var dist_symbol2 = Symbol.for(dist_marker2); + var gateway_dist_a2, gateway_dist_b2; + var GatewayAuthenticationError = class _GatewayAuthenticationError extends (gateway_dist_b2 = GatewayError, gateway_dist_a2 = dist_symbol2, gateway_dist_b2) { + constructor({ message = "Authentication failed", statusCode = 401, cause, generationId } = {}){ + super({ + message, + statusCode, + cause, + generationId + }); + this[gateway_dist_a2] = true; + this.name = gateway_dist_name; + this.type = "authentication_error"; + } + static isInstance(error) { + return GatewayError.hasMarker(error) && dist_symbol2 in error; + } + static createContextualError({ apiKeyProvided, oidcTokenProvided, message = "Authentication failed", statusCode = 401, cause, generationId }) { + let contextualMessage; + contextualMessage = apiKeyProvided ? `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.` : oidcTokenProvided ? `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` : `AI Gateway authentication failed: No authentication provided. + +Option 1 - API key: +Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys +Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable. + +Option 2 - OIDC token: +Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`; + return new _GatewayAuthenticationError({ + message: contextualMessage, + statusCode, + cause, + generationId + }); + } + }; + var gateway_dist_name2 = "GatewayInvalidRequestError"; + var dist_marker3 = `vercel.ai.gateway.error.${gateway_dist_name2}`; + var dist_symbol3 = Symbol.for(dist_marker3); + var gateway_dist_a3, dist_b3; + var GatewayInvalidRequestError = class extends (dist_b3 = GatewayError, gateway_dist_a3 = dist_symbol3, dist_b3) { + constructor({ message = "Invalid request", statusCode = 400, cause, generationId } = {}){ + super({ + message, + statusCode, + cause, + generationId + }); + this[gateway_dist_a3] = true; + this.name = gateway_dist_name2; + this.type = "invalid_request_error"; + } + static isInstance(error) { + return GatewayError.hasMarker(error) && dist_symbol3 in error; + } + }; + var gateway_dist_name3 = "GatewayRateLimitError"; + var dist_marker4 = `vercel.ai.gateway.error.${gateway_dist_name3}`; + var dist_symbol4 = Symbol.for(dist_marker4); + var dist_a4, dist_b4; + var GatewayRateLimitError = class extends (dist_b4 = GatewayError, dist_a4 = dist_symbol4, dist_b4) { + constructor({ message = "Rate limit exceeded", statusCode = 429, cause, generationId } = {}){ + super({ + message, + statusCode, + cause, + generationId + }); + this[dist_a4] = true; + this.name = gateway_dist_name3; + this.type = "rate_limit_exceeded"; + } + static isInstance(error) { + return GatewayError.hasMarker(error) && dist_symbol4 in error; + } + }; + var dist_name4 = "GatewayModelNotFoundError"; + var dist_marker5 = `vercel.ai.gateway.error.${dist_name4}`; + var dist_symbol5 = Symbol.for(dist_marker5); + var modelNotFoundParamSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + modelId: schemas_string() + }))); + var dist_a5, dist_b5; + var GatewayModelNotFoundError = class extends (dist_b5 = GatewayError, dist_a5 = dist_symbol5, dist_b5) { + constructor({ message = "Model not found", statusCode = 404, modelId, cause, generationId } = {}){ + super({ + message, + statusCode, + cause, + generationId + }); + this[dist_a5] = true; + this.name = dist_name4; + this.type = "model_not_found"; + this.modelId = modelId; + } + static isInstance(error) { + return GatewayError.hasMarker(error) && dist_symbol5 in error; + } + }; + var dist_name5 = "GatewayInternalServerError"; + var dist_marker6 = `vercel.ai.gateway.error.${dist_name5}`; + var dist_symbol6 = Symbol.for(dist_marker6); + var dist_a6, dist_b6; + var GatewayInternalServerError = class extends (dist_b6 = GatewayError, dist_a6 = dist_symbol6, dist_b6) { + constructor({ message = "Internal server error", statusCode = 500, cause, generationId } = {}){ + super({ + message, + statusCode, + cause, + generationId + }); + this[dist_a6] = true; + this.name = dist_name5; + this.type = "internal_server_error"; + } + static isInstance(error) { + return GatewayError.hasMarker(error) && dist_symbol6 in error; + } + }; + var dist_name6 = "GatewayResponseError"; + var dist_marker7 = `vercel.ai.gateway.error.${dist_name6}`; + var dist_symbol7 = Symbol.for(dist_marker7); + var dist_a7, dist_b7; + var GatewayResponseError = class extends (dist_b7 = GatewayError, dist_a7 = dist_symbol7, dist_b7) { + constructor({ message = "Invalid response from Gateway", statusCode = 502, response, validationError, cause, generationId } = {}){ + super({ + message, + statusCode, + cause, + generationId + }); + this[dist_a7] = true; + this.name = dist_name6; + this.type = "response_error"; + this.response = response; + this.validationError = validationError; + } + static isInstance(error) { + return GatewayError.hasMarker(error) && dist_symbol7 in error; + } + }; + async function createGatewayErrorFromResponse({ response, statusCode, defaultMessage = "Gateway request failed", cause, authMethod }) { + var _a9; + const parseResult = await safeValidateTypes({ + value: response, + schema: gatewayErrorResponseSchema + }); + if (!parseResult.success) { + const rawGenerationId = "object" == typeof response && null !== response && "generationId" in response ? response.generationId : void 0; + return new GatewayResponseError({ + message: `Invalid error response format: ${defaultMessage}`, + statusCode, + response, + validationError: parseResult.error, + cause, + generationId: rawGenerationId + }); + } + const validatedResponse = parseResult.value; + const errorType = validatedResponse.error.type; + const message = validatedResponse.error.message; + const generationId = null != (_a9 = validatedResponse.generationId) ? _a9 : void 0; + switch(errorType){ + case "authentication_error": + return GatewayAuthenticationError.createContextualError({ + apiKeyProvided: "api-key" === authMethod, + oidcTokenProvided: "oidc" === authMethod, + statusCode, + cause, + generationId + }); + case "invalid_request_error": + return new GatewayInvalidRequestError({ + message, + statusCode, + cause, + generationId + }); + case "rate_limit_exceeded": + return new GatewayRateLimitError({ + message, + statusCode, + cause, + generationId + }); + case "model_not_found": + { + const modelResult = await safeValidateTypes({ + value: validatedResponse.error.param, + schema: modelNotFoundParamSchema + }); + return new GatewayModelNotFoundError({ + message, + statusCode, + modelId: modelResult.success ? modelResult.value.modelId : void 0, + cause, + generationId + }); + } + case "internal_server_error": + return new GatewayInternalServerError({ + message, + statusCode, + cause, + generationId + }); + default: + return new GatewayInternalServerError({ + message, + statusCode, + cause, + generationId + }); + } + } + var gatewayErrorResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + error: schemas_object({ + message: schemas_string(), + type: schemas_string().nullish(), + param: unknown().nullish(), + code: union([ + schemas_string(), + schemas_number() + ]).nullish() + }), + generationId: schemas_string().nullish() + }))); + var dist_name7 = "GatewayTimeoutError"; + var dist_marker8 = `vercel.ai.gateway.error.${dist_name7}`; + var dist_symbol8 = Symbol.for(dist_marker8); + var dist_a8, dist_b8; + var GatewayTimeoutError = class _GatewayTimeoutError extends (dist_b8 = GatewayError, dist_a8 = dist_symbol8, dist_b8) { + constructor({ message = "Request timed out", statusCode = 408, cause, generationId } = {}){ + super({ + message, + statusCode, + cause, + generationId + }); + this[dist_a8] = true; + this.name = dist_name7; + this.type = "timeout_error"; + } + static isInstance(error) { + return GatewayError.hasMarker(error) && dist_symbol8 in error; + } + static createTimeoutError({ originalMessage, statusCode = 408, cause, generationId }) { + const message = `Gateway request timed out: ${originalMessage} + + This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`; + return new _GatewayTimeoutError({ + message, + statusCode, + cause, + generationId + }); + } + }; + function isTimeoutError(error) { + if (!(error instanceof Error)) return false; + const errorCode = error.code; + if ("string" == typeof errorCode) { + const undiciTimeoutCodes = [ + "UND_ERR_HEADERS_TIMEOUT", + "UND_ERR_BODY_TIMEOUT", + "UND_ERR_CONNECT_TIMEOUT" + ]; + return undiciTimeoutCodes.includes(errorCode); + } + return false; + } + async function asGatewayError(error, authMethod) { + var _a9; + 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: null != (_a9 = error.statusCode) ? _a9 : 500, + defaultMessage: "Gateway request failed", + cause: error, + authMethod + }); + } + return await createGatewayErrorFromResponse({ + response: {}, + statusCode: 500, + defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error", + cause: error, + authMethod + }); + } + function extractApiCallResponse(error) { + if (void 0 !== error.data) return error.data; + if (null != error.responseBody) try { + return JSON.parse(error.responseBody); + } catch (e) { + return error.responseBody; + } + return {}; + } + 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 = dist_lazySchema(()=>dist_zodSchema(union([ + schemas_literal("api-key"), + schemas_literal("oidc") + ]))); + var GatewayFetchMetadata = class { + constructor(config){ + this.config = config; + } + async getAvailableModels() { + try { + const { value: value1 } = await getFromApi({ + url: `${this.config.baseURL}/config`, + headers: await dist_resolve(this.config.headers()), + successfulResponseHandler: createJsonResponseHandler(gatewayAvailableModelsResponseSchema), + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: any(), + errorToMessage: (data)=>data + }), + fetch: this.config.fetch + }); + return value1; + } catch (error) { + throw await asGatewayError(error); + } + } + async getCredits() { + try { + const baseUrl = new URL(this.config.baseURL); + const { value: value1 } = await getFromApi({ + url: `${baseUrl.origin}/v1/credits`, + headers: await dist_resolve(this.config.headers()), + successfulResponseHandler: createJsonResponseHandler(gatewayCreditsResponseSchema), + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: any(), + errorToMessage: (data)=>data + }), + fetch: this.config.fetch + }); + return value1; + } catch (error) { + throw await asGatewayError(error); + } + } + }; + var gatewayAvailableModelsResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + models: schemas_array(schemas_object({ + id: schemas_string(), + name: schemas_string(), + description: schemas_string().nullish(), + pricing: schemas_object({ + input: schemas_string(), + output: schemas_string(), + input_cache_read: schemas_string().nullish(), + input_cache_write: schemas_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: schemas_object({ + specificationVersion: schemas_literal("v3"), + provider: schemas_string(), + modelId: schemas_string() + }), + modelType: schemas_enum([ + "embedding", + "image", + "language", + "video" + ]).nullish() + })) + }))); + var gatewayCreditsResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + balance: schemas_string(), + total_used: schemas_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: value1 } = await getFromApi({ + url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`, + headers: await dist_resolve(this.config.headers()), + successfulResponseHandler: createJsonResponseHandler(gatewaySpendReportResponseSchema), + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: any(), + errorToMessage: (data)=>data + }), + fetch: this.config.fetch + }); + return value1; + } catch (error) { + throw await asGatewayError(error); + } + } + }; + var gatewaySpendReportResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + results: schemas_array(schemas_object({ + day: schemas_string().optional(), + hour: schemas_string().optional(), + user: schemas_string().optional(), + model: schemas_string().optional(), + tag: schemas_string().optional(), + provider: schemas_string().optional(), + credential_type: schemas_enum([ + "byok", + "system" + ]).optional(), + total_cost: schemas_number(), + market_cost: schemas_number().optional(), + input_tokens: schemas_number().optional(), + output_tokens: schemas_number().optional(), + cached_input_tokens: schemas_number().optional(), + cache_creation_input_tokens: schemas_number().optional(), + reasoning_tokens: schemas_number().optional(), + request_count: schemas_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, + ...void 0 !== credential_type ? { + credentialType: credential_type + } : {}, + totalCost: total_cost, + ...void 0 !== market_cost ? { + marketCost: market_cost + } : {}, + ...void 0 !== input_tokens ? { + inputTokens: input_tokens + } : {}, + ...void 0 !== output_tokens ? { + outputTokens: output_tokens + } : {}, + ...void 0 !== cached_input_tokens ? { + cachedInputTokens: cached_input_tokens + } : {}, + ...void 0 !== cache_creation_input_tokens ? { + cacheCreationInputTokens: cache_creation_input_tokens + } : {}, + ...void 0 !== reasoning_tokens ? { + reasoningTokens: reasoning_tokens + } : {}, + ...void 0 !== request_count ? { + requestCount: request_count + } : {} + }))) + }))); + var GatewayGenerationInfoFetcher = class { + constructor(config){ + this.config = config; + } + async getGenerationInfo(params) { + try { + const baseUrl = new URL(this.config.baseURL); + const { value: value1 } = await getFromApi({ + url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`, + headers: await dist_resolve(this.config.headers()), + successfulResponseHandler: createJsonResponseHandler(gatewayGenerationInfoResponseSchema), + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: any(), + errorToMessage: (data)=>data + }), + fetch: this.config.fetch + }); + return value1; + } catch (error) { + throw await asGatewayError(error); + } + } + }; + var gatewayGenerationInfoResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + data: schemas_object({ + id: schemas_string(), + total_cost: schemas_number(), + upstream_inference_cost: schemas_number(), + usage: schemas_number(), + created_at: schemas_string(), + model: schemas_string(), + is_byok: schemas_boolean(), + provider_name: schemas_string(), + streamed: schemas_boolean(), + finish_reason: schemas_string(), + latency: schemas_number(), + generation_time: schemas_number(), + native_tokens_prompt: schemas_number(), + native_tokens_completion: schemas_number(), + native_tokens_reasoning: schemas_number(), + native_tokens_cached: schemas_number(), + native_tokens_cache_creation: schemas_number(), + billable_web_search_calls: schemas_number() + }).transform(({ total_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest })=>({ + ...rest, + totalCost: total_cost, + upstreamInferenceCost: upstream_inference_cost, + createdAt: created_at, + isByok: is_byok, + providerName: provider_name, + finishReason: finish_reason, + generationTime: generation_time, + promptTokens: native_tokens_prompt, + completionTokens: native_tokens_completion, + reasoningTokens: native_tokens_reasoning, + cachedTokens: native_tokens_cached, + cacheCreationTokens: native_tokens_cache_creation, + billableWebSearchCalls: billable_web_search_calls + })) + }).transform(({ data })=>data))); + var GatewayLanguageModel = class { + constructor(modelId, config){ + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v3"; + this.supportedUrls = { + "*/*": [ + /.*/ + ] + }; + } + get provider() { + return this.config.provider; + } + async getArgs(options1) { + const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options1; + return { + args: this.maybeEncodeFileParts(optionsWithoutSignal), + warnings: [] + }; + } + async doGenerate(options1) { + const { args, warnings } = await this.getArgs(options1); + const { abortSignal } = options1; + const resolvedHeaders = await dist_resolve(this.config.headers()); + try { + const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({ + url: this.getUrl(), + headers: combineHeaders(resolvedHeaders, options1.headers, this.getModelConfigHeaders(this.modelId, false), await dist_resolve(this.config.o11yHeaders)), + body: args, + successfulResponseHandler: createJsonResponseHandler(any()), + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: any(), + errorToMessage: (data)=>data + }), + ...abortSignal && { + abortSignal + }, + fetch: this.config.fetch + }); + return { + ...responseBody, + request: { + body: args + }, + response: { + headers: responseHeaders, + body: rawResponse + }, + warnings + }; + } catch (error) { + throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders)); + } + } + async doStream(options1) { + const { args, warnings } = await this.getArgs(options1); + const { abortSignal } = options1; + const resolvedHeaders = await dist_resolve(this.config.headers()); + try { + const { value: response, responseHeaders } = await postJsonToApi({ + url: this.getUrl(), + headers: combineHeaders(resolvedHeaders, options1.headers, this.getModelConfigHeaders(this.modelId, true), await dist_resolve(this.config.o11yHeaders)), + body: args, + successfulResponseHandler: createEventSourceResponseHandler(any()), + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: any(), + errorToMessage: (data)=>data + }), + ...abortSignal && { + abortSignal + }, + fetch: this.config.fetch + }); + return { + stream: response.pipeThrough(new TransformStream({ + start (controller) { + if (warnings.length > 0) controller.enqueue({ + type: "stream-start", + warnings + }); + }, + transform (chunk, controller) { + if (chunk.success) { + const streamPart = chunk.value; + if ("raw" === streamPart.type && !options1.includeRawChunks) return; + if ("response-metadata" === streamPart.type && streamPart.timestamp && "string" == typeof streamPart.timestamp) 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 && "object" == typeof part && "type" in part && "file" === part.type; + } + maybeEncodeFileParts(options1) { + for (const message of options1.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 options1; + } + getUrl() { + return `${this.config.baseURL}/language-model`; + } + getModelConfigHeaders(modelId, streaming) { + return { + "ai-language-model-specification-version": "3", + "ai-language-model-id": modelId, + "ai-language-model-streaming": String(streaming) + }; + } + }; + var GatewayEmbeddingModel = class { + constructor(modelId, config){ + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v3"; + this.maxEmbeddingsPerCall = 2048; + this.supportsParallelCalls = true; + } + get provider() { + return this.config.provider; + } + async doEmbed({ values, headers, abortSignal, providerOptions }) { + var _a9; + const resolvedHeaders = await dist_resolve(this.config.headers()); + try { + const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({ + url: this.getUrl(), + headers: combineHeaders(resolvedHeaders, null != headers ? headers : {}, this.getModelConfigHeaders(), await dist_resolve(this.config.o11yHeaders)), + body: { + values, + ...providerOptions ? { + providerOptions + } : {} + }, + successfulResponseHandler: createJsonResponseHandler(gatewayEmbeddingResponseSchema), + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: any(), + errorToMessage: (data)=>data + }), + ...abortSignal && { + abortSignal + }, + fetch: this.config.fetch + }); + return { + embeddings: responseBody.embeddings, + usage: null != (_a9 = responseBody.usage) ? _a9 : void 0, + providerMetadata: responseBody.providerMetadata, + response: { + headers: responseHeaders, + body: rawValue + }, + warnings: [] + }; + } catch (error) { + throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders)); + } + } + getUrl() { + return `${this.config.baseURL}/embedding-model`; + } + getModelConfigHeaders() { + return { + "ai-embedding-model-specification-version": "3", + "ai-model-id": this.modelId + }; + } + }; + var gatewayEmbeddingResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + embeddings: schemas_array(schemas_array(schemas_number())), + usage: schemas_object({ + tokens: schemas_number() + }).nullish(), + providerMetadata: schemas_record(schemas_string(), schemas_record(schemas_string(), unknown())).optional() + }))); + var GatewayImageModel = class { + constructor(modelId, config){ + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v3"; + this.maxImagesPerCall = Number.MAX_SAFE_INTEGER; + } + get provider() { + return this.config.provider; + } + async doGenerate({ prompt, n, size, aspectRatio, seed, files, mask, providerOptions, headers, abortSignal }) { + var _a9, _b9, _c, _d; + const resolvedHeaders = await dist_resolve(this.config.headers()); + try { + const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({ + url: this.getUrl(), + headers: combineHeaders(resolvedHeaders, null != headers ? headers : {}, this.getModelConfigHeaders(), await dist_resolve(this.config.o11yHeaders)), + body: { + prompt, + n, + ...size && { + size + }, + ...aspectRatio && { + aspectRatio + }, + ...seed && { + seed + }, + ...providerOptions && { + providerOptions + }, + ...files && { + files: files.map((file)=>maybeEncodeImageFile(file)) + }, + ...mask && { + mask: maybeEncodeImageFile(mask) + } + }, + successfulResponseHandler: createJsonResponseHandler(gatewayImageResponseSchema), + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: any(), + errorToMessage: (data)=>data + }), + ...abortSignal && { + abortSignal + }, + fetch: this.config.fetch + }); + return { + images: responseBody.images, + warnings: null != (_a9 = responseBody.warnings) ? _a9 : [], + providerMetadata: responseBody.providerMetadata, + response: { + timestamp: /* @__PURE__ */ new Date(), + modelId: this.modelId, + headers: responseHeaders + }, + ...null != responseBody.usage && { + usage: { + inputTokens: null != (_b9 = responseBody.usage.inputTokens) ? _b9 : void 0, + outputTokens: null != (_c = responseBody.usage.outputTokens) ? _c : void 0, + totalTokens: null != (_d = responseBody.usage.totalTokens) ? _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": "3", + "ai-model-id": this.modelId + }; + } + }; + function maybeEncodeImageFile(file) { + if ("file" === file.type && file.data instanceof Uint8Array) return { + ...file, + data: convertUint8ArrayToBase64(file.data) + }; + return file; + } + var providerMetadataEntrySchema = schemas_object({ + images: schemas_array(unknown()).optional() + }).catchall(unknown()); + var gatewayImageWarningSchema = discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("unsupported"), + feature: schemas_string(), + details: schemas_string().optional() + }), + schemas_object({ + type: schemas_literal("compatibility"), + feature: schemas_string(), + details: schemas_string().optional() + }), + schemas_object({ + type: schemas_literal("other"), + message: schemas_string() + }) + ]); + var gatewayImageUsageSchema = schemas_object({ + inputTokens: schemas_number().nullish(), + outputTokens: schemas_number().nullish(), + totalTokens: schemas_number().nullish() + }); + var gatewayImageResponseSchema = schemas_object({ + images: schemas_array(schemas_string()), + warnings: schemas_array(gatewayImageWarningSchema).optional(), + providerMetadata: schemas_record(schemas_string(), providerMetadataEntrySchema).optional(), + usage: gatewayImageUsageSchema.optional() + }); + var GatewayVideoModel = class { + constructor(modelId, config){ + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v3"; + this.maxVideosPerCall = Number.MAX_SAFE_INTEGER; + } + get provider() { + return this.config.provider; + } + async doGenerate({ prompt, n, aspectRatio, resolution, duration, fps, seed, image, providerOptions, headers, abortSignal }) { + var _a9; + const resolvedHeaders = await dist_resolve(this.config.headers()); + try { + const { responseHeaders, value: responseBody } = await postJsonToApi({ + url: this.getUrl(), + headers: combineHeaders(resolvedHeaders, null != headers ? headers : {}, this.getModelConfigHeaders(), await dist_resolve(this.config.o11yHeaders), { + accept: "text/event-stream" + }), + body: { + prompt, + n, + ...aspectRatio && { + aspectRatio + }, + ...resolution && { + resolution + }, + ...duration && { + duration + }, + ...fps && { + fps + }, + ...seed && { + seed + }, + ...providerOptions && { + providerOptions + }, + ...image && { + image: maybeEncodeVideoFile(image) + } + }, + successfulResponseHandler: async ({ response, url, requestBodyValues })=>{ + if (null == response.body) throw new APICallError({ + message: "SSE response body is empty", + url, + requestBodyValues, + statusCode: response.status + }); + const eventStream = dist_parseJsonEventStream({ + stream: response.body, + schema: gatewayVideoEventSchema + }); + const reader = eventStream.getReader(); + const { done, value: parseResult } = await reader.read(); + reader.releaseLock(); + if (done || !parseResult) throw new APICallError({ + message: "SSE stream ended without a data event", + url, + requestBodyValues, + statusCode: response.status + }); + if (!parseResult.success) throw new APICallError({ + message: "Failed to parse video SSE event", + cause: parseResult.error, + url, + requestBodyValues, + statusCode: response.status + }); + const event = parseResult.value; + if ("error" === event.type) throw new APICallError({ + message: event.message, + statusCode: event.statusCode, + url, + requestBodyValues, + responseHeaders: Object.fromEntries([ + ...response.headers + ]), + responseBody: JSON.stringify(event), + data: { + error: { + message: event.message, + type: event.errorType, + param: event.param + } + } + }); + return { + value: { + videos: event.videos, + warnings: event.warnings, + providerMetadata: event.providerMetadata + }, + responseHeaders: Object.fromEntries([ + ...response.headers + ]) + }; + }, + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: any(), + errorToMessage: (data)=>data + }), + ...abortSignal && { + abortSignal + }, + fetch: this.config.fetch + }); + return { + videos: responseBody.videos, + warnings: null != (_a9 = responseBody.warnings) ? _a9 : [], + providerMetadata: responseBody.providerMetadata, + response: { + timestamp: /* @__PURE__ */ new Date(), + modelId: this.modelId, + headers: responseHeaders + } + }; + } catch (error) { + throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders)); + } + } + getUrl() { + return `${this.config.baseURL}/video-model`; + } + getModelConfigHeaders() { + return { + "ai-video-model-specification-version": "3", + "ai-model-id": this.modelId + }; + } + }; + function maybeEncodeVideoFile(file) { + if ("file" === file.type && file.data instanceof Uint8Array) return { + ...file, + data: convertUint8ArrayToBase64(file.data) + }; + return file; + } + var providerMetadataEntrySchema2 = schemas_object({ + videos: schemas_array(unknown()).optional() + }).catchall(unknown()); + var gatewayVideoDataSchema = union([ + schemas_object({ + type: schemas_literal("url"), + url: schemas_string(), + mediaType: schemas_string() + }), + schemas_object({ + type: schemas_literal("base64"), + data: schemas_string(), + mediaType: schemas_string() + }) + ]); + var gatewayVideoWarningSchema = discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("unsupported"), + feature: schemas_string(), + details: schemas_string().optional() + }), + schemas_object({ + type: schemas_literal("compatibility"), + feature: schemas_string(), + details: schemas_string().optional() + }), + schemas_object({ + type: schemas_literal("other"), + message: schemas_string() + }) + ]); + var gatewayVideoEventSchema = discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("result"), + videos: schemas_array(gatewayVideoDataSchema), + warnings: schemas_array(gatewayVideoWarningSchema).optional(), + providerMetadata: schemas_record(schemas_string(), providerMetadataEntrySchema2).optional() + }), + schemas_object({ + type: schemas_literal("error"), + message: schemas_string(), + errorType: schemas_string(), + statusCode: schemas_number(), + param: unknown().nullable() + }) + ]); + var GatewayRerankingModel = class { + constructor(modelId, config){ + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v3"; + } + get provider() { + return this.config.provider; + } + async doRerank({ documents, query, topN, headers, abortSignal, providerOptions }) { + const resolvedHeaders = await dist_resolve(this.config.headers()); + try { + const { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({ + url: this.getUrl(), + headers: combineHeaders(resolvedHeaders, null != headers ? headers : {}, this.getModelConfigHeaders(), await dist_resolve(this.config.o11yHeaders)), + body: { + documents, + query, + ...null != topN ? { + topN + } : {}, + ...providerOptions ? { + providerOptions + } : {} + }, + successfulResponseHandler: createJsonResponseHandler(gatewayRerankingResponseSchema), + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: any(), + errorToMessage: (data)=>data + }), + ...abortSignal && { + abortSignal + }, + fetch: this.config.fetch + }); + return { + ranking: responseBody.ranking, + providerMetadata: responseBody.providerMetadata, + response: { + headers: responseHeaders, + body: rawValue + }, + warnings: [] + }; + } catch (error) { + throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders)); + } + } + getUrl() { + return `${this.config.baseURL}/reranking-model`; + } + getModelConfigHeaders() { + return { + "ai-reranking-model-specification-version": "3", + "ai-model-id": this.modelId + }; + } + }; + var gatewayRerankingResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + ranking: schemas_array(schemas_object({ + index: schemas_number(), + relevanceScore: schemas_number() + })), + providerMetadata: schemas_record(schemas_string(), schemas_record(schemas_string(), unknown())).optional() + }))); + var parallelSearchInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + objective: schemas_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: schemas_array(schemas_string()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."), + mode: schemas_enum([ + "one-shot", + "agentic" + ]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'), + max_results: schemas_number().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."), + source_policy: schemas_object({ + include_domains: schemas_array(schemas_string()).optional().describe("List of domains to include in search results."), + exclude_domains: schemas_array(schemas_string()).optional().describe("List of domains to exclude from search results."), + after_date: schemas_string().optional().describe("Only include results published after this date (ISO 8601 format).") + }).optional().describe("Source policy for controlling which domains to include/exclude and freshness."), + excerpts: schemas_object({ + max_chars_per_result: schemas_number().optional().describe("Maximum characters per result."), + max_chars_total: schemas_number().optional().describe("Maximum total characters across all results.") + }).optional().describe("Excerpt configuration for controlling result length."), + fetch_policy: schemas_object({ + max_age_seconds: schemas_number().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.") + }).optional().describe("Fetch policy for controlling content freshness.") + }))); + var parallelSearchOutputSchema = dist_lazySchema(()=>dist_zodSchema(union([ + schemas_object({ + searchId: schemas_string(), + results: schemas_array(schemas_object({ + url: schemas_string(), + title: schemas_string(), + excerpt: schemas_string(), + publishDate: schemas_string().nullable().optional(), + relevanceScore: schemas_number().optional() + })) + }), + schemas_object({ + error: schemas_enum([ + "api_error", + "rate_limit", + "timeout", + "invalid_input", + "configuration_error", + "unknown" + ]), + statusCode: schemas_number().optional(), + message: schemas_string() + }) + ]))); + var parallelSearchToolFactory = createProviderToolFactoryWithOutputSchema({ + id: "gateway.parallel_search", + inputSchema: parallelSearchInputSchema, + outputSchema: parallelSearchOutputSchema + }); + var parallelSearch = (config = {})=>parallelSearchToolFactory(config); + var perplexitySearchInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + query: union([ + schemas_string(), + schemas_array(schemas_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: schemas_number().optional().describe("Maximum number of search results to return (1-20, default: 10)"), + max_tokens_per_page: schemas_number().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"), + max_tokens: schemas_number().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"), + country: schemas_string().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"), + search_domain_filter: schemas_array(schemas_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: schemas_array(schemas_string()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"), + search_after_date: schemas_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: schemas_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: schemas_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: schemas_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: schemas_enum([ + "day", + "week", + "month", + "year" + ]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.") + }))); + var perplexitySearchOutputSchema = dist_lazySchema(()=>dist_zodSchema(union([ + schemas_object({ + results: schemas_array(schemas_object({ + title: schemas_string(), + url: schemas_string(), + snippet: schemas_string(), + date: schemas_string().optional(), + lastUpdated: schemas_string().optional() + })), + id: schemas_string() + }), + schemas_object({ + error: schemas_enum([ + "api_error", + "rate_limit", + "timeout", + "invalid_input", + "unknown" + ]), + statusCode: schemas_number().optional(), + message: schemas_string() + }) + ]))); + var perplexitySearchToolFactory = createProviderToolFactoryWithOutputSchema({ + id: "gateway.perplexity_search", + inputSchema: perplexitySearchInputSchema, + outputSchema: perplexitySearchOutputSchema + }); + var perplexitySearch = (config = {})=>perplexitySearchToolFactory(config); + var gatewayTools = { + parallelSearch, + perplexitySearch + }; + async function getVercelRequestId() { + var _a9; + return null == (_a9 = (0, dist.getContext)().headers) ? void 0 : _a9["x-vercel-id"]; + } + var dist_VERSION = "3.0.96"; + var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1"; + function createGatewayProvider(options1 = {}) { + var _a9, _b9; + let pendingMetadata = null; + let metadataCache = null; + const cacheRefreshMillis = null != (_a9 = options1.metadataCacheRefreshMillis) ? _a9 : 300000; + let lastFetchTime = 0; + const baseURL = null != (_b9 = withoutTrailingSlash(options1.baseURL)) ? _b9 : "https://ai-gateway.vercel.sh/v3/ai"; + const getHeaders = async ()=>{ + try { + const auth = await getGatewayAuthToken(options1); + return withUserAgentSuffix({ + Authorization: `Bearer ${auth.token}`, + "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION, + [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod, + ...options1.headers + }, `ai-sdk/gateway/${dist_VERSION}`); + } catch (error) { + throw GatewayAuthenticationError.createContextualError({ + apiKeyProvided: false, + oidcTokenProvided: false, + statusCode: 401, + cause: error + }); + } + }; + const createO11yHeaders = ()=>{ + const deploymentId = loadOptionalSetting({ + settingValue: void 0, + environmentVariableName: "VERCEL_DEPLOYMENT_ID" + }); + const environment = loadOptionalSetting({ + settingValue: void 0, + environmentVariableName: "VERCEL_ENV" + }); + const region = loadOptionalSetting({ + settingValue: void 0, + environmentVariableName: "VERCEL_REGION" + }); + const projectId = loadOptionalSetting({ + settingValue: void 0, + environmentVariableName: "VERCEL_PROJECT_ID" + }); + return async ()=>{ + const requestId = await getVercelRequestId(); + return { + ...deploymentId && { + "ai-o11y-deployment-id": deploymentId + }, + ...environment && { + "ai-o11y-environment": environment + }, + ...region && { + "ai-o11y-region": region + }, + ...requestId && { + "ai-o11y-request-id": requestId + }, + ...projectId && { + "ai-o11y-project-id": projectId + } + }; + }; + }; + const createLanguageModel = (modelId)=>new GatewayLanguageModel(modelId, { + provider: "gateway", + baseURL, + headers: getHeaders, + fetch: options1.fetch, + o11yHeaders: createO11yHeaders() + }); + const getAvailableModels = async ()=>{ + var _a10, _b10, _c; + const now = null != (_c = null == (_b10 = null == (_a10 = options1._internal) ? void 0 : _a10.currentDate) ? void 0 : _b10.call(_a10).getTime()) ? _c : Date.now(); + if (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) { + lastFetchTime = now; + pendingMetadata = new GatewayFetchMetadata({ + baseURL, + headers: getHeaders, + fetch: options1.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 ()=>new GatewayFetchMetadata({ + baseURL, + headers: getHeaders, + fetch: options1.fetch + }).getCredits().catch(async (error)=>{ + throw await asGatewayError(error, await parseAuthMethod(await getHeaders())); + }); + const getSpendReport = async (params)=>new GatewaySpendReport({ + baseURL, + headers: getHeaders, + fetch: options1.fetch + }).getSpendReport(params).catch(async (error)=>{ + throw await asGatewayError(error, await parseAuthMethod(await getHeaders())); + }); + const getGenerationInfo = async (params)=>new GatewayGenerationInfoFetcher({ + baseURL, + headers: getHeaders, + fetch: options1.fetch + }).getGenerationInfo(params).catch(async (error)=>{ + throw await asGatewayError(error, await parseAuthMethod(await getHeaders())); + }); + const provider = function(modelId) { + if (new.target) throw new Error("The Gateway Provider model function cannot be called with the new keyword."); + return createLanguageModel(modelId); + }; + provider.specificationVersion = "v3"; + provider.getAvailableModels = getAvailableModels; + provider.getCredits = getCredits; + provider.getSpendReport = getSpendReport; + provider.getGenerationInfo = getGenerationInfo; + provider.imageModel = (modelId)=>new GatewayImageModel(modelId, { + provider: "gateway", + baseURL, + headers: getHeaders, + fetch: options1.fetch, + o11yHeaders: createO11yHeaders() + }); + provider.languageModel = createLanguageModel; + const createEmbeddingModel = (modelId)=>new GatewayEmbeddingModel(modelId, { + provider: "gateway", + baseURL, + headers: getHeaders, + fetch: options1.fetch, + o11yHeaders: createO11yHeaders() + }); + provider.embeddingModel = createEmbeddingModel; + provider.textEmbeddingModel = createEmbeddingModel; + provider.videoModel = (modelId)=>new GatewayVideoModel(modelId, { + provider: "gateway", + baseURL, + headers: getHeaders, + fetch: options1.fetch, + o11yHeaders: createO11yHeaders() + }); + const createRerankingModel = (modelId)=>new GatewayRerankingModel(modelId, { + provider: "gateway", + baseURL, + headers: getHeaders, + fetch: options1.fetch, + o11yHeaders: createO11yHeaders() + }); + provider.rerankingModel = createRerankingModel; + provider.reranking = createRerankingModel; + provider.chat = provider.languageModel; + provider.embedding = provider.embeddingModel; + provider.image = provider.imageModel; + provider.video = provider.videoModel; + provider.tools = gatewayTools; + return provider; + } + var gateway = createGatewayProvider(); + async function getGatewayAuthToken(options1) { + const apiKey = loadOptionalSetting({ + settingValue: options1.apiKey, + environmentVariableName: "AI_GATEWAY_API_KEY" + }); + if (apiKey) return { + token: apiKey, + authMethod: "api-key" + }; + const oidcToken = await (0, dist.getVercelOidcToken)(); + return { + token: oidcToken, + authMethod: "oidc" + }; + } + var _globalThis = 'object' == typeof globalThis ? globalThis : global; + var version_VERSION = '1.9.0'; + var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; + function _makeCompatibilityCheck(ownVersion) { + var acceptedVersions = new Set([ + ownVersion + ]); + var rejectedVersions = 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 (null != ownVersionParsed.prerelease) return function(globalVersion) { + return globalVersion === ownVersion; + }; + function _reject(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function(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 (null != globalVersionParsed.prerelease) return _reject(globalVersion); + if (ownVersionParsed.major !== globalVersionParsed.major) return _reject(globalVersion); + if (0 === ownVersionParsed.major) { + 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); + }; + } + var semver_isCompatible = _makeCompatibilityCheck(version_VERSION); + var major = version_VERSION.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 (void 0 === allowOverride) allowOverride = false; + var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = null != (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) ? _a : { + version: version_VERSION + }; + if (!allowOverride && api[type]) { + var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); + diag.error(err.stack || err.message); + return false; + } + if (api.version !== version_VERSION) { + var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + version_VERSION); + diag.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + version_VERSION + "."); + return true; + } + function getGlobal(type) { + var _a, _b; + var globalVersion = null == (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) ? void 0 : _a.version; + if (!globalVersion || !semver_isCompatible(globalVersion)) return; + return null == (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) ? void 0 : _b[type]; + } + function unregisterGlobal(type, diag) { + diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + version_VERSION + "."); + var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) delete api[type]; + } + function createContextKey(description) { + return Symbol.for(description); + } + var context_BaseContext = function() { + function BaseContext(parentContext) { + var self1 = this; + self1._currentContext = parentContext ? new Map(parentContext) : new Map(); + self1.getValue = function(key) { + return self1._currentContext.get(key); + }; + self1.setValue = function(key, value1) { + var context = new BaseContext(self1._currentContext); + context._currentContext.set(key, value1); + return context; + }; + self1.deleteValue = function(key) { + var context = new BaseContext(self1._currentContext); + context._currentContext.delete(key); + return context; + }; + } + return BaseContext; + }(); + var ROOT_CONTEXT = new context_BaseContext(); + var __read = function(o, n) { + var m = "function" == typeof Symbol && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while((void 0 === n || n-- > 0) && !(r = i.next()).done)ar.push(r.value); + } catch (error) { + e = { + error: 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 || 2 === arguments.length) { + 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_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([ + thisArg + ], __read(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 ComponentLogger_read = function(o, n) { + var m = "function" == typeof Symbol && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while((void 0 === n || n-- > 0) && !(r = i.next()).done)ar.push(r.value); + } catch (error) { + e = { + error: error + }; + } finally{ + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally{ + if (e) throw e.error; + } + } + return ar; + }; + var ComponentLogger_spreadArray = function(to, from, pack) { + if (pack || 2 === arguments.length) { + 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 ComponentLogger_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, ComponentLogger_spreadArray([], ComponentLogger_read(args), false)); + } + var types_DiagLogLevel; + (function(DiagLogLevel) { + DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; + DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; + DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; + DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; + DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; + DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; + DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; + })(types_DiagLogLevel || (types_DiagLogLevel = {})); + function createLogLevelDiagLogger(maxLevel, logger) { + if (maxLevel < types_DiagLogLevel.NONE) maxLevel = types_DiagLogLevel.NONE; + else if (maxLevel > types_DiagLogLevel.ALL) maxLevel = types_DiagLogLevel.ALL; + logger = logger || {}; + function _filterFunc(funcName, theLevel) { + var theFunc = logger[funcName]; + if ('function' == typeof theFunc && maxLevel >= theLevel) return theFunc.bind(logger); + return function() {}; + } + return { + error: _filterFunc('error', types_DiagLogLevel.ERROR), + warn: _filterFunc('warn', types_DiagLogLevel.WARN), + info: _filterFunc('info', types_DiagLogLevel.INFO), + debug: _filterFunc('debug', types_DiagLogLevel.DEBUG), + verbose: _filterFunc('verbose', types_DiagLogLevel.VERBOSE) + }; + } + var diag_read = function(o, n) { + var m = "function" == typeof Symbol && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while((void 0 === n || n-- > 0) && !(r = i.next()).done)ar.push(r.value); + } catch (error) { + e = { + error: error + }; + } finally{ + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally{ + if (e) throw e.error; + } + } + return ar; + }; + var diag_spreadArray = function(to, from, pack) { + if (pack || 2 === arguments.length) { + 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 = 'diag'; + var diag_DiagAPI = function() { + 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, diag_spreadArray([], diag_read(args), false)); + }; + } + var self1 = this; + var setLogger = function(logger, optionsOrLogLevel) { + var _a, _b, _c; + if (void 0 === optionsOrLogLevel) optionsOrLogLevel = { + logLevel: types_DiagLogLevel.INFO + }; + if (logger === self1) { + var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); + self1.error(null != (_a = err.stack) ? _a : err.message); + return false; + } + if ('number' == typeof optionsOrLogLevel) optionsOrLogLevel = { + logLevel: optionsOrLogLevel + }; + var oldLogger = getGlobal('diag'); + var newLogger = createLogLevelDiagLogger(null != (_b = optionsOrLogLevel.logLevel) ? _b : types_DiagLogLevel.INFO, logger); + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + var stack = null != (_c = new Error().stack) ? _c : ''; + oldLogger.warn("Current logger will be overwritten from " + stack); + newLogger.warn("Current logger will overwrite one already registered from " + stack); + } + return registerGlobal('diag', newLogger, self1, true); + }; + self1.setLogger = setLogger; + self1.disable = function() { + unregisterGlobal(API_NAME, self1); + }; + self1.createComponentLogger = function(options1) { + return new ComponentLogger_DiagComponentLogger(options1); + }; + self1.verbose = _logProxy('verbose'); + self1.debug = _logProxy('debug'); + self1.info = _logProxy('info'); + self1.warn = _logProxy('warn'); + self1.error = _logProxy('error'); + } + DiagAPI.instance = function() { + if (!this._instance) this._instance = new DiagAPI(); + return this._instance; + }; + return DiagAPI; + }(); + var context_read = function(o, n) { + var m = "function" == typeof Symbol && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while((void 0 === n || n-- > 0) && !(r = i.next()).done)ar.push(r.value); + } catch (error) { + e = { + error: error + }; + } finally{ + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally{ + if (e) throw e.error; + } + } + return ar; + }; + var context_spreadArray = function(to, from, pack) { + if (pack || 2 === arguments.length) { + 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 context_API_NAME = 'context'; + var NOOP_CONTEXT_MANAGER = new NoopContextManager_NoopContextManager(); + var context_ContextAPI = function() { + function ContextAPI() {} + ContextAPI.getInstance = function() { + if (!this._instance) this._instance = new ContextAPI(); + return this._instance; + }; + ContextAPI.prototype.setGlobalContextManager = function(contextManager) { + return registerGlobal(context_API_NAME, contextManager, diag_DiagAPI.instance()); + }; + ContextAPI.prototype.active = function() { + return this._getContextManager().active(); + }; + 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, context_spreadArray([ + context, + fn, + thisArg + ], context_read(args), false)); + }; + ContextAPI.prototype.bind = function(context, target) { + return this._getContextManager().bind(context, target); + }; + ContextAPI.prototype._getContextManager = function() { + return getGlobal(context_API_NAME) || NOOP_CONTEXT_MANAGER; + }; + ContextAPI.prototype.disable = function() { + this._getContextManager().disable(); + unregisterGlobal(context_API_NAME, diag_DiagAPI.instance()); + }; + return ContextAPI; + }(); + var trace_flags_TraceFlags; + (function(TraceFlags) { + TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; + TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; + })(trace_flags_TraceFlags || (trace_flags_TraceFlags = {})); + var INVALID_SPANID = '0000000000000000'; + var INVALID_TRACEID = '00000000000000000000000000000000'; + var INVALID_SPAN_CONTEXT = { + traceId: INVALID_TRACEID, + spanId: INVALID_SPANID, + traceFlags: trace_flags_TraceFlags.NONE + }; + var NonRecordingSpan_NonRecordingSpan = function() { + function NonRecordingSpan(_spanContext) { + if (void 0 === _spanContext) _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; + }(); + var SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN'); + function getSpan(context) { + return context.getValue(SPAN_KEY) || void 0; + } + function getActiveSpan() { + return getSpan(context_ContextAPI.getInstance().active()); + } + function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); + } + function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); + } + function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan_NonRecordingSpan(spanContext)); + } + function getSpanContext(context) { + var _a; + return null == (_a = getSpan(context)) ? 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 !== INVALID_TRACEID; + } + function isValidSpanId(spanId) { + return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID; + } + function isSpanContextValid(spanContext) { + return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId); + } + function wrapSpanContext(spanContext) { + return new NonRecordingSpan_NonRecordingSpan(spanContext); + } + var contextApi = context_ContextAPI.getInstance(); + var NoopTracer_NoopTracer = function() { + function NoopTracer() {} + NoopTracer.prototype.startSpan = function(name, options1, context) { + if (void 0 === context) context = contextApi.active(); + var root = Boolean(null == options1 ? void 0 : options1.root); + if (root) return new NonRecordingSpan_NonRecordingSpan(); + var parentFromContext = context && getSpanContext(context); + if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) return new NonRecordingSpan_NonRecordingSpan(parentFromContext); + return new NonRecordingSpan_NonRecordingSpan(); + }; + NoopTracer.prototype.startActiveSpan = function(name, arg2, arg3, arg4) { + var opts; + var ctx; + var fn; + if (arguments.length < 2) return; + if (2 === arguments.length) fn = arg2; + else if (3 === arguments.length) { + opts = arg2; + fn = arg3; + } else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + var parentContext = null != ctx ? 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 'object' == typeof spanContext && 'string' == typeof spanContext['spanId'] && 'string' == typeof spanContext['traceId'] && 'number' == typeof spanContext['traceFlags']; + } + var NOOP_TRACER = new NoopTracer_NoopTracer(); + var ProxyTracer_ProxyTracer = function() { + function ProxyTracer(_provider, name, version, options1) { + this._provider = _provider; + this.name = name; + this.version = version; + this.options = options1; + } + ProxyTracer.prototype.startSpan = function(name, options1, context) { + return this._getTracer().startSpan(name, options1, context); + }; + ProxyTracer.prototype.startActiveSpan = function(_name, _options, _context, _fn) { + var tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + }; + 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 NoopTracerProvider_NoopTracerProvider = function() { + function NoopTracerProvider() {} + NoopTracerProvider.prototype.getTracer = function(_name, _version, _options) { + return new NoopTracer_NoopTracer(); + }; + return NoopTracerProvider; + }(); + var NOOP_TRACER_PROVIDER = new NoopTracerProvider_NoopTracerProvider(); + var ProxyTracerProvider_ProxyTracerProvider = function() { + function ProxyTracerProvider() {} + ProxyTracerProvider.prototype.getTracer = function(name, version, options1) { + var _a; + return null != (_a = this.getDelegateTracer(name, version, options1)) ? _a : new ProxyTracer_ProxyTracer(this, name, version, options1); + }; + ProxyTracerProvider.prototype.getDelegate = function() { + var _a; + return null != (_a = this._delegate) ? _a : NOOP_TRACER_PROVIDER; + }; + ProxyTracerProvider.prototype.setDelegate = function(delegate) { + this._delegate = delegate; + }; + ProxyTracerProvider.prototype.getDelegateTracer = function(name, version, options1) { + var _a; + return null == (_a = this._delegate) ? void 0 : _a.getTracer(name, version, options1); + }; + return ProxyTracerProvider; + }(); + var trace_API_NAME = 'trace'; + var trace_TraceAPI = function() { + function TraceAPI() { + this._proxyTracerProvider = new ProxyTracerProvider_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; + } + TraceAPI.getInstance = function() { + if (!this._instance) this._instance = new TraceAPI(); + return this._instance; + }; + TraceAPI.prototype.setGlobalTracerProvider = function(provider) { + var success = registerGlobal(trace_API_NAME, this._proxyTracerProvider, diag_DiagAPI.instance()); + if (success) this._proxyTracerProvider.setDelegate(provider); + return success; + }; + TraceAPI.prototype.getTracerProvider = function() { + return getGlobal(trace_API_NAME) || this._proxyTracerProvider; + }; + TraceAPI.prototype.getTracer = function(name, version) { + return this.getTracerProvider().getTracer(name, version); + }; + TraceAPI.prototype.disable = function() { + unregisterGlobal(trace_API_NAME, diag_DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider_ProxyTracerProvider(); + }; + return TraceAPI; + }(); + var trace = trace_TraceAPI.getInstance(); + var context_api_context = context_ContextAPI.getInstance(); + var status_SpanStatusCode; + (function(SpanStatusCode) { + SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; + SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; + SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; + })(status_SpanStatusCode || (status_SpanStatusCode = {})); + var __defProp = Object.defineProperty; + var __export = (target, all)=>{ + for(var name21 in all)__defProp(target, name21, { + get: all[name21], + enumerable: true + }); + }; + var ai_dist_name = "AI_InvalidArgumentError"; + var ai_dist_marker = `vercel.ai.error.${ai_dist_name}`; + var ai_dist_symbol = Symbol.for(ai_dist_marker); + var ai_dist_a; + var dist_InvalidArgumentError = class extends AISDKError { + constructor({ parameter, value: value1, message }){ + super({ + name: ai_dist_name, + message: `Invalid argument for parameter ${parameter}: ${message}` + }); + this[ai_dist_a] = true; + this.parameter = parameter; + this.value = value1; + } + static isInstance(error) { + return AISDKError.hasMarker(error, ai_dist_marker); + } + }; + ai_dist_a = ai_dist_symbol; + var ai_dist_name2 = "AI_InvalidStreamPartError"; + var ai_dist_marker2 = `vercel.ai.error.${ai_dist_name2}`; + Symbol.for(ai_dist_marker2); + var ai_dist_name3 = "AI_InvalidToolApprovalError"; + var ai_dist_marker3 = `vercel.ai.error.${ai_dist_name3}`; + var ai_dist_symbol3 = Symbol.for(ai_dist_marker3); + var ai_dist_a3; + var InvalidToolApprovalError = class extends AISDKError { + constructor({ approvalId }){ + super({ + name: ai_dist_name3, + message: `Tool approval response references unknown approvalId: "${approvalId}". No matching tool-approval-request found in message history.` + }); + this[ai_dist_a3] = true; + this.approvalId = approvalId; + } + static isInstance(error) { + return AISDKError.hasMarker(error, ai_dist_marker3); + } + }; + ai_dist_a3 = ai_dist_symbol3; + var ai_dist_name4 = "AI_InvalidToolInputError"; + var ai_dist_marker4 = `vercel.ai.error.${ai_dist_name4}`; + var ai_dist_symbol4 = Symbol.for(ai_dist_marker4); + var ai_dist_a4; + var InvalidToolInputError = class extends AISDKError { + constructor({ toolInput, toolName, cause, message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}` }){ + super({ + name: ai_dist_name4, + message, + cause + }); + this[ai_dist_a4] = true; + this.toolInput = toolInput; + this.toolName = toolName; + } + static isInstance(error) { + return AISDKError.hasMarker(error, ai_dist_marker4); + } + }; + ai_dist_a4 = ai_dist_symbol4; + var ai_dist_name5 = "AI_ToolCallNotFoundForApprovalError"; + var ai_dist_marker5 = `vercel.ai.error.${ai_dist_name5}`; + var ai_dist_symbol5 = Symbol.for(ai_dist_marker5); + var ai_dist_a5; + var ToolCallNotFoundForApprovalError = class extends AISDKError { + constructor({ toolCallId, approvalId }){ + super({ + name: ai_dist_name5, + message: `Tool call "${toolCallId}" not found for approval request "${approvalId}".` + }); + this[ai_dist_a5] = true; + this.toolCallId = toolCallId; + this.approvalId = approvalId; + } + static isInstance(error) { + return AISDKError.hasMarker(error, ai_dist_marker5); + } + }; + ai_dist_a5 = ai_dist_symbol5; + var ai_dist_name6 = "AI_MissingToolResultsError"; + var ai_dist_marker6 = `vercel.ai.error.${ai_dist_name6}`; + var ai_dist_symbol6 = Symbol.for(ai_dist_marker6); + var ai_dist_a6; + var MissingToolResultsError = class extends AISDKError { + constructor({ toolCallIds }){ + super({ + name: ai_dist_name6, + message: `Tool result${toolCallIds.length > 1 ? "s are" : " is"} missing for tool call${toolCallIds.length > 1 ? "s" : ""} ${toolCallIds.join(", ")}.` + }); + this[ai_dist_a6] = true; + this.toolCallIds = toolCallIds; + } + static isInstance(error) { + return AISDKError.hasMarker(error, ai_dist_marker6); + } + }; + ai_dist_a6 = ai_dist_symbol6; + var ai_dist_name7 = "AI_NoImageGeneratedError"; + var ai_dist_marker7 = `vercel.ai.error.${ai_dist_name7}`; + Symbol.for(ai_dist_marker7); + var dist_name8 = "AI_NoObjectGeneratedError"; + var ai_dist_marker8 = `vercel.ai.error.${dist_name8}`; + var ai_dist_symbol8 = Symbol.for(ai_dist_marker8); + var ai_dist_a8; + var NoObjectGeneratedError = class extends AISDKError { + constructor({ message = "No object generated.", cause, text: text2, response, usage, finishReason }){ + super({ + name: dist_name8, + message, + cause + }); + this[ai_dist_a8] = true; + this.text = text2; + this.response = response; + this.usage = usage; + this.finishReason = finishReason; + } + static isInstance(error) { + return AISDKError.hasMarker(error, ai_dist_marker8); + } + }; + ai_dist_a8 = ai_dist_symbol8; + var dist_name9 = "AI_NoOutputGeneratedError"; + var dist_marker9 = `vercel.ai.error.${dist_name9}`; + var dist_symbol9 = Symbol.for(dist_marker9); + var ai_dist_a9; + var NoOutputGeneratedError = class extends AISDKError { + constructor({ message = "No output generated.", cause } = {}){ + super({ + name: dist_name9, + message, + cause + }); + this[ai_dist_a9] = true; + } + static isInstance(error) { + return AISDKError.hasMarker(error, dist_marker9); + } + }; + ai_dist_a9 = dist_symbol9; + var dist_name10 = "AI_NoSpeechGeneratedError"; + var dist_marker10 = `vercel.ai.error.${dist_name10}`; + Symbol.for(dist_marker10); + var dist_name11 = "AI_NoTranscriptGeneratedError"; + var dist_marker11 = `vercel.ai.error.${dist_name11}`; + Symbol.for(dist_marker11); + var dist_name12 = "AI_NoVideoGeneratedError"; + var dist_marker12 = `vercel.ai.error.${dist_name12}`; + Symbol.for(dist_marker12); + var dist_name13 = "AI_NoSuchToolError"; + var dist_marker13 = `vercel.ai.error.${dist_name13}`; + var dist_symbol13 = Symbol.for(dist_marker13); + var dist_a13; + var NoSuchToolError = class extends AISDKError { + constructor({ toolName, availableTools, message = `Model tried to call unavailable tool '${toolName}'. ${void 0 === availableTools ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}` }){ + super({ + name: dist_name13, + message + }); + this[dist_a13] = true; + this.toolName = toolName; + this.availableTools = availableTools; + } + static isInstance(error) { + return AISDKError.hasMarker(error, dist_marker13); + } + }; + dist_a13 = dist_symbol13; + var dist_name14 = "AI_ToolCallRepairError"; + var dist_marker14 = `vercel.ai.error.${dist_name14}`; + var dist_symbol14 = Symbol.for(dist_marker14); + var dist_a14; + var ToolCallRepairError = class extends AISDKError { + constructor({ cause, originalError, message = `Error repairing tool call: ${getErrorMessage(cause)}` }){ + super({ + name: dist_name14, + message, + cause + }); + this[dist_a14] = true; + this.originalError = originalError; + } + static isInstance(error) { + return AISDKError.hasMarker(error, dist_marker14); + } + }; + dist_a14 = dist_symbol14; + var UnsupportedModelVersionError = class extends AISDKError { + constructor(options1){ + super({ + name: "AI_UnsupportedModelVersionError", + message: `Unsupported model version ${options1.version} for provider "${options1.provider}" and model "${options1.modelId}". AI SDK 5 only supports models that implement specification version "v2".` + }); + this.version = options1.version; + this.provider = options1.provider; + this.modelId = options1.modelId; + } + }; + var name15 = "AI_UIMessageStreamError"; + var dist_marker15 = `vercel.ai.error.${name15}`; + Symbol.for(dist_marker15); + var name16 = "AI_InvalidDataContentError"; + var marker16 = `vercel.ai.error.${name16}`; + Symbol.for(marker16); + var name17 = "AI_InvalidMessageRoleError"; + var marker17 = `vercel.ai.error.${name17}`; + var symbol17 = Symbol.for(marker17); + var _a17; + var InvalidMessageRoleError = class extends AISDKError { + constructor({ role, message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".` }){ + super({ + name: name17, + message + }); + this[_a17] = true; + this.role = role; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker17); + } + }; + _a17 = symbol17; + var name18 = "AI_MessageConversionError"; + var marker18 = `vercel.ai.error.${name18}`; + Symbol.for(marker18); + var name19 = "AI_RetryError"; + var marker19 = `vercel.ai.error.${name19}`; + var symbol19 = Symbol.for(marker19); + var _a19; + var RetryError = class extends AISDKError { + constructor({ message, reason, errors }){ + super({ + name: name19, + message + }); + this[_a19] = true; + this.reason = reason; + this.errors = errors; + this.lastError = errors[errors.length - 1]; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker19); + } + }; + _a19 = symbol19; + function asArray(value1) { + return void 0 === value1 ? [] : Array.isArray(value1) ? value1 : [ + value1 + ]; + } + async function notify(options1) { + for (const callback of asArray(options1.callbacks))if (null != callback) try { + await callback(options1.event); + } catch (_ignored) {} + } + function formatWarning({ warning, provider, model }) { + const prefix = `AI SDK Warning (${provider} / ${model}):`; + switch(warning.type){ + case "unsupported": + { + let message = `${prefix} The feature "${warning.feature}" is not supported.`; + if (warning.details) message += ` ${warning.details}`; + return message; + } + case "compatibility": + { + let message = `${prefix} The feature "${warning.feature}" is used in a compatibility mode.`; + 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; + var logWarnings = (options1)=>{ + if (0 === options1.warnings.length) return; + const logger = globalThis.AI_SDK_LOG_WARNINGS; + if (false === logger) return; + if ("function" == typeof logger) return void logger(options1); + if (!hasLoggedBefore) { + hasLoggedBefore = true; + console.info(FIRST_WARNING_INFO_MESSAGE); + } + for (const warning of options1.warnings)console.warn(formatWarning({ + warning, + provider: options1.provider, + model: options1.model + })); + }; + function logV2CompatibilityWarning({ provider, modelId }) { + logWarnings({ + warnings: [ + { + type: "compatibility", + feature: "specificationVersion", + details: "Using v2 specification compatibility mode. Some features may not be available." + } + ], + provider, + model: modelId + }); + } + function asLanguageModelV3(model) { + if ("v3" === model.specificationVersion) return model; + logV2CompatibilityWarning({ + provider: model.provider, + modelId: model.modelId + }); + return new Proxy(model, { + get (target, prop) { + switch(prop){ + case "specificationVersion": + return "v3"; + case "doGenerate": + return async (...args)=>{ + const result = await target.doGenerate(...args); + return { + ...result, + finishReason: convertV2FinishReasonToV3(result.finishReason), + usage: convertV2UsageToV3(result.usage) + }; + }; + case "doStream": + return async (...args)=>{ + const result = await target.doStream(...args); + return { + ...result, + stream: convertV2StreamToV3(result.stream) + }; + }; + default: + return target[prop]; + } + } + }); + } + function convertV2StreamToV3(stream) { + return stream.pipeThrough(new TransformStream({ + transform (chunk, controller) { + switch(chunk.type){ + case "finish": + controller.enqueue({ + ...chunk, + finishReason: convertV2FinishReasonToV3(chunk.finishReason), + usage: convertV2UsageToV3(chunk.usage) + }); + break; + default: + controller.enqueue(chunk); + break; + } + } + })); + } + function convertV2FinishReasonToV3(finishReason) { + return { + unified: "unknown" === finishReason ? "other" : finishReason, + raw: void 0 + }; + } + function convertV2UsageToV3(usage) { + return { + inputTokens: { + total: usage.inputTokens, + noCache: void 0, + cacheRead: usage.cachedInputTokens, + cacheWrite: void 0 + }, + outputTokens: { + total: usage.outputTokens, + text: void 0, + reasoning: usage.reasoningTokens + } + }; + } + function resolveLanguageModel(model) { + if ("string" != typeof model) { + if ("v3" !== model.specificationVersion && "v2" !== model.specificationVersion) { + const unsupportedModel = model; + throw new UnsupportedModelVersionError({ + version: unsupportedModel.specificationVersion, + provider: unsupportedModel.provider, + modelId: unsupportedModel.modelId + }); + } + return asLanguageModelV3(model); + } + return getGlobalProvider().languageModel(model); + } + function getGlobalProvider() { + var _a21; + return null != (_a21 = globalThis.AI_SDK_DEFAULT_PROVIDER) ? _a21 : gateway; + } + function getTotalTimeoutMs(timeout) { + if (null == timeout) return; + if ("number" == typeof timeout) return timeout; + return timeout.totalMs; + } + function getStepTimeoutMs(timeout) { + if (null == timeout || "number" == typeof timeout) return; + return timeout.stepMs; + } + var imageMediaTypeSignatures = [ + { + mediaType: "image/gif", + bytesPrefix: [ + 71, + 73, + 70 + ] + }, + { + mediaType: "image/png", + bytesPrefix: [ + 137, + 80, + 78, + 71 + ] + }, + { + mediaType: "image/jpeg", + bytesPrefix: [ + 255, + 216 + ] + }, + { + mediaType: "image/webp", + bytesPrefix: [ + 82, + 73, + 70, + 70, + null, + null, + null, + null, + 87, + 69, + 66, + 80 + ] + }, + { + mediaType: "image/bmp", + bytesPrefix: [ + 66, + 77 + ] + }, + { + mediaType: "image/tiff", + bytesPrefix: [ + 73, + 73, + 42, + 0 + ] + }, + { + mediaType: "image/tiff", + bytesPrefix: [ + 77, + 77, + 0, + 42 + ] + }, + { + mediaType: "image/avif", + bytesPrefix: [ + 0, + 0, + 0, + 32, + 102, + 116, + 121, + 112, + 97, + 118, + 105, + 102 + ] + }, + { + mediaType: "image/heic", + bytesPrefix: [ + 0, + 0, + 0, + 32, + 102, + 116, + 121, + 112, + 104, + 101, + 105, + 99 + ] + } + ]; + var stripID3 = (data)=>{ + const bytes = "string" == typeof data ? convertBase64ToUint8Array(data) : data; + const id3Size = (127 & bytes[6]) << 21 | (127 & bytes[7]) << 14 | (127 & bytes[8]) << 7 | 127 & bytes[9]; + return bytes.slice(id3Size + 10); + }; + function stripID3TagsIfPresent(data) { + const hasId3 = "string" == typeof data && data.startsWith("SUQz") || "string" != typeof data && data.length > 10 && 73 === data[0] && 68 === data[1] && 51 === data[2]; + return hasId3 ? stripID3(data) : data; + } + function detectMediaType({ data, signatures }) { + const processedData = stripID3TagsIfPresent(data); + const bytes = "string" == typeof processedData ? convertBase64ToUint8Array(processedData.substring(0, Math.min(processedData.length, 24))) : processedData; + for (const signature of signatures)if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index)=>null === byte || bytes[index] === byte)) return signature.mediaType; + } + var ai_dist_VERSION = "6.0.159"; + var download = async ({ url, maxBytes, abortSignal })=>{ + var _a21; + const urlText = url.toString(); + validateDownloadUrl(urlText); + try { + const response = await fetch(urlText, { + headers: withUserAgentSuffix({}, `ai-sdk/${ai_dist_VERSION}`, getRuntimeEnvironmentUserAgent()), + signal: abortSignal + }); + if (response.redirected) validateDownloadUrl(response.url); + if (!response.ok) throw new DownloadError({ + url: urlText, + statusCode: response.status, + statusText: response.statusText + }); + const data = await readResponseWithSizeLimit({ + response, + url: urlText, + maxBytes: null != maxBytes ? maxBytes : DEFAULT_MAX_DOWNLOAD_SIZE + }); + return { + data, + mediaType: null != (_a21 = response.headers.get("content-type")) ? _a21 : void 0 + }; + } catch (error) { + if (DownloadError.isInstance(error)) throw error; + throw new DownloadError({ + url: urlText, + cause: error + }); + } + }; + var createDefaultDownloadFunction = (download2 = download)=>(requestedDownloads)=>Promise.all(requestedDownloads.map(async (requestedDownload)=>requestedDownload.isUrlSupportedByModel ? null : download2(requestedDownload))); + function splitDataUrl(dataUrl) { + try { + const [header, base64Content] = dataUrl.split(","); + return { + mediaType: header.split(";")[0].split(":")[1], + base64Content + }; + } catch (error) { + return { + mediaType: void 0, + base64Content: void 0 + }; + } + } + var dataContentSchema = union([ + schemas_string(), + _instanceof(Uint8Array), + _instanceof(ArrayBuffer), + custom((value1)=>{ + var _a21, _b; + return null != (_b = null == (_a21 = globalThis.Buffer) ? void 0 : _a21.isBuffer(value1)) ? _b : false; + }, { + message: "Must be a Buffer" + }) + ]); + function convertToLanguageModelV3DataContent(content) { + if (content instanceof Uint8Array) return { + data: content, + mediaType: void 0 + }; + if (content instanceof ArrayBuffer) return { + data: new Uint8Array(content), + mediaType: void 0 + }; + if ("string" == typeof content) try { + content = new URL(content); + } catch (error) {} + if (content instanceof URL && "data:" === content.protocol) { + const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(content.toString()); + if (null == dataUrlMediaType || null == base64Content) throw new AISDKError({ + name: "InvalidDataContentError", + message: `Invalid data URL format in content ${content.toString()}` + }); + return { + data: base64Content, + mediaType: dataUrlMediaType + }; + } + return { + data: content, + mediaType: void 0 + }; + } + function convertDataContentToBase64String(content) { + if ("string" == typeof content) return content; + if (content instanceof ArrayBuffer) return convertUint8ArrayToBase64(new Uint8Array(content)); + return convertUint8ArrayToBase64(content); + } + async function convertToLanguageModelPrompt({ prompt, supportedUrls, download: download2 = createDefaultDownloadFunction() }) { + const downloadedAssets = await downloadAssets(prompt.messages, download2, supportedUrls); + const approvalIdToToolCallId = /* @__PURE__ */ new Map(); + for (const message of prompt.messages)if ("assistant" === message.role && Array.isArray(message.content)) { + for (const part of message.content)if ("tool-approval-request" === part.type && "approvalId" in part && "toolCallId" in part) approvalIdToToolCallId.set(part.approvalId, part.toolCallId); + } + const approvedToolCallIds = /* @__PURE__ */ new Set(); + for (const message of prompt.messages)if ("tool" === message.role) { + for (const part of message.content)if ("tool-approval-response" === part.type) { + const toolCallId = approvalIdToToolCallId.get(part.approvalId); + if (toolCallId) approvedToolCallIds.add(toolCallId); + } + } + const messages = [ + ...null != prompt.system ? "string" == typeof prompt.system ? [ + { + role: "system", + content: prompt.system + } + ] : asArray(prompt.system).map((message)=>({ + role: "system", + content: message.content, + providerOptions: message.providerOptions + })) : [], + ...prompt.messages.map((message)=>convertToLanguageModelMessage({ + message, + downloadedAssets + })) + ]; + const combinedMessages = []; + for (const message of messages){ + if ("tool" !== message.role) { + combinedMessages.push(message); + continue; + } + const lastCombinedMessage = combinedMessages.at(-1); + if ((null == lastCombinedMessage ? void 0 : lastCombinedMessage.role) === "tool") lastCombinedMessage.content.push(...message.content); + else combinedMessages.push(message); + } + const toolCallIds = /* @__PURE__ */ new Set(); + for (const message of combinedMessages)switch(message.role){ + case "assistant": + for (const content of message.content)if ("tool-call" === content.type && !content.providerExecuted) toolCallIds.add(content.toolCallId); + break; + case "tool": + for (const content of message.content)if ("tool-result" === content.type) toolCallIds.delete(content.toolCallId); + break; + case "user": + case "system": + for (const id of approvedToolCallIds)toolCallIds.delete(id); + if (toolCallIds.size > 0) throw new MissingToolResultsError({ + toolCallIds: Array.from(toolCallIds) + }); + break; + } + for (const id of approvedToolCallIds)toolCallIds.delete(id); + if (toolCallIds.size > 0) throw new MissingToolResultsError({ + toolCallIds: Array.from(toolCallIds) + }); + return combinedMessages.filter((message)=>"tool" !== message.role || message.content.length > 0); + } + function convertToLanguageModelMessage({ message, downloadedAssets }) { + const role = message.role; + switch(role){ + case "system": + return { + role: "system", + content: message.content, + providerOptions: message.providerOptions + }; + case "user": + if ("string" == typeof message.content) return { + role: "user", + content: [ + { + type: "text", + text: message.content + } + ], + providerOptions: message.providerOptions + }; + return { + role: "user", + content: message.content.map((part)=>convertPartToLanguageModelPart(part, downloadedAssets)).filter((part)=>"text" !== part.type || "" !== part.text), + providerOptions: message.providerOptions + }; + case "assistant": + if ("string" == typeof message.content) return { + role: "assistant", + content: [ + { + type: "text", + text: message.content + } + ], + providerOptions: message.providerOptions + }; + return { + role: "assistant", + content: message.content.filter((part)=>"text" !== part.type || "" !== part.text || null != part.providerOptions).filter((part)=>"tool-approval-request" !== part.type).map((part)=>{ + const providerOptions = part.providerOptions; + switch(part.type){ + case "file": + { + const { data, mediaType } = convertToLanguageModelV3DataContent(part.data); + return { + type: "file", + data, + filename: part.filename, + mediaType: null != mediaType ? mediaType : part.mediaType, + providerOptions + }; + } + case "reasoning": + return { + type: "reasoning", + text: part.text, + providerOptions + }; + case "text": + return { + type: "text", + text: part.text, + providerOptions + }; + case "tool-call": + return { + type: "tool-call", + toolCallId: part.toolCallId, + toolName: part.toolName, + input: part.input, + providerExecuted: part.providerExecuted, + providerOptions + }; + case "tool-result": + return { + type: "tool-result", + toolCallId: part.toolCallId, + toolName: part.toolName, + output: mapToolResultOutput(part.output), + providerOptions + }; + } + }), + providerOptions: message.providerOptions + }; + case "tool": + return { + role: "tool", + content: message.content.filter((part)=>"tool-approval-response" !== part.type || part.providerExecuted).map((part)=>{ + switch(part.type){ + case "tool-result": + return { + type: "tool-result", + toolCallId: part.toolCallId, + toolName: part.toolName, + output: mapToolResultOutput(part.output), + providerOptions: part.providerOptions + }; + case "tool-approval-response": + return { + type: "tool-approval-response", + approvalId: part.approvalId, + approved: part.approved, + reason: part.reason + }; + } + }), + providerOptions: message.providerOptions + }; + default: + { + const _exhaustiveCheck = role; + throw new InvalidMessageRoleError({ + role: _exhaustiveCheck + }); + } + } + } + async function downloadAssets(messages, download2, supportedUrls) { + const plannedDownloads = messages.filter((message)=>"user" === message.role).map((message)=>message.content).filter((content)=>Array.isArray(content)).flat().filter((part)=>"image" === part.type || "file" === part.type).map((part)=>{ + var _a21; + const mediaType = null != (_a21 = part.mediaType) ? _a21 : "image" === part.type ? "image/*" : void 0; + let data = "image" === part.type ? part.image : part.data; + if ("string" == typeof data) try { + data = new URL(data); + } catch (ignored) {} + return { + mediaType, + data + }; + }).filter((part)=>part.data instanceof URL).map((part)=>({ + url: part.data, + isUrlSupportedByModel: null != part.mediaType && isUrlSupported({ + url: part.data.toString(), + mediaType: part.mediaType, + supportedUrls + }) + })); + const downloadedFiles = await download2(plannedDownloads); + return Object.fromEntries(downloadedFiles.map((file, index)=>null == file ? null : [ + plannedDownloads[index].url.toString(), + { + data: file.data, + mediaType: file.mediaType + } + ]).filter((file)=>null != file)); + } + function convertPartToLanguageModelPart(part, downloadedAssets) { + var _a21; + if ("text" === part.type) return { + type: "text", + text: part.text, + providerOptions: part.providerOptions + }; + let originalData; + const type = part.type; + switch(type){ + case "image": + originalData = part.image; + break; + case "file": + originalData = part.data; + break; + default: + throw new Error(`Unsupported part type: ${type}`); + } + const { data: convertedData, mediaType: convertedMediaType } = convertToLanguageModelV3DataContent(originalData); + let mediaType = null != convertedMediaType ? convertedMediaType : part.mediaType; + let data = convertedData; + if (data instanceof URL) { + const downloadedFile = downloadedAssets[data.toString()]; + if (downloadedFile) { + data = downloadedFile.data; + null != mediaType || (mediaType = downloadedFile.mediaType); + } + } + switch(type){ + case "image": + if (data instanceof Uint8Array || "string" == typeof data) mediaType = null != (_a21 = detectMediaType({ + data, + signatures: imageMediaTypeSignatures + })) ? _a21 : mediaType; + return { + type: "file", + mediaType: null != mediaType ? mediaType : "image/*", + filename: void 0, + data, + providerOptions: part.providerOptions + }; + case "file": + if (null == mediaType) throw new Error("Media type is missing for file part"); + return { + type: "file", + mediaType, + filename: part.filename, + data, + providerOptions: part.providerOptions + }; + } + } + function mapToolResultOutput(output) { + if ("content" !== output.type) return output; + return { + type: "content", + value: output.value.map((item)=>{ + if ("media" !== item.type) return item; + if (item.mediaType.startsWith("image/")) return { + type: "image-data", + data: item.data, + mediaType: item.mediaType + }; + return { + type: "file-data", + data: item.data, + mediaType: item.mediaType + }; + }) + }; + } + async function createToolModelOutput({ toolCallId, input, output, tool: tool2, errorMode }) { + if ("text" === errorMode) return { + type: "error-text", + value: getErrorMessage(output) + }; + if ("json" === errorMode) return { + type: "error-json", + value: toJSONValue(output) + }; + if (null == tool2 ? void 0 : tool2.toModelOutput) return await tool2.toModelOutput({ + toolCallId, + input, + output + }); + return "string" == typeof output ? { + type: "text", + value: output + } : { + type: "json", + value: toJSONValue(output) + }; + } + function toJSONValue(value1) { + return void 0 === value1 ? null : value1; + } + function prepareCallSettings({ maxOutputTokens, temperature, topP, topK, presencePenalty, frequencyPenalty, seed, stopSequences }) { + if (null != maxOutputTokens) { + if (!Number.isInteger(maxOutputTokens)) throw new dist_InvalidArgumentError({ + parameter: "maxOutputTokens", + value: maxOutputTokens, + message: "maxOutputTokens must be an integer" + }); + if (maxOutputTokens < 1) throw new dist_InvalidArgumentError({ + parameter: "maxOutputTokens", + value: maxOutputTokens, + message: "maxOutputTokens must be >= 1" + }); + } + if (null != temperature) { + if ("number" != typeof temperature) throw new dist_InvalidArgumentError({ + parameter: "temperature", + value: temperature, + message: "temperature must be a number" + }); + } + if (null != topP) { + if ("number" != typeof topP) throw new dist_InvalidArgumentError({ + parameter: "topP", + value: topP, + message: "topP must be a number" + }); + } + if (null != topK) { + if ("number" != typeof topK) throw new dist_InvalidArgumentError({ + parameter: "topK", + value: topK, + message: "topK must be a number" + }); + } + if (null != presencePenalty) { + if ("number" != typeof presencePenalty) throw new dist_InvalidArgumentError({ + parameter: "presencePenalty", + value: presencePenalty, + message: "presencePenalty must be a number" + }); + } + if (null != frequencyPenalty) { + if ("number" != typeof frequencyPenalty) throw new dist_InvalidArgumentError({ + parameter: "frequencyPenalty", + value: frequencyPenalty, + message: "frequencyPenalty must be a number" + }); + } + if (null != seed) { + if (!Number.isInteger(seed)) throw new dist_InvalidArgumentError({ + parameter: "seed", + value: seed, + message: "seed must be an integer" + }); + } + return { + maxOutputTokens, + temperature, + topP, + topK, + presencePenalty, + frequencyPenalty, + stopSequences, + seed + }; + } + function isNonEmptyObject(object2) { + return null != object2 && Object.keys(object2).length > 0; + } + async function prepareToolsAndToolChoice({ tools, toolChoice, activeTools }) { + if (!isNonEmptyObject(tools)) return { + tools: void 0, + toolChoice: void 0 + }; + const filteredTools = null != activeTools ? Object.entries(tools).filter(([name21])=>activeTools.includes(name21)) : Object.entries(tools); + const languageModelTools = []; + for (const [name21, tool2] of filteredTools){ + const toolType = tool2.type; + switch(toolType){ + case void 0: + case "dynamic": + case "function": + languageModelTools.push({ + type: "function", + name: name21, + description: tool2.description, + inputSchema: await asSchema(tool2.inputSchema).jsonSchema, + ...null != tool2.inputExamples ? { + inputExamples: tool2.inputExamples + } : {}, + providerOptions: tool2.providerOptions, + ...null != tool2.strict ? { + strict: tool2.strict + } : {} + }); + break; + case "provider": + languageModelTools.push({ + type: "provider", + name: name21, + id: tool2.id, + args: tool2.args + }); + break; + default: + { + const exhaustiveCheck = toolType; + throw new Error(`Unsupported tool type: ${exhaustiveCheck}`); + } + } + } + return { + tools: languageModelTools, + toolChoice: null == toolChoice ? { + type: "auto" + } : "string" == typeof toolChoice ? { + type: toolChoice + } : { + type: "tool", + toolName: toolChoice.toolName + } + }; + } + var jsonValueSchema = lazy(()=>union([ + schemas_null(), + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_record(schemas_string(), jsonValueSchema.optional()), + schemas_array(jsonValueSchema) + ])); + var providerMetadataSchema = schemas_record(schemas_string(), schemas_record(schemas_string(), jsonValueSchema.optional())); + var textPartSchema = schemas_object({ + type: schemas_literal("text"), + text: schemas_string(), + providerOptions: providerMetadataSchema.optional() + }); + var imagePartSchema = schemas_object({ + type: schemas_literal("image"), + image: union([ + dataContentSchema, + _instanceof(URL) + ]), + mediaType: schemas_string().optional(), + providerOptions: providerMetadataSchema.optional() + }); + var filePartSchema = schemas_object({ + type: schemas_literal("file"), + data: union([ + dataContentSchema, + _instanceof(URL) + ]), + filename: schemas_string().optional(), + mediaType: schemas_string(), + providerOptions: providerMetadataSchema.optional() + }); + var reasoningPartSchema = schemas_object({ + type: schemas_literal("reasoning"), + text: schemas_string(), + providerOptions: providerMetadataSchema.optional() + }); + var toolCallPartSchema = schemas_object({ + type: schemas_literal("tool-call"), + toolCallId: schemas_string(), + toolName: schemas_string(), + input: unknown(), + providerOptions: providerMetadataSchema.optional(), + providerExecuted: schemas_boolean().optional() + }); + var dist_outputSchema = discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("text"), + value: schemas_string(), + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("json"), + value: jsonValueSchema, + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("execution-denied"), + reason: schemas_string().optional(), + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("error-text"), + value: schemas_string(), + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("error-json"), + value: jsonValueSchema, + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("content"), + value: schemas_array(union([ + schemas_object({ + type: schemas_literal("text"), + text: schemas_string(), + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("media"), + data: schemas_string(), + mediaType: schemas_string() + }), + schemas_object({ + type: schemas_literal("file-data"), + data: schemas_string(), + mediaType: schemas_string(), + filename: schemas_string().optional(), + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("file-url"), + url: schemas_string(), + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("file-id"), + fileId: union([ + schemas_string(), + schemas_record(schemas_string(), schemas_string()) + ]), + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("image-data"), + data: schemas_string(), + mediaType: schemas_string(), + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("image-url"), + url: schemas_string(), + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("image-file-id"), + fileId: union([ + schemas_string(), + schemas_record(schemas_string(), schemas_string()) + ]), + providerOptions: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("custom"), + providerOptions: providerMetadataSchema.optional() + }) + ])) + }) + ]); + var toolResultPartSchema = schemas_object({ + type: schemas_literal("tool-result"), + toolCallId: schemas_string(), + toolName: schemas_string(), + output: dist_outputSchema, + providerOptions: providerMetadataSchema.optional() + }); + var toolApprovalRequestSchema = schemas_object({ + type: schemas_literal("tool-approval-request"), + approvalId: schemas_string(), + toolCallId: schemas_string() + }); + var toolApprovalResponseSchema = schemas_object({ + type: schemas_literal("tool-approval-response"), + approvalId: schemas_string(), + approved: schemas_boolean(), + reason: schemas_string().optional() + }); + var systemModelMessageSchema = schemas_object({ + role: schemas_literal("system"), + content: schemas_string(), + providerOptions: providerMetadataSchema.optional() + }); + var userModelMessageSchema = schemas_object({ + role: schemas_literal("user"), + content: union([ + schemas_string(), + schemas_array(union([ + textPartSchema, + imagePartSchema, + filePartSchema + ])) + ]), + providerOptions: providerMetadataSchema.optional() + }); + var assistantModelMessageSchema = schemas_object({ + role: schemas_literal("assistant"), + content: union([ + schemas_string(), + schemas_array(union([ + textPartSchema, + filePartSchema, + reasoningPartSchema, + toolCallPartSchema, + toolResultPartSchema, + toolApprovalRequestSchema + ])) + ]), + providerOptions: providerMetadataSchema.optional() + }); + var toolModelMessageSchema = schemas_object({ + role: schemas_literal("tool"), + content: schemas_array(union([ + toolResultPartSchema, + toolApprovalResponseSchema + ])), + providerOptions: providerMetadataSchema.optional() + }); + var modelMessageSchema = union([ + systemModelMessageSchema, + userModelMessageSchema, + assistantModelMessageSchema, + toolModelMessageSchema + ]); + async function standardizePrompt(prompt) { + if (null == prompt.prompt && null == prompt.messages) throw new InvalidPromptError({ + prompt, + message: "prompt or messages must be defined" + }); + if (null != prompt.prompt && null != prompt.messages) throw new InvalidPromptError({ + prompt, + message: "prompt and messages cannot be defined at the same time" + }); + if (null != prompt.system && "string" != typeof prompt.system && !asArray(prompt.system).every((message)=>"object" == typeof message && null !== message && "role" in message && "system" === message.role)) throw new InvalidPromptError({ + prompt, + message: "system must be a string, SystemModelMessage, or array of SystemModelMessage" + }); + let messages; + if (null != prompt.prompt && "string" == typeof prompt.prompt) messages = [ + { + role: "user", + content: prompt.prompt + } + ]; + else if (null != prompt.prompt && Array.isArray(prompt.prompt)) messages = prompt.prompt; + else if (null != prompt.messages) messages = prompt.messages; + else throw new InvalidPromptError({ + prompt, + message: "prompt or messages must be defined" + }); + if (0 === messages.length) throw new InvalidPromptError({ + prompt, + message: "messages must not be empty" + }); + const validationResult = await safeValidateTypes({ + value: messages, + schema: schemas_array(modelMessageSchema) + }); + if (!validationResult.success) throw new InvalidPromptError({ + prompt, + message: "The messages do not match the ModelMessage[] schema.", + cause: validationResult.error + }); + return { + messages, + system: prompt.system + }; + } + function wrapGatewayError(error) { + if (!GatewayAuthenticationError.isInstance(error)) return error; + const isProductionEnv = (null == process ? void 0 : process.env.NODE_ENV) === "production"; + const moreInfoURL = "https://ai-sdk.dev/unauthenticated-ai-gateway"; + if (isProductionEnv) return new AISDKError({ + name: "GatewayError", + message: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}` + }); + return Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m + +To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key. + +Alternatively, you can use a provider module instead of the AI Gateway. + +Learn more: \x1B[34m${moreInfoURL}\x1B[0m + +`), { + name: "GatewayAuthenticationError" + }); + } + function assembleOperationName({ operationId, telemetry }) { + return { + "operation.name": `${operationId}${(null == telemetry ? void 0 : telemetry.functionId) != null ? ` ${telemetry.functionId}` : ""}`, + "resource.name": null == telemetry ? void 0 : telemetry.functionId, + "ai.operationId": operationId, + "ai.telemetry.functionId": null == telemetry ? void 0 : telemetry.functionId + }; + } + function getBaseTelemetryAttributes({ model, settings, telemetry, headers }) { + var _a21; + return { + "ai.model.provider": model.provider, + "ai.model.id": model.modelId, + ...Object.entries(settings).reduce((attributes, [key, value1])=>{ + if ("timeout" === key) { + const totalTimeoutMs = getTotalTimeoutMs(value1); + if (null != totalTimeoutMs) attributes[`ai.settings.${key}`] = totalTimeoutMs; + } else attributes[`ai.settings.${key}`] = value1; + return attributes; + }, {}), + ...Object.entries(null != (_a21 = null == telemetry ? void 0 : telemetry.metadata) ? _a21 : {}).reduce((attributes, [key, value1])=>{ + attributes[`ai.telemetry.metadata.${key}`] = value1; + return attributes; + }, {}), + ...Object.entries(null != headers ? headers : {}).reduce((attributes, [key, value1])=>{ + if (void 0 !== value1) attributes[`ai.request.headers.${key}`] = value1; + return attributes; + }, {}) + }; + } + var noopTracer = { + startSpan () { + return noopSpan; + }, + startActiveSpan (name21, arg1, arg2, arg3) { + if ("function" == typeof arg1) return arg1(noopSpan); + if ("function" == typeof arg2) return arg2(noopSpan); + if ("function" == typeof arg3) 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"); + } + async function recordSpan({ name: name21, tracer, attributes, fn, endWhenDone = true }) { + return tracer.startActiveSpan(name21, { + attributes: await attributes + }, async (span)=>{ + const ctx = context_api_context.active(); + try { + const result = await context_api_context["with"](ctx, ()=>fn(span)); + if (endWhenDone) span.end(); + return result; + } catch (error) { + try { + recordErrorOnSpan(span, error); + } finally{ + 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: status_SpanStatusCode.ERROR, + message: error.message + }); + } else span.setStatus({ + code: status_SpanStatusCode.ERROR + }); + } + async function selectTelemetryAttributes({ telemetry, attributes }) { + if ((null == telemetry ? void 0 : telemetry.isEnabled) !== true) return {}; + const resultAttributes = {}; + for (const [key, value1] of Object.entries(attributes))if (null != value1) { + if ("object" == typeof value1 && "input" in value1 && "function" == typeof value1.input) { + if ((null == telemetry ? void 0 : telemetry.recordInputs) === false) continue; + const result = await value1.input(); + if (null != result) resultAttributes[key] = result; + continue; + } + if ("object" == typeof value1 && "output" in value1 && "function" == typeof value1.output) { + if ((null == telemetry ? void 0 : telemetry.recordOutputs) === false) continue; + const result = await value1.output(); + if (null != result) resultAttributes[key] = result; + continue; + } + resultAttributes[key] = value1; + } + return resultAttributes; + } + function stringifyForTelemetry(prompt) { + return JSON.stringify(prompt.map((message)=>({ + ...message, + content: "string" == typeof message.content ? message.content : message.content.map((part)=>"file" === part.type ? { + ...part, + data: part.data instanceof Uint8Array ? convertDataContentToBase64String(part.data) : part.data + } : part) + }))); + } + function getGlobalTelemetryIntegrations() { + var _a21; + return null != (_a21 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) ? _a21 : []; + } + function getGlobalTelemetryIntegration() { + const globalIntegrations = getGlobalTelemetryIntegrations(); + return (integrations)=>{ + const localIntegrations = asArray(integrations); + const allIntegrations = [ + ...globalIntegrations, + ...localIntegrations + ]; + function createTelemetryComposite(getListenerFromIntegration) { + const listeners = allIntegrations.map(getListenerFromIntegration).filter(Boolean); + return async (event)=>{ + for (const listener of listeners)try { + await listener(event); + } catch (_ignored) {} + }; + } + return { + onStart: createTelemetryComposite((integration)=>integration.onStart), + onStepStart: createTelemetryComposite((integration)=>integration.onStepStart), + onToolCallStart: createTelemetryComposite((integration)=>integration.onToolCallStart), + onToolCallFinish: createTelemetryComposite((integration)=>integration.onToolCallFinish), + onStepFinish: createTelemetryComposite((integration)=>integration.onStepFinish), + onFinish: createTelemetryComposite((integration)=>integration.onFinish) + }; + }; + } + function asLanguageModelUsage(usage) { + return { + inputTokens: usage.inputTokens.total, + inputTokenDetails: { + noCacheTokens: usage.inputTokens.noCache, + cacheReadTokens: usage.inputTokens.cacheRead, + cacheWriteTokens: usage.inputTokens.cacheWrite + }, + outputTokens: usage.outputTokens.total, + outputTokenDetails: { + textTokens: usage.outputTokens.text, + reasoningTokens: usage.outputTokens.reasoning + }, + totalTokens: addTokenCounts(usage.inputTokens.total, usage.outputTokens.total), + raw: usage.raw, + reasoningTokens: usage.outputTokens.reasoning, + cachedInputTokens: usage.inputTokens.cacheRead + }; + } + function addLanguageModelUsage(usage1, usage2) { + var _a21, _b, _c, _d, _e, _f, _g, _h, _i, _j; + return { + inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens), + inputTokenDetails: { + noCacheTokens: addTokenCounts(null == (_a21 = usage1.inputTokenDetails) ? void 0 : _a21.noCacheTokens, null == (_b = usage2.inputTokenDetails) ? void 0 : _b.noCacheTokens), + cacheReadTokens: addTokenCounts(null == (_c = usage1.inputTokenDetails) ? void 0 : _c.cacheReadTokens, null == (_d = usage2.inputTokenDetails) ? void 0 : _d.cacheReadTokens), + cacheWriteTokens: addTokenCounts(null == (_e = usage1.inputTokenDetails) ? void 0 : _e.cacheWriteTokens, null == (_f = usage2.inputTokenDetails) ? void 0 : _f.cacheWriteTokens) + }, + outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens), + outputTokenDetails: { + textTokens: addTokenCounts(null == (_g = usage1.outputTokenDetails) ? void 0 : _g.textTokens, null == (_h = usage2.outputTokenDetails) ? void 0 : _h.textTokens), + reasoningTokens: addTokenCounts(null == (_i = usage1.outputTokenDetails) ? void 0 : _i.reasoningTokens, null == (_j = usage2.outputTokenDetails) ? void 0 : _j.reasoningTokens) + }, + totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens), + reasoningTokens: addTokenCounts(usage1.reasoningTokens, usage2.reasoningTokens), + cachedInputTokens: addTokenCounts(usage1.cachedInputTokens, usage2.cachedInputTokens) + }; + } + function addTokenCounts(tokenCount1, tokenCount2) { + return null == tokenCount1 && null == tokenCount2 ? void 0 : (null != tokenCount1 ? tokenCount1 : 0) + (null != tokenCount2 ? tokenCount2 : 0); + } + function mergeObjects(base, overrides) { + if (void 0 === base && void 0 === overrides) return; + if (void 0 === base) return overrides; + if (void 0 === overrides) return base; + const result = { + ...base + }; + for(const key in overrides)if (Object.prototype.hasOwnProperty.call(overrides, key)) { + const overridesValue = overrides[key]; + if (void 0 === overridesValue) continue; + const baseValue = key in base ? base[key] : void 0; + const isSourceObject = null !== overridesValue && "object" == typeof overridesValue && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp); + const isTargetObject = null != baseValue && "object" == typeof baseValue && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp); + if (isSourceObject && isTargetObject) result[key] = mergeObjects(baseValue, overridesValue); + else result[key] = overridesValue; + } + return result; + } + function getRetryDelayInMs({ error, exponentialBackoffDelay }) { + const headers = error.responseHeaders; + 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 && void 0 === ms) { + const timeoutSeconds = parseFloat(retryAfter); + ms = Number.isNaN(timeoutSeconds) ? Date.parse(retryAfter) - Date.now() : 1e3 * timeoutSeconds; + } + if (null != ms && !Number.isNaN(ms) && 0 <= ms && (ms < 60000 || ms < exponentialBackoffDelay)) return ms; + return exponentialBackoffDelay; + } + var retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal } = {})=>async (f)=>_retryWithExponentialBackoff(f, { + maxRetries, + delayInMs: initialDelayInMs, + backoffFactor, + abortSignal + }); + async function _retryWithExponentialBackoff(f, { maxRetries, delayInMs, backoffFactor, abortSignal }, errors = []) { + try { + return await f(); + } catch (error) { + if (isAbortError(error)) throw error; + if (0 === maxRetries) throw error; + const errorMessage = dist_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) && true === error.isRetryable && tryNumber <= maxRetries) { + await delay(getRetryDelayInMs({ + error, + exponentialBackoffDelay: delayInMs + }), { + abortSignal + }); + return _retryWithExponentialBackoff(f, { + maxRetries, + delayInMs: backoffFactor * delayInMs, + backoffFactor, + abortSignal + }, newErrors); + } + if (1 === tryNumber) throw error; + throw new RetryError({ + message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`, + reason: "errorNotRetryable", + errors: newErrors + }); + } + } + function prepareRetries({ maxRetries, abortSignal }) { + if (null != maxRetries) { + if (!Number.isInteger(maxRetries)) throw new dist_InvalidArgumentError({ + parameter: "maxRetries", + value: maxRetries, + message: "maxRetries must be an integer" + }); + if (maxRetries < 0) throw new dist_InvalidArgumentError({ + parameter: "maxRetries", + value: maxRetries, + message: "maxRetries must be >= 0" + }); + } + const maxRetriesResult = null != maxRetries ? maxRetries : 2; + return { + maxRetries: maxRetriesResult, + retry: retryWithExponentialBackoffRespectingRetryHeaders({ + maxRetries: maxRetriesResult, + abortSignal + }) + }; + } + function collectToolApprovals({ messages }) { + const lastMessage = messages.at(-1); + if ((null == lastMessage ? void 0 : lastMessage.role) != "tool") return { + approvedToolApprovals: [], + deniedToolApprovals: [] + }; + const toolCallsByToolCallId = {}; + for (const message of messages)if ("assistant" === message.role && "string" != typeof message.content) { + const content = message.content; + for (const part of content)if ("tool-call" === part.type) toolCallsByToolCallId[part.toolCallId] = part; + } + const toolApprovalRequestsByApprovalId = {}; + for (const message of messages)if ("assistant" === message.role && "string" != typeof message.content) { + const content = message.content; + for (const part of content)if ("tool-approval-request" === part.type) toolApprovalRequestsByApprovalId[part.approvalId] = part; + } + const toolResults = {}; + for (const part of lastMessage.content)if ("tool-result" === part.type) toolResults[part.toolCallId] = part; + const approvedToolApprovals = []; + const deniedToolApprovals = []; + const approvalResponses = lastMessage.content.filter((part)=>"tool-approval-response" === part.type); + for (const approvalResponse of approvalResponses){ + const approvalRequest = toolApprovalRequestsByApprovalId[approvalResponse.approvalId]; + if (null == approvalRequest) throw new InvalidToolApprovalError({ + approvalId: approvalResponse.approvalId + }); + if (null != toolResults[approvalRequest.toolCallId]) continue; + const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId]; + if (null == toolCall) throw new ToolCallNotFoundForApprovalError({ + toolCallId: approvalRequest.toolCallId, + approvalId: approvalRequest.approvalId + }); + const approval = { + approvalRequest, + approvalResponse, + toolCall + }; + if (approvalResponse.approved) approvedToolApprovals.push(approval); + else deniedToolApprovals.push(approval); + } + return { + approvedToolApprovals, + deniedToolApprovals + }; + } + function dist_now() { + var _a21, _b; + return null != (_b = null == (_a21 = null == globalThis ? void 0 : globalThis.performance) ? void 0 : _a21.now()) ? _b : Date.now(); + } + async function executeToolCall({ toolCall, tools, tracer, telemetry, messages, abortSignal, experimental_context, stepNumber, model, onPreliminaryToolResult, onToolCallStart, onToolCallFinish }) { + const { toolName, toolCallId, input } = toolCall; + const tool2 = null == tools ? void 0 : tools[toolName]; + if ((null == tool2 ? void 0 : tool2.execute) == null) return; + const baseCallbackEvent = { + stepNumber, + model, + toolCall, + messages, + abortSignal, + functionId: null == telemetry ? void 0 : telemetry.functionId, + metadata: null == telemetry ? void 0 : telemetry.metadata, + experimental_context + }; + return recordSpan({ + name: "ai.toolCall", + attributes: selectTelemetryAttributes({ + telemetry, + attributes: { + ...assembleOperationName({ + operationId: "ai.toolCall", + telemetry + }), + "ai.toolCall.name": toolName, + "ai.toolCall.id": toolCallId, + "ai.toolCall.args": { + output: ()=>JSON.stringify(input) + } + } + }), + tracer, + fn: async (span)=>{ + let output; + await notify({ + event: baseCallbackEvent, + callbacks: onToolCallStart + }); + const startTime = dist_now(); + try { + const stream = executeTool({ + execute: tool2.execute.bind(tool2), + input, + options: { + toolCallId, + messages, + abortSignal, + experimental_context + } + }); + for await (const part of stream)if ("preliminary" === part.type) null == onPreliminaryToolResult || onPreliminaryToolResult({ + ...toolCall, + type: "tool-result", + output: part.output, + preliminary: true + }); + else output = part.output; + } catch (error) { + const durationMs2 = dist_now() - startTime; + await notify({ + event: { + ...baseCallbackEvent, + success: false, + error, + durationMs: durationMs2 + }, + callbacks: onToolCallFinish + }); + recordErrorOnSpan(span, error); + return { + type: "tool-error", + toolCallId, + toolName, + input, + error, + dynamic: "dynamic" === tool2.type, + ...null != toolCall.providerMetadata ? { + providerMetadata: toolCall.providerMetadata + } : {} + }; + } + const durationMs = dist_now() - startTime; + await notify({ + event: { + ...baseCallbackEvent, + success: true, + output, + durationMs + }, + callbacks: onToolCallFinish + }); + try { + span.setAttributes(await selectTelemetryAttributes({ + telemetry, + attributes: { + "ai.toolCall.result": { + output: ()=>JSON.stringify(output) + } + } + })); + } catch (ignored) {} + return { + type: "tool-result", + toolCallId, + toolName, + input, + output, + dynamic: "dynamic" === tool2.type, + ...null != toolCall.providerMetadata ? { + providerMetadata: toolCall.providerMetadata + } : {} + }; + } + }); + } + function extractReasoningContent(content) { + const parts = content.filter((content2)=>"reasoning" === content2.type); + return 0 === parts.length ? void 0 : parts.map((content2)=>content2.text).join("\n"); + } + function extractTextContent(content) { + const parts = content.filter((content2)=>"text" === content2.type); + if (0 === parts.length) return; + return parts.map((content2)=>content2.text).join(""); + } + var DefaultGeneratedFile = class { + constructor({ data, mediaType }){ + const isUint8Array = data instanceof Uint8Array; + this.base64Data = isUint8Array ? void 0 : data; + this.uint8ArrayData = isUint8Array ? data : void 0; + this.mediaType = mediaType; + } + get base64() { + if (null == this.base64Data) this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData); + return this.base64Data; + } + get uint8Array() { + if (null == this.uint8ArrayData) this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data); + return this.uint8ArrayData; + } + }; + async function isApprovalNeeded({ tool: tool2, toolCall, messages, experimental_context }) { + if (null == tool2.needsApproval) return false; + if ("boolean" == typeof tool2.needsApproval) return tool2.needsApproval; + return await tool2.needsApproval(toolCall.input, { + toolCallId: toolCall.toolCallId, + messages, + experimental_context + }); + } + var output_exports = {}; + __export(output_exports, { + array: ()=>dist_array, + choice: ()=>dist_choice, + json: ()=>dist_json, + object: ()=>dist_object, + text: ()=>dist_text + }); + 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"); + break; + } + } + function processAfterObjectValue(char, i) { + switch(char){ + case ",": + stack.pop(); + stack.push("INSIDE_OBJECT_AFTER_COMMA"); + break; + case "}": + lastValidIndex = i; + stack.pop(); + break; + } + } + function processAfterArrayValue(char, i) { + switch(char){ + case ",": + stack.pop(); + stack.push("INSIDE_ARRAY_AFTER_COMMA"); + break; + case "]": + lastValidIndex = i; + stack.pop(); + break; + } + } + for(let i = 0; i < input.length; i++){ + const char = input[i]; + const currentState = stack[stack.length - 1]; + switch(currentState){ + 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; + } + break; + case "INSIDE_OBJECT_AFTER_COMMA": + switch(char){ + case '"': + stack.pop(); + stack.push("INSIDE_OBJECT_KEY"); + break; + } + break; + case "INSIDE_OBJECT_KEY": + switch(char){ + case '"': + stack.pop(); + stack.push("INSIDE_OBJECT_AFTER_KEY"); + break; + } + break; + case "INSIDE_OBJECT_AFTER_KEY": + switch(char){ + case ":": + stack.pop(); + stack.push("INSIDE_OBJECT_BEFORE_VALUE"); + break; + } + 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; + } + 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; + } + 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 ("INSIDE_ARRAY_AFTER_VALUE" === stack[stack.length - 1]) processAfterArrayValue(char, i); + if ("INSIDE_OBJECT_AFTER_VALUE" === stack[stack.length - 1]) processAfterObjectValue(char, i); + break; + case "}": + stack.pop(); + if ("INSIDE_OBJECT_AFTER_VALUE" === stack[stack.length - 1]) processAfterObjectValue(char, i); + break; + case "]": + stack.pop(); + if ("INSIDE_ARRAY_AFTER_VALUE" === stack[stack.length - 1]) processAfterArrayValue(char, i); + break; + default: + stack.pop(); + break; + } + break; + case "INSIDE_LITERAL": + { + const partialLiteral = input.substring(literalStart, i + 1); + if ("false".startsWith(partialLiteral) || "true".startsWith(partialLiteral) || "null".startsWith(partialLiteral)) lastValidIndex = i; + else { + stack.pop(); + if ("INSIDE_OBJECT_AFTER_VALUE" === stack[stack.length - 1]) processAfterObjectValue(char, i); + else if ("INSIDE_ARRAY_AFTER_VALUE" === stack[stack.length - 1]) processAfterArrayValue(char, i); + } + break; + } + } + } + let result = input.slice(0, lastValidIndex + 1); + for(let i = stack.length - 1; i >= 0; i--){ + const state = stack[i]; + switch(state){ + 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 (void 0 === jsonText) 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" + }; + } + var dist_text = ()=>({ + name: "text", + responseFormat: Promise.resolve({ + type: "text" + }), + async parseCompleteOutput ({ text: text2 }) { + return text2; + }, + async parsePartialOutput ({ text: text2 }) { + return { + partial: text2 + }; + }, + createElementStreamTransform () {} + }); + var dist_object = ({ schema: inputSchema, name: name21, description })=>{ + const schema = asSchema(inputSchema); + return { + name: "object", + responseFormat: dist_resolve(schema.jsonSchema).then((jsonSchema2)=>({ + type: "json", + schema: jsonSchema2, + ...null != name21 && { + name: name21 + }, + ...null != description && { + description + } + })), + async parseCompleteOutput ({ text: text2 }, context2) { + 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: context2.response, + usage: context2.usage, + finishReason: context2.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: context2.response, + usage: context2.usage, + finishReason: context2.finishReason + }); + return validationResult.value; + }, + async parsePartialOutput ({ 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 + }; + } + }, + createElementStreamTransform () {} + }; + }; + var dist_array = ({ element: inputElementSchema, name: name21, description })=>{ + const elementSchema = asSchema(inputElementSchema); + return { + name: "array", + responseFormat: dist_resolve(elementSchema.jsonSchema).then((jsonSchema2)=>{ + const { $schema, ...itemSchema } = jsonSchema2; + return { + type: "json", + schema: { + $schema: "http://json-schema.org/draft-07/schema#", + type: "object", + properties: { + elements: { + type: "array", + items: itemSchema + } + }, + required: [ + "elements" + ], + additionalProperties: false + }, + ...null != name21 && { + name: name21 + }, + ...null != description && { + description + } + }; + }), + async parseCompleteOutput ({ text: text2 }, context2) { + 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: context2.response, + usage: context2.usage, + finishReason: context2.finishReason + }); + const outerValue = parseResult.value; + if (null == outerValue || "object" != typeof outerValue || !("elements" in outerValue) || !Array.isArray(outerValue.elements)) throw new NoObjectGeneratedError({ + message: "No object generated: response did not match schema.", + cause: new TypeValidationError({ + value: outerValue, + cause: "response must be an object with an elements array" + }), + text: text2, + response: context2.response, + usage: context2.usage, + finishReason: context2.finishReason + }); + for (const element of outerValue.elements){ + const validationResult = await safeValidateTypes({ + value: element, + schema: elementSchema + }); + if (!validationResult.success) throw new NoObjectGeneratedError({ + message: "No object generated: response did not match schema.", + cause: validationResult.error, + text: text2, + response: context2.response, + usage: context2.usage, + finishReason: context2.finishReason + }); + } + return outerValue.elements; + }, + async parsePartialOutput ({ text: text2 }) { + const result = await parsePartialJson(text2); + switch(result.state){ + case "failed-parse": + case "undefined-input": + return; + case "repaired-parse": + case "successful-parse": + { + const outerValue = result.value; + if (null == outerValue || "object" != typeof outerValue || !("elements" in outerValue) || !Array.isArray(outerValue.elements)) return; + const rawElements = "repaired-parse" === result.state && outerValue.elements.length > 0 ? outerValue.elements.slice(0, -1) : outerValue.elements; + const parsedElements = []; + for (const rawElement of rawElements){ + const validationResult = await safeValidateTypes({ + value: rawElement, + schema: elementSchema + }); + if (validationResult.success) parsedElements.push(validationResult.value); + } + return { + partial: parsedElements + }; + } + } + }, + createElementStreamTransform () { + let publishedElements = 0; + return new TransformStream({ + transform ({ partialOutput }, controller) { + if (null != partialOutput) for(; publishedElements < partialOutput.length; publishedElements++)controller.enqueue(partialOutput[publishedElements]); + } + }); + } + }; + }; + var dist_choice = ({ options: choiceOptions, name: name21, description })=>({ + name: "choice", + responseFormat: Promise.resolve({ + type: "json", + schema: { + $schema: "http://json-schema.org/draft-07/schema#", + type: "object", + properties: { + result: { + type: "string", + enum: choiceOptions + } + }, + required: [ + "result" + ], + additionalProperties: false + }, + ...null != name21 && { + name: name21 + }, + ...null != description && { + description + } + }), + async parseCompleteOutput ({ text: text2 }, context2) { + 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: context2.response, + usage: context2.usage, + finishReason: context2.finishReason + }); + const outerValue = parseResult.value; + if (null == outerValue || "object" != typeof outerValue || !("result" in outerValue) || "string" != typeof outerValue.result || !choiceOptions.includes(outerValue.result)) throw new NoObjectGeneratedError({ + message: "No object generated: response did not match schema.", + cause: new TypeValidationError({ + value: outerValue, + cause: "response must be an object that contains a choice value." + }), + text: text2, + response: context2.response, + usage: context2.usage, + finishReason: context2.finishReason + }); + return outerValue.result; + }, + async parsePartialOutput ({ text: text2 }) { + const result = await parsePartialJson(text2); + switch(result.state){ + case "failed-parse": + case "undefined-input": + return; + case "repaired-parse": + case "successful-parse": + { + const outerValue = result.value; + if (null == outerValue || "object" != typeof outerValue || !("result" in outerValue) || "string" != typeof outerValue.result) return; + const potentialMatches = choiceOptions.filter((choiceOption)=>choiceOption.startsWith(outerValue.result)); + if ("successful-parse" === result.state) return potentialMatches.includes(outerValue.result) ? { + partial: outerValue.result + } : void 0; + return 1 === potentialMatches.length ? { + partial: potentialMatches[0] + } : void 0; + } + } + }, + createElementStreamTransform () {} + }); + var dist_json = ({ name: name21, description } = {})=>({ + name: "json", + responseFormat: Promise.resolve({ + type: "json", + ...null != name21 && { + name: name21 + }, + ...null != description && { + description + } + }), + async parseCompleteOutput ({ text: text2 }, context2) { + 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: context2.response, + usage: context2.usage, + finishReason: context2.finishReason + }); + return parseResult.value; + }, + async parsePartialOutput ({ text: text2 }) { + const result = await parsePartialJson(text2); + switch(result.state){ + case "failed-parse": + case "undefined-input": + return; + case "repaired-parse": + case "successful-parse": + return void 0 === result.value ? void 0 : { + partial: result.value + }; + } + }, + createElementStreamTransform () {} + }); + async function parseToolCall({ toolCall, tools, repairToolCall, system, messages }) { + var _a21; + try { + if (null == tools) { + if (toolCall.providerExecuted && toolCall.dynamic) return await parseProviderExecutedDynamicToolCall(toolCall); + throw new NoSuchToolError({ + toolName: toolCall.toolName + }); + } + try { + return await doParseToolCall({ + toolCall, + tools + }); + } catch (error) { + if (null == repairToolCall || !(NoSuchToolError.isInstance(error) || InvalidToolInputError.isInstance(error))) throw error; + let repairedToolCall = null; + try { + repairedToolCall = await repairToolCall({ + toolCall, + tools, + inputSchema: async ({ toolName })=>{ + const { inputSchema } = tools[toolName]; + return await asSchema(inputSchema).jsonSchema; + }, + system, + messages, + error + }); + } catch (repairError) { + throw new ToolCallRepairError({ + cause: repairError, + originalError: error + }); + } + if (null == repairedToolCall) throw error; + return await doParseToolCall({ + toolCall: repairedToolCall, + tools + }); + } + } catch (error) { + const parsedInput = await safeParseJSON({ + text: toolCall.input + }); + const input = parsedInput.success ? parsedInput.value : toolCall.input; + return { + type: "tool-call", + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + input, + dynamic: true, + invalid: true, + error, + title: null == (_a21 = null == tools ? void 0 : tools[toolCall.toolName]) ? void 0 : _a21.title, + providerExecuted: toolCall.providerExecuted, + providerMetadata: toolCall.providerMetadata + }; + } + } + async function parseProviderExecutedDynamicToolCall(toolCall) { + const parseResult = "" === toolCall.input.trim() ? { + success: true, + value: {} + } : await safeParseJSON({ + text: toolCall.input + }); + if (false === parseResult.success) throw new InvalidToolInputError({ + toolName: toolCall.toolName, + toolInput: toolCall.input, + cause: parseResult.error + }); + return { + type: "tool-call", + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + input: parseResult.value, + providerExecuted: true, + dynamic: true, + providerMetadata: toolCall.providerMetadata + }; + } + async function doParseToolCall({ toolCall, tools }) { + const toolName = toolCall.toolName; + const tool2 = tools[toolName]; + if (null == tool2) { + if (toolCall.providerExecuted && toolCall.dynamic) return await parseProviderExecutedDynamicToolCall(toolCall); + throw new NoSuchToolError({ + toolName: toolCall.toolName, + availableTools: Object.keys(tools) + }); + } + const schema = asSchema(tool2.inputSchema); + const parseResult = "" === toolCall.input.trim() ? await safeValidateTypes({ + value: {}, + schema + }) : await safeParseJSON({ + text: toolCall.input, + schema + }); + if (false === parseResult.success) throw new InvalidToolInputError({ + toolName, + toolInput: toolCall.input, + cause: parseResult.error + }); + return "dynamic" === tool2.type ? { + type: "tool-call", + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + input: parseResult.value, + providerExecuted: toolCall.providerExecuted, + providerMetadata: toolCall.providerMetadata, + dynamic: true, + title: tool2.title + } : { + type: "tool-call", + toolCallId: toolCall.toolCallId, + toolName, + input: parseResult.value, + providerExecuted: toolCall.providerExecuted, + providerMetadata: toolCall.providerMetadata, + title: tool2.title + }; + } + var DefaultStepResult = class { + constructor({ stepNumber, model, functionId, metadata, experimental_context, content, finishReason, rawFinishReason, usage, warnings, request, response, providerMetadata }){ + this.stepNumber = stepNumber; + this.model = model; + this.functionId = functionId; + this.metadata = metadata; + this.experimental_context = experimental_context; + this.content = content; + this.finishReason = finishReason; + this.rawFinishReason = rawFinishReason; + this.usage = usage; + this.warnings = warnings; + this.request = request; + this.response = response; + this.providerMetadata = providerMetadata; + } + get text() { + return this.content.filter((part)=>"text" === part.type).map((part)=>part.text).join(""); + } + get reasoning() { + return this.content.filter((part)=>"reasoning" === part.type); + } + get reasoningText() { + return 0 === this.reasoning.length ? void 0 : this.reasoning.map((part)=>part.text).join(""); + } + get files() { + return this.content.filter((part)=>"file" === part.type).map((part)=>part.file); + } + get sources() { + return this.content.filter((part)=>"source" === part.type); + } + get toolCalls() { + return this.content.filter((part)=>"tool-call" === part.type); + } + get staticToolCalls() { + return this.toolCalls.filter((toolCall)=>true !== toolCall.dynamic); + } + get dynamicToolCalls() { + return this.toolCalls.filter((toolCall)=>true === toolCall.dynamic); + } + get toolResults() { + return this.content.filter((part)=>"tool-result" === part.type); + } + get staticToolResults() { + return this.toolResults.filter((toolResult)=>true !== toolResult.dynamic); + } + get dynamicToolResults() { + return this.toolResults.filter((toolResult)=>true === toolResult.dynamic); + } + }; + function stepCountIs(stepCount) { + return ({ steps })=>steps.length === stepCount; + } + async function isStopConditionMet({ stopConditions, steps }) { + return (await Promise.all(stopConditions.map((condition)=>condition({ + steps + })))).some((result)=>result); + } + async function toResponseMessages({ content: inputContent, tools }) { + const responseMessages = []; + const content = []; + for (const part of inputContent){ + if ("source" !== part.type) { + if ("tool-result" !== part.type && "tool-error" !== part.type || part.providerExecuted) { + if ("text" !== part.type || 0 !== part.text.length) switch(part.type){ + case "text": + content.push({ + type: "text", + text: part.text, + providerOptions: part.providerMetadata + }); + break; + case "reasoning": + content.push({ + type: "reasoning", + text: part.text, + providerOptions: part.providerMetadata + }); + break; + case "file": + content.push({ + type: "file", + data: part.file.base64, + mediaType: part.file.mediaType, + providerOptions: part.providerMetadata + }); + break; + case "tool-call": + content.push({ + type: "tool-call", + toolCallId: part.toolCallId, + toolName: part.toolName, + input: part.invalid && "object" != typeof part.input ? {} : part.input, + providerExecuted: part.providerExecuted, + providerOptions: part.providerMetadata + }); + break; + case "tool-result": + { + const output = await createToolModelOutput({ + toolCallId: part.toolCallId, + input: part.input, + tool: null == tools ? void 0 : tools[part.toolName], + output: part.output, + errorMode: "none" + }); + content.push({ + type: "tool-result", + toolCallId: part.toolCallId, + toolName: part.toolName, + output, + providerOptions: part.providerMetadata + }); + break; + } + case "tool-error": + { + const output = await createToolModelOutput({ + toolCallId: part.toolCallId, + input: part.input, + tool: null == tools ? void 0 : tools[part.toolName], + output: part.error, + errorMode: "json" + }); + content.push({ + type: "tool-result", + toolCallId: part.toolCallId, + toolName: part.toolName, + output, + providerOptions: part.providerMetadata + }); + break; + } + case "tool-approval-request": + content.push({ + type: "tool-approval-request", + approvalId: part.approvalId, + toolCallId: part.toolCall.toolCallId + }); + break; + } + } + } + } + if (content.length > 0) responseMessages.push({ + role: "assistant", + content + }); + const toolResultContent = []; + for (const part of inputContent){ + if (!("tool-result" === part.type || "tool-error" === part.type) || part.providerExecuted) continue; + const output = await createToolModelOutput({ + toolCallId: part.toolCallId, + input: part.input, + tool: null == tools ? void 0 : tools[part.toolName], + output: "tool-result" === part.type ? part.output : part.error, + errorMode: "tool-error" === part.type ? "text" : "none" + }); + toolResultContent.push({ + type: "tool-result", + toolCallId: part.toolCallId, + toolName: part.toolName, + output, + ...null != part.providerMetadata ? { + providerOptions: part.providerMetadata + } : {} + }); + } + if (toolResultContent.length > 0) responseMessages.push({ + role: "tool", + content: toolResultContent + }); + return responseMessages; + } + function mergeAbortSignals(...signals) { + const validSignals = signals.filter((signal)=>null != signal); + if (0 === validSignals.length) return; + if (1 === validSignals.length) return validSignals[0]; + const controller = new AbortController(); + for (const signal of validSignals){ + if (signal.aborted) { + controller.abort(signal.reason); + break; + } + signal.addEventListener("abort", ()=>{ + controller.abort(signal.reason); + }, { + once: true + }); + } + return controller.signal; + } + var originalGenerateId = createIdGenerator({ + prefix: "aitxt", + size: 24 + }); + async function generateText({ model: modelArg, tools, toolChoice, system, prompt, messages, maxRetries: maxRetriesArg, abortSignal, timeout, headers, stopWhen = stepCountIs(1), experimental_output, output = experimental_output, experimental_telemetry: telemetry, providerOptions, experimental_activeTools, activeTools = experimental_activeTools, experimental_prepareStep, prepareStep = experimental_prepareStep, experimental_repairToolCall: repairToolCall, experimental_download: download2, experimental_context, experimental_include: include, _internal: { generateId: generateId2 = originalGenerateId } = {}, experimental_onStart: onStart, experimental_onStepStart: onStepStart, experimental_onToolCallStart: onToolCallStart, experimental_onToolCallFinish: onToolCallFinish, onStepFinish, onFinish, ...settings }) { + const model = resolveLanguageModel(modelArg); + const createGlobalTelemetry = getGlobalTelemetryIntegration(); + const stopConditions = asArray(stopWhen); + const totalTimeoutMs = getTotalTimeoutMs(timeout); + const stepTimeoutMs = getStepTimeoutMs(timeout); + const stepAbortController = null != stepTimeoutMs ? new AbortController() : void 0; + const mergedAbortSignal = mergeAbortSignals(abortSignal, null != totalTimeoutMs ? AbortSignal.timeout(totalTimeoutMs) : void 0, null == stepAbortController ? void 0 : stepAbortController.signal); + const { maxRetries, retry } = prepareRetries({ + maxRetries: maxRetriesArg, + abortSignal: mergedAbortSignal + }); + const callSettings = prepareCallSettings(settings); + const headersWithUserAgent = withUserAgentSuffix(null != headers ? headers : {}, `ai/${ai_dist_VERSION}`); + const baseTelemetryAttributes = getBaseTelemetryAttributes({ + model, + telemetry, + headers: headersWithUserAgent, + settings: { + ...callSettings, + maxRetries + } + }); + const modelInfo = { + provider: model.provider, + modelId: model.modelId + }; + const initialPrompt = await standardizePrompt({ + system, + prompt, + messages + }); + const globalTelemetry = createGlobalTelemetry(null == telemetry ? void 0 : telemetry.integrations); + await notify({ + event: { + model: modelInfo, + system, + prompt, + messages, + tools, + toolChoice, + activeTools, + maxOutputTokens: callSettings.maxOutputTokens, + temperature: callSettings.temperature, + topP: callSettings.topP, + topK: callSettings.topK, + presencePenalty: callSettings.presencePenalty, + frequencyPenalty: callSettings.frequencyPenalty, + stopSequences: callSettings.stopSequences, + seed: callSettings.seed, + maxRetries, + timeout, + headers, + providerOptions, + stopWhen, + output, + abortSignal, + include, + functionId: null == telemetry ? void 0 : telemetry.functionId, + metadata: null == telemetry ? void 0 : telemetry.metadata, + experimental_context + }, + callbacks: [ + onStart, + globalTelemetry.onStart + ] + }); + const tracer = getTracer(telemetry); + try { + return await recordSpan({ + name: "ai.generateText", + attributes: selectTelemetryAttributes({ + telemetry, + attributes: { + ...assembleOperationName({ + operationId: "ai.generateText", + telemetry + }), + ...baseTelemetryAttributes, + "ai.model.provider": model.provider, + "ai.model.id": model.modelId, + "ai.prompt": { + input: ()=>JSON.stringify({ + system, + prompt, + messages + }) + } + } + }), + tracer, + fn: async (span)=>{ + var _a21, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t; + const initialMessages = initialPrompt.messages; + const responseMessages = []; + const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ + messages: initialMessages + }); + const localApprovedToolApprovals = approvedToolApprovals.filter((toolApproval)=>!toolApproval.toolCall.providerExecuted); + if (deniedToolApprovals.length > 0 || localApprovedToolApprovals.length > 0) { + const toolOutputs = await executeTools({ + toolCalls: localApprovedToolApprovals.map((toolApproval)=>toolApproval.toolCall), + tools, + tracer, + telemetry, + messages: initialMessages, + abortSignal: mergedAbortSignal, + experimental_context, + stepNumber: 0, + model: modelInfo, + onToolCallStart: [ + onToolCallStart, + globalTelemetry.onToolCallStart + ], + onToolCallFinish: [ + onToolCallFinish, + globalTelemetry.onToolCallFinish + ] + }); + const toolContent = []; + for (const output2 of toolOutputs){ + const modelOutput = await createToolModelOutput({ + toolCallId: output2.toolCallId, + input: output2.input, + tool: null == tools ? void 0 : tools[output2.toolName], + output: "tool-result" === output2.type ? output2.output : output2.error, + errorMode: "tool-error" === output2.type ? "text" : "none" + }); + toolContent.push({ + type: "tool-result", + toolCallId: output2.toolCallId, + toolName: output2.toolName, + output: modelOutput + }); + } + for (const toolApproval of deniedToolApprovals)toolContent.push({ + type: "tool-result", + toolCallId: toolApproval.toolCall.toolCallId, + toolName: toolApproval.toolCall.toolName, + output: { + type: "execution-denied", + reason: toolApproval.approvalResponse.reason, + ...toolApproval.toolCall.providerExecuted && { + providerOptions: { + openai: { + approvalId: toolApproval.approvalResponse.approvalId + } + } + } + } + }); + responseMessages.push({ + role: "tool", + content: toolContent + }); + } + const callSettings2 = prepareCallSettings(settings); + let currentModelResponse; + let clientToolCalls = []; + let clientToolOutputs = []; + const steps = []; + const pendingDeferredToolCalls = /* @__PURE__ */ new Map(); + do { + const stepTimeoutId = null != stepTimeoutMs ? setTimeout(()=>stepAbortController.abort(), stepTimeoutMs) : void 0; + try { + const stepInputMessages = [ + ...initialMessages, + ...responseMessages + ]; + const prepareStepResult = await (null == prepareStep ? void 0 : prepareStep({ + model, + steps, + stepNumber: steps.length, + messages: stepInputMessages, + experimental_context + })); + const stepModel = resolveLanguageModel(null != (_a21 = null == prepareStepResult ? void 0 : prepareStepResult.model) ? _a21 : model); + const stepModelInfo = { + provider: stepModel.provider, + modelId: stepModel.modelId + }; + const promptMessages = await convertToLanguageModelPrompt({ + prompt: { + system: null != (_b = null == prepareStepResult ? void 0 : prepareStepResult.system) ? _b : initialPrompt.system, + messages: null != (_c = null == prepareStepResult ? void 0 : prepareStepResult.messages) ? _c : stepInputMessages + }, + supportedUrls: await stepModel.supportedUrls, + download: download2 + }); + experimental_context = null != (_d = null == prepareStepResult ? void 0 : prepareStepResult.experimental_context) ? _d : experimental_context; + const stepActiveTools = null != (_e = null == prepareStepResult ? void 0 : prepareStepResult.activeTools) ? _e : activeTools; + const { toolChoice: stepToolChoice, tools: stepTools } = await prepareToolsAndToolChoice({ + tools, + toolChoice: null != (_f = null == prepareStepResult ? void 0 : prepareStepResult.toolChoice) ? _f : toolChoice, + activeTools: stepActiveTools + }); + const stepMessages = null != (_g = null == prepareStepResult ? void 0 : prepareStepResult.messages) ? _g : stepInputMessages; + const stepSystem = null != (_h = null == prepareStepResult ? void 0 : prepareStepResult.system) ? _h : initialPrompt.system; + const stepProviderOptions = mergeObjects(providerOptions, null == prepareStepResult ? void 0 : prepareStepResult.providerOptions); + await notify({ + event: { + stepNumber: steps.length, + model: stepModelInfo, + system: stepSystem, + messages: stepMessages, + tools, + toolChoice: stepToolChoice, + activeTools: stepActiveTools, + steps: [ + ...steps + ], + providerOptions: stepProviderOptions, + timeout, + headers, + stopWhen, + output, + abortSignal, + include, + functionId: null == telemetry ? void 0 : telemetry.functionId, + metadata: null == telemetry ? void 0 : telemetry.metadata, + experimental_context + }, + callbacks: [ + onStepStart, + globalTelemetry.onStepStart + ] + }); + currentModelResponse = await retry(()=>{ + var _a22; + return recordSpan({ + name: "ai.generateText.doGenerate", + attributes: selectTelemetryAttributes({ + telemetry, + attributes: { + ...assembleOperationName({ + operationId: "ai.generateText.doGenerate", + telemetry + }), + ...baseTelemetryAttributes, + "ai.model.provider": stepModel.provider, + "ai.model.id": stepModel.modelId, + "ai.prompt.messages": { + input: ()=>stringifyForTelemetry(promptMessages) + }, + "ai.prompt.tools": { + input: ()=>null == stepTools ? void 0 : stepTools.map((tool2)=>JSON.stringify(tool2)) + }, + "ai.prompt.toolChoice": { + input: ()=>null != stepToolChoice ? JSON.stringify(stepToolChoice) : void 0 + }, + "gen_ai.system": stepModel.provider, + "gen_ai.request.model": stepModel.modelId, + "gen_ai.request.frequency_penalty": settings.frequencyPenalty, + "gen_ai.request.max_tokens": settings.maxOutputTokens, + "gen_ai.request.presence_penalty": settings.presencePenalty, + "gen_ai.request.stop_sequences": settings.stopSequences, + "gen_ai.request.temperature": null != (_a22 = settings.temperature) ? _a22 : void 0, + "gen_ai.request.top_k": settings.topK, + "gen_ai.request.top_p": settings.topP + } + }), + tracer, + fn: async (span2)=>{ + var _a23, _b2, _c2, _d2, _e2, _f2, _g2, _h2; + const result = await stepModel.doGenerate({ + ...callSettings2, + tools: stepTools, + toolChoice: stepToolChoice, + responseFormat: await (null == output ? void 0 : output.responseFormat), + prompt: promptMessages, + providerOptions: stepProviderOptions, + abortSignal: mergedAbortSignal, + headers: headersWithUserAgent + }); + const responseData = { + id: null != (_b2 = null == (_a23 = result.response) ? void 0 : _a23.id) ? _b2 : generateId2(), + timestamp: null != (_d2 = null == (_c2 = result.response) ? void 0 : _c2.timestamp) ? _d2 : /* @__PURE__ */ new Date(), + modelId: null != (_f2 = null == (_e2 = result.response) ? void 0 : _e2.modelId) ? _f2 : stepModel.modelId, + headers: null == (_g2 = result.response) ? void 0 : _g2.headers, + body: null == (_h2 = result.response) ? void 0 : _h2.body + }; + const usage = asLanguageModelUsage(result.usage); + span2.setAttributes(await selectTelemetryAttributes({ + telemetry, + attributes: { + "ai.response.finishReason": result.finishReason.unified, + "ai.response.text": { + output: ()=>extractTextContent(result.content) + }, + "ai.response.reasoning": { + output: ()=>extractReasoningContent(result.content) + }, + "ai.response.toolCalls": { + output: ()=>{ + const toolCalls = asToolCalls(result.content); + return null == toolCalls ? void 0 : JSON.stringify(toolCalls); + } + }, + "ai.response.id": responseData.id, + "ai.response.model": responseData.modelId, + "ai.response.timestamp": responseData.timestamp.toISOString(), + "ai.response.providerMetadata": JSON.stringify(result.providerMetadata), + "ai.usage.inputTokens": result.usage.inputTokens.total, + "ai.usage.inputTokenDetails.noCacheTokens": result.usage.inputTokens.noCache, + "ai.usage.inputTokenDetails.cacheReadTokens": result.usage.inputTokens.cacheRead, + "ai.usage.inputTokenDetails.cacheWriteTokens": result.usage.inputTokens.cacheWrite, + "ai.usage.outputTokens": result.usage.outputTokens.total, + "ai.usage.outputTokenDetails.textTokens": result.usage.outputTokens.text, + "ai.usage.outputTokenDetails.reasoningTokens": result.usage.outputTokens.reasoning, + "ai.usage.totalTokens": usage.totalTokens, + "ai.usage.reasoningTokens": result.usage.outputTokens.reasoning, + "ai.usage.cachedInputTokens": result.usage.inputTokens.cacheRead, + "gen_ai.response.finish_reasons": [ + result.finishReason.unified + ], + "gen_ai.response.id": responseData.id, + "gen_ai.response.model": responseData.modelId, + "gen_ai.usage.input_tokens": result.usage.inputTokens.total, + "gen_ai.usage.output_tokens": result.usage.outputTokens.total + } + })); + return { + ...result, + response: responseData + }; + } + }); + }); + const stepToolCalls = await Promise.all(currentModelResponse.content.filter((part)=>"tool-call" === part.type).map((toolCall)=>parseToolCall({ + toolCall, + tools, + repairToolCall, + system, + messages: stepInputMessages + }))); + const toolApprovalRequests = {}; + for (const toolCall of stepToolCalls){ + if (toolCall.invalid) continue; + const tool2 = null == tools ? void 0 : tools[toolCall.toolName]; + if (null != tool2) { + if ((null == tool2 ? void 0 : tool2.onInputAvailable) != null) await tool2.onInputAvailable({ + input: toolCall.input, + toolCallId: toolCall.toolCallId, + messages: stepInputMessages, + abortSignal: mergedAbortSignal, + experimental_context + }); + if (await isApprovalNeeded({ + tool: tool2, + toolCall, + messages: stepInputMessages, + experimental_context + })) toolApprovalRequests[toolCall.toolCallId] = { + type: "tool-approval-request", + approvalId: generateId2(), + toolCall + }; + } + } + const invalidToolCalls = stepToolCalls.filter((toolCall)=>toolCall.invalid && toolCall.dynamic); + clientToolOutputs = []; + for (const toolCall of invalidToolCalls)clientToolOutputs.push({ + type: "tool-error", + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + input: toolCall.input, + error: dist_getErrorMessage(toolCall.error), + dynamic: true + }); + clientToolCalls = stepToolCalls.filter((toolCall)=>!toolCall.providerExecuted); + if (null != tools) clientToolOutputs.push(...await executeTools({ + toolCalls: clientToolCalls.filter((toolCall)=>!toolCall.invalid && null == toolApprovalRequests[toolCall.toolCallId]), + tools, + tracer, + telemetry, + messages: stepInputMessages, + abortSignal: mergedAbortSignal, + experimental_context, + stepNumber: steps.length, + model: stepModelInfo, + onToolCallStart: [ + onToolCallStart, + globalTelemetry.onToolCallStart + ], + onToolCallFinish: [ + onToolCallFinish, + globalTelemetry.onToolCallFinish + ] + })); + for (const toolCall of stepToolCalls){ + if (!toolCall.providerExecuted) continue; + const tool2 = null == tools ? void 0 : tools[toolCall.toolName]; + if ((null == tool2 ? void 0 : tool2.type) === "provider" && tool2.supportsDeferredResults) { + const hasResultInResponse = currentModelResponse.content.some((part)=>"tool-result" === part.type && part.toolCallId === toolCall.toolCallId); + if (!hasResultInResponse) pendingDeferredToolCalls.set(toolCall.toolCallId, { + toolName: toolCall.toolName + }); + } + } + for (const part of currentModelResponse.content)if ("tool-result" === part.type) pendingDeferredToolCalls.delete(part.toolCallId); + const stepContent = asContent({ + content: currentModelResponse.content, + toolCalls: stepToolCalls, + toolOutputs: clientToolOutputs, + toolApprovalRequests: Object.values(toolApprovalRequests), + tools + }); + responseMessages.push(...await toResponseMessages({ + content: stepContent, + tools + })); + const stepRequest = (null != (_i = null == include ? void 0 : include.requestBody) ? _i : true) ? null != (_j = currentModelResponse.request) ? _j : {} : { + ...currentModelResponse.request, + body: void 0 + }; + const stepResponse = { + ...currentModelResponse.response, + messages: structuredClone(responseMessages), + body: (null != (_k = null == include ? void 0 : include.responseBody) ? _k : true) ? null == (_l = currentModelResponse.response) ? void 0 : _l.body : void 0 + }; + const stepNumber = steps.length; + const currentStepResult = new DefaultStepResult({ + stepNumber, + model: stepModelInfo, + functionId: null == telemetry ? void 0 : telemetry.functionId, + metadata: null == telemetry ? void 0 : telemetry.metadata, + experimental_context, + content: stepContent, + finishReason: currentModelResponse.finishReason.unified, + rawFinishReason: currentModelResponse.finishReason.raw, + usage: asLanguageModelUsage(currentModelResponse.usage), + warnings: currentModelResponse.warnings, + providerMetadata: currentModelResponse.providerMetadata, + request: stepRequest, + response: stepResponse + }); + logWarnings({ + warnings: null != (_m = currentModelResponse.warnings) ? _m : [], + provider: stepModelInfo.provider, + model: stepModelInfo.modelId + }); + steps.push(currentStepResult); + await notify({ + event: currentStepResult, + callbacks: [ + onStepFinish, + globalTelemetry.onStepFinish + ] + }); + } finally{ + if (null != stepTimeoutId) clearTimeout(stepTimeoutId); + } + }while ((clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length || pendingDeferredToolCalls.size > 0) && !await isStopConditionMet({ + stopConditions, + steps + })); + span.setAttributes(await selectTelemetryAttributes({ + telemetry, + attributes: { + "ai.response.finishReason": currentModelResponse.finishReason.unified, + "ai.response.text": { + output: ()=>extractTextContent(currentModelResponse.content) + }, + "ai.response.reasoning": { + output: ()=>extractReasoningContent(currentModelResponse.content) + }, + "ai.response.toolCalls": { + output: ()=>{ + const toolCalls = asToolCalls(currentModelResponse.content); + return null == toolCalls ? void 0 : JSON.stringify(toolCalls); + } + }, + "ai.response.providerMetadata": JSON.stringify(currentModelResponse.providerMetadata) + } + })); + const lastStep = steps[steps.length - 1]; + const totalUsage = steps.reduce((totalUsage2, step)=>addLanguageModelUsage(totalUsage2, step.usage), { + inputTokens: void 0, + outputTokens: void 0, + totalTokens: void 0, + reasoningTokens: void 0, + cachedInputTokens: void 0 + }); + span.setAttributes(await selectTelemetryAttributes({ + telemetry, + attributes: { + "ai.usage.inputTokens": totalUsage.inputTokens, + "ai.usage.inputTokenDetails.noCacheTokens": null == (_n = totalUsage.inputTokenDetails) ? void 0 : _n.noCacheTokens, + "ai.usage.inputTokenDetails.cacheReadTokens": null == (_o = totalUsage.inputTokenDetails) ? void 0 : _o.cacheReadTokens, + "ai.usage.inputTokenDetails.cacheWriteTokens": null == (_p = totalUsage.inputTokenDetails) ? void 0 : _p.cacheWriteTokens, + "ai.usage.outputTokens": totalUsage.outputTokens, + "ai.usage.outputTokenDetails.textTokens": null == (_q = totalUsage.outputTokenDetails) ? void 0 : _q.textTokens, + "ai.usage.outputTokenDetails.reasoningTokens": null == (_r = totalUsage.outputTokenDetails) ? void 0 : _r.reasoningTokens, + "ai.usage.totalTokens": totalUsage.totalTokens, + "ai.usage.reasoningTokens": null == (_s = totalUsage.outputTokenDetails) ? void 0 : _s.reasoningTokens, + "ai.usage.cachedInputTokens": null == (_t = totalUsage.inputTokenDetails) ? void 0 : _t.cacheReadTokens + } + })); + await notify({ + event: { + stepNumber: lastStep.stepNumber, + model: lastStep.model, + functionId: lastStep.functionId, + metadata: lastStep.metadata, + experimental_context: lastStep.experimental_context, + finishReason: lastStep.finishReason, + rawFinishReason: lastStep.rawFinishReason, + usage: lastStep.usage, + content: lastStep.content, + text: lastStep.text, + reasoningText: lastStep.reasoningText, + reasoning: lastStep.reasoning, + files: lastStep.files, + sources: lastStep.sources, + toolCalls: lastStep.toolCalls, + staticToolCalls: lastStep.staticToolCalls, + dynamicToolCalls: lastStep.dynamicToolCalls, + toolResults: lastStep.toolResults, + staticToolResults: lastStep.staticToolResults, + dynamicToolResults: lastStep.dynamicToolResults, + request: lastStep.request, + response: lastStep.response, + warnings: lastStep.warnings, + providerMetadata: lastStep.providerMetadata, + steps, + totalUsage + }, + callbacks: [ + onFinish, + globalTelemetry.onFinish + ] + }); + let resolvedOutput; + if ("stop" === lastStep.finishReason) { + const outputSpecification = null != output ? output : dist_text(); + resolvedOutput = await outputSpecification.parseCompleteOutput({ + text: lastStep.text + }, { + response: lastStep.response, + usage: lastStep.usage, + finishReason: lastStep.finishReason + }); + } + return new DefaultGenerateTextResult({ + steps, + totalUsage, + output: resolvedOutput + }); + } + }); + } catch (error) { + throw wrapGatewayError(error); + } + } + async function executeTools({ toolCalls, tools, tracer, telemetry, messages, abortSignal, experimental_context, stepNumber, model, onToolCallStart, onToolCallFinish }) { + const toolOutputs = await Promise.all(toolCalls.map(async (toolCall)=>executeToolCall({ + toolCall, + tools, + tracer, + telemetry, + messages, + abortSignal, + experimental_context, + stepNumber, + model, + onToolCallStart, + onToolCallFinish + }))); + return toolOutputs.filter((output)=>null != output); + } + var DefaultGenerateTextResult = class { + constructor(options1){ + this.steps = options1.steps; + this._output = options1.output; + this.totalUsage = options1.totalUsage; + } + get finalStep() { + return this.steps[this.steps.length - 1]; + } + get content() { + return this.finalStep.content; + } + get text() { + return this.finalStep.text; + } + get files() { + return this.finalStep.files; + } + get reasoningText() { + return this.finalStep.reasoningText; + } + get reasoning() { + return this.finalStep.reasoning; + } + get toolCalls() { + return this.finalStep.toolCalls; + } + get staticToolCalls() { + return this.finalStep.staticToolCalls; + } + get dynamicToolCalls() { + return this.finalStep.dynamicToolCalls; + } + get toolResults() { + return this.finalStep.toolResults; + } + get staticToolResults() { + return this.finalStep.staticToolResults; + } + get dynamicToolResults() { + return this.finalStep.dynamicToolResults; + } + get sources() { + return this.finalStep.sources; + } + get finishReason() { + return this.finalStep.finishReason; + } + get rawFinishReason() { + return this.finalStep.rawFinishReason; + } + get warnings() { + return this.finalStep.warnings; + } + get providerMetadata() { + return this.finalStep.providerMetadata; + } + get response() { + return this.finalStep.response; + } + get request() { + return this.finalStep.request; + } + get usage() { + return this.finalStep.usage; + } + get experimental_output() { + return this.output; + } + get output() { + if (null == this._output) throw new NoOutputGeneratedError(); + return this._output; + } + }; + function asToolCalls(content) { + const parts = content.filter((part)=>"tool-call" === part.type); + if (0 === parts.length) return; + return parts.map((toolCall)=>({ + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + input: toolCall.input + })); + } + function asContent({ content, toolCalls, toolOutputs, toolApprovalRequests, tools }) { + const contentParts = []; + for (const part of content)switch(part.type){ + case "text": + case "reasoning": + case "source": + contentParts.push(part); + break; + case "file": + contentParts.push({ + type: "file", + file: new DefaultGeneratedFile(part), + ...null != part.providerMetadata ? { + providerMetadata: part.providerMetadata + } : {} + }); + break; + case "tool-call": + contentParts.push(toolCalls.find((toolCall)=>toolCall.toolCallId === part.toolCallId)); + break; + case "tool-result": + { + const toolCall = toolCalls.find((toolCall2)=>toolCall2.toolCallId === part.toolCallId); + if (null == toolCall) { + const tool2 = null == tools ? void 0 : tools[part.toolName]; + const supportsDeferredResults = (null == tool2 ? void 0 : tool2.type) === "provider" && tool2.supportsDeferredResults; + if (!supportsDeferredResults) throw new Error(`Tool call ${part.toolCallId} not found.`); + if (part.isError) contentParts.push({ + type: "tool-error", + toolCallId: part.toolCallId, + toolName: part.toolName, + input: void 0, + error: part.result, + providerExecuted: true, + dynamic: part.dynamic, + ...null != part.providerMetadata ? { + providerMetadata: part.providerMetadata + } : {} + }); + else contentParts.push({ + type: "tool-result", + toolCallId: part.toolCallId, + toolName: part.toolName, + input: void 0, + output: part.result, + providerExecuted: true, + dynamic: part.dynamic, + ...null != part.providerMetadata ? { + providerMetadata: part.providerMetadata + } : {} + }); + break; + } + if (part.isError) contentParts.push({ + type: "tool-error", + toolCallId: part.toolCallId, + toolName: part.toolName, + input: toolCall.input, + error: part.result, + providerExecuted: true, + dynamic: toolCall.dynamic, + ...null != part.providerMetadata ? { + providerMetadata: part.providerMetadata + } : {} + }); + else contentParts.push({ + type: "tool-result", + toolCallId: part.toolCallId, + toolName: part.toolName, + input: toolCall.input, + output: part.result, + providerExecuted: true, + dynamic: toolCall.dynamic, + ...null != part.providerMetadata ? { + providerMetadata: part.providerMetadata + } : {} + }); + break; + } + case "tool-approval-request": + { + const toolCall = toolCalls.find((toolCall2)=>toolCall2.toolCallId === part.toolCallId); + if (null == toolCall) throw new ToolCallNotFoundForApprovalError({ + toolCallId: part.toolCallId, + approvalId: part.approvalId + }); + contentParts.push({ + type: "tool-approval-request", + approvalId: part.approvalId, + toolCall + }); + break; + } + } + return [ + ...contentParts, + ...toolOutputs, + ...toolApprovalRequests + ]; + } + dist_lazySchema(()=>dist_zodSchema(union([ + strictObject({ + type: schemas_literal("text-start"), + id: schemas_string(), + providerMetadata: providerMetadataSchema.optional() + }), + strictObject({ + type: schemas_literal("text-delta"), + id: schemas_string(), + delta: schemas_string(), + providerMetadata: providerMetadataSchema.optional() + }), + strictObject({ + type: schemas_literal("text-end"), + id: schemas_string(), + providerMetadata: providerMetadataSchema.optional() + }), + strictObject({ + type: schemas_literal("error"), + errorText: schemas_string() + }), + strictObject({ + type: schemas_literal("tool-input-start"), + toolCallId: schemas_string(), + toolName: schemas_string(), + providerExecuted: schemas_boolean().optional(), + providerMetadata: providerMetadataSchema.optional(), + dynamic: schemas_boolean().optional(), + title: schemas_string().optional() + }), + strictObject({ + type: schemas_literal("tool-input-delta"), + toolCallId: schemas_string(), + inputTextDelta: schemas_string() + }), + strictObject({ + type: schemas_literal("tool-input-available"), + toolCallId: schemas_string(), + toolName: schemas_string(), + input: unknown(), + providerExecuted: schemas_boolean().optional(), + providerMetadata: providerMetadataSchema.optional(), + dynamic: schemas_boolean().optional(), + title: schemas_string().optional() + }), + strictObject({ + type: schemas_literal("tool-input-error"), + toolCallId: schemas_string(), + toolName: schemas_string(), + input: unknown(), + providerExecuted: schemas_boolean().optional(), + providerMetadata: providerMetadataSchema.optional(), + dynamic: schemas_boolean().optional(), + errorText: schemas_string(), + title: schemas_string().optional() + }), + strictObject({ + type: schemas_literal("tool-approval-request"), + approvalId: schemas_string(), + toolCallId: schemas_string() + }), + strictObject({ + type: schemas_literal("tool-output-available"), + toolCallId: schemas_string(), + output: unknown(), + providerExecuted: schemas_boolean().optional(), + providerMetadata: providerMetadataSchema.optional(), + dynamic: schemas_boolean().optional(), + preliminary: schemas_boolean().optional() + }), + strictObject({ + type: schemas_literal("tool-output-error"), + toolCallId: schemas_string(), + errorText: schemas_string(), + providerExecuted: schemas_boolean().optional(), + providerMetadata: providerMetadataSchema.optional(), + dynamic: schemas_boolean().optional() + }), + strictObject({ + type: schemas_literal("tool-output-denied"), + toolCallId: schemas_string() + }), + strictObject({ + type: schemas_literal("reasoning-start"), + id: schemas_string(), + providerMetadata: providerMetadataSchema.optional() + }), + strictObject({ + type: schemas_literal("reasoning-delta"), + id: schemas_string(), + delta: schemas_string(), + providerMetadata: providerMetadataSchema.optional() + }), + strictObject({ + type: schemas_literal("reasoning-end"), + id: schemas_string(), + providerMetadata: providerMetadataSchema.optional() + }), + strictObject({ + type: schemas_literal("source-url"), + sourceId: schemas_string(), + url: schemas_string(), + title: schemas_string().optional(), + providerMetadata: providerMetadataSchema.optional() + }), + strictObject({ + type: schemas_literal("source-document"), + sourceId: schemas_string(), + mediaType: schemas_string(), + title: schemas_string(), + filename: schemas_string().optional(), + providerMetadata: providerMetadataSchema.optional() + }), + strictObject({ + type: schemas_literal("file"), + url: schemas_string(), + mediaType: schemas_string(), + providerMetadata: providerMetadataSchema.optional() + }), + strictObject({ + type: custom((value1)=>"string" == typeof value1 && value1.startsWith("data-"), { + message: 'Type must start with "data-"' + }), + id: schemas_string().optional(), + data: unknown(), + transient: schemas_boolean().optional() + }), + strictObject({ + type: schemas_literal("start-step") + }), + strictObject({ + type: schemas_literal("finish-step") + }), + strictObject({ + type: schemas_literal("start"), + messageId: schemas_string().optional(), + messageMetadata: unknown().optional() + }), + strictObject({ + type: schemas_literal("finish"), + finishReason: schemas_enum([ + "stop", + "length", + "content-filter", + "tool-calls", + "error", + "other" + ]).optional(), + messageMetadata: unknown().optional() + }), + strictObject({ + type: schemas_literal("abort"), + reason: schemas_string().optional() + }), + strictObject({ + type: schemas_literal("message-metadata"), + messageMetadata: unknown() + }) + ]))); + createIdGenerator({ + prefix: "aitxt", + size: 24 + }); + dist_lazySchema(()=>dist_zodSchema(schemas_array(schemas_object({ + id: schemas_string(), + role: schemas_enum([ + "system", + "user", + "assistant" + ]), + metadata: unknown().optional(), + parts: schemas_array(union([ + schemas_object({ + type: schemas_literal("text"), + text: schemas_string(), + state: schemas_enum([ + "streaming", + "done" + ]).optional(), + providerMetadata: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("reasoning"), + text: schemas_string(), + state: schemas_enum([ + "streaming", + "done" + ]).optional(), + providerMetadata: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("source-url"), + sourceId: schemas_string(), + url: schemas_string(), + title: schemas_string().optional(), + providerMetadata: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("source-document"), + sourceId: schemas_string(), + mediaType: schemas_string(), + title: schemas_string(), + filename: schemas_string().optional(), + providerMetadata: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("file"), + mediaType: schemas_string(), + filename: schemas_string().optional(), + url: schemas_string(), + providerMetadata: providerMetadataSchema.optional() + }), + schemas_object({ + type: schemas_literal("step-start") + }), + schemas_object({ + type: schemas_string().startsWith("data-"), + id: schemas_string().optional(), + data: unknown() + }), + schemas_object({ + type: schemas_literal("dynamic-tool"), + toolName: schemas_string(), + toolCallId: schemas_string(), + state: schemas_literal("input-streaming"), + input: unknown().optional(), + providerExecuted: schemas_boolean().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + output: never().optional(), + errorText: never().optional(), + approval: never().optional() + }), + schemas_object({ + type: schemas_literal("dynamic-tool"), + toolName: schemas_string(), + toolCallId: schemas_string(), + state: schemas_literal("input-available"), + input: unknown(), + providerExecuted: schemas_boolean().optional(), + output: never().optional(), + errorText: never().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + approval: never().optional() + }), + schemas_object({ + type: schemas_literal("dynamic-tool"), + toolName: schemas_string(), + toolCallId: schemas_string(), + state: schemas_literal("approval-requested"), + input: unknown(), + providerExecuted: schemas_boolean().optional(), + output: never().optional(), + errorText: never().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + approval: schemas_object({ + id: schemas_string(), + approved: never().optional(), + reason: never().optional() + }) + }), + schemas_object({ + type: schemas_literal("dynamic-tool"), + toolName: schemas_string(), + toolCallId: schemas_string(), + state: schemas_literal("approval-responded"), + input: unknown(), + providerExecuted: schemas_boolean().optional(), + output: never().optional(), + errorText: never().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + approval: schemas_object({ + id: schemas_string(), + approved: schemas_boolean(), + reason: schemas_string().optional() + }) + }), + schemas_object({ + type: schemas_literal("dynamic-tool"), + toolName: schemas_string(), + toolCallId: schemas_string(), + state: schemas_literal("output-available"), + input: unknown(), + providerExecuted: schemas_boolean().optional(), + output: unknown(), + errorText: never().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + resultProviderMetadata: providerMetadataSchema.optional(), + preliminary: schemas_boolean().optional(), + approval: schemas_object({ + id: schemas_string(), + approved: schemas_literal(true), + reason: schemas_string().optional() + }).optional() + }), + schemas_object({ + type: schemas_literal("dynamic-tool"), + toolName: schemas_string(), + toolCallId: schemas_string(), + state: schemas_literal("output-error"), + input: unknown(), + rawInput: unknown().optional(), + providerExecuted: schemas_boolean().optional(), + output: never().optional(), + errorText: schemas_string(), + callProviderMetadata: providerMetadataSchema.optional(), + resultProviderMetadata: providerMetadataSchema.optional(), + approval: schemas_object({ + id: schemas_string(), + approved: schemas_literal(true), + reason: schemas_string().optional() + }).optional() + }), + schemas_object({ + type: schemas_literal("dynamic-tool"), + toolName: schemas_string(), + toolCallId: schemas_string(), + state: schemas_literal("output-denied"), + input: unknown(), + providerExecuted: schemas_boolean().optional(), + output: never().optional(), + errorText: never().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + approval: schemas_object({ + id: schemas_string(), + approved: schemas_literal(false), + reason: schemas_string().optional() + }) + }), + schemas_object({ + type: schemas_string().startsWith("tool-"), + toolCallId: schemas_string(), + state: schemas_literal("input-streaming"), + providerExecuted: schemas_boolean().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + input: unknown().optional(), + output: never().optional(), + errorText: never().optional(), + approval: never().optional() + }), + schemas_object({ + type: schemas_string().startsWith("tool-"), + toolCallId: schemas_string(), + state: schemas_literal("input-available"), + providerExecuted: schemas_boolean().optional(), + input: unknown(), + output: never().optional(), + errorText: never().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + approval: never().optional() + }), + schemas_object({ + type: schemas_string().startsWith("tool-"), + toolCallId: schemas_string(), + state: schemas_literal("approval-requested"), + input: unknown(), + providerExecuted: schemas_boolean().optional(), + output: never().optional(), + errorText: never().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + approval: schemas_object({ + id: schemas_string(), + approved: never().optional(), + reason: never().optional() + }) + }), + schemas_object({ + type: schemas_string().startsWith("tool-"), + toolCallId: schemas_string(), + state: schemas_literal("approval-responded"), + input: unknown(), + providerExecuted: schemas_boolean().optional(), + output: never().optional(), + errorText: never().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + approval: schemas_object({ + id: schemas_string(), + approved: schemas_boolean(), + reason: schemas_string().optional() + }) + }), + schemas_object({ + type: schemas_string().startsWith("tool-"), + toolCallId: schemas_string(), + state: schemas_literal("output-available"), + providerExecuted: schemas_boolean().optional(), + input: unknown(), + output: unknown(), + errorText: never().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + resultProviderMetadata: providerMetadataSchema.optional(), + preliminary: schemas_boolean().optional(), + approval: schemas_object({ + id: schemas_string(), + approved: schemas_literal(true), + reason: schemas_string().optional() + }).optional() + }), + schemas_object({ + type: schemas_string().startsWith("tool-"), + toolCallId: schemas_string(), + state: schemas_literal("output-error"), + providerExecuted: schemas_boolean().optional(), + input: unknown(), + rawInput: unknown().optional(), + output: never().optional(), + errorText: schemas_string(), + callProviderMetadata: providerMetadataSchema.optional(), + resultProviderMetadata: providerMetadataSchema.optional(), + approval: schemas_object({ + id: schemas_string(), + approved: schemas_literal(true), + reason: schemas_string().optional() + }).optional() + }), + schemas_object({ + type: schemas_string().startsWith("tool-"), + toolCallId: schemas_string(), + state: schemas_literal("output-denied"), + providerExecuted: schemas_boolean().optional(), + input: unknown(), + output: never().optional(), + errorText: never().optional(), + callProviderMetadata: providerMetadataSchema.optional(), + approval: schemas_object({ + id: schemas_string(), + approved: schemas_literal(false), + reason: schemas_string().optional() + }) + }) + ])).nonempty("Message must contain at least one part") + })).nonempty("Messages array must not be empty"))); + createIdGenerator({ + prefix: "aiobj", + size: 24 + }); + function createDownload(options1) { + return ({ url, abortSignal })=>download({ + url, + maxBytes: null == options1 ? void 0 : options1.maxBytes, + abortSignal + }); + } + createIdGenerator({ + prefix: "aiobj", + size: 24 + }); + createDownload(); + var name20 = "AI_NoSuchProviderError"; + var marker20 = `vercel.ai.error.${name20}`; + Symbol.for(marker20); + createDownload(); + var anthropic_dist_VERSION = "3.0.69"; + var anthropicErrorDataSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + type: schemas_literal("error"), + error: schemas_object({ + type: schemas_string(), + message: schemas_string() + }) + }))); + var anthropicFailedResponseHandler = createJsonErrorResponseHandler({ + errorSchema: anthropicErrorDataSchema, + errorToMessage: (data)=>data.error.message + }); + var anthropicMessagesResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + type: schemas_literal("message"), + id: schemas_string().nullish(), + model: schemas_string().nullish(), + content: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("text"), + text: schemas_string(), + citations: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("web_search_result_location"), + cited_text: schemas_string(), + url: schemas_string(), + title: schemas_string(), + encrypted_index: schemas_string() + }), + schemas_object({ + type: schemas_literal("page_location"), + cited_text: schemas_string(), + document_index: schemas_number(), + document_title: schemas_string().nullable(), + start_page_number: schemas_number(), + end_page_number: schemas_number() + }), + schemas_object({ + type: schemas_literal("char_location"), + cited_text: schemas_string(), + document_index: schemas_number(), + document_title: schemas_string().nullable(), + start_char_index: schemas_number(), + end_char_index: schemas_number() + }) + ])).optional() + }), + schemas_object({ + type: schemas_literal("thinking"), + thinking: schemas_string(), + signature: schemas_string() + }), + schemas_object({ + type: schemas_literal("redacted_thinking"), + data: schemas_string() + }), + schemas_object({ + type: schemas_literal("compaction"), + content: schemas_string() + }), + schemas_object({ + type: schemas_literal("tool_use"), + id: schemas_string(), + name: schemas_string(), + input: unknown(), + caller: union([ + schemas_object({ + type: schemas_literal("code_execution_20250825"), + tool_id: schemas_string() + }), + schemas_object({ + type: schemas_literal("code_execution_20260120"), + tool_id: schemas_string() + }), + schemas_object({ + type: schemas_literal("direct") + }) + ]).optional() + }), + schemas_object({ + type: schemas_literal("server_tool_use"), + id: schemas_string(), + name: schemas_string(), + input: schemas_record(schemas_string(), unknown()).nullish(), + caller: union([ + schemas_object({ + type: schemas_literal("code_execution_20260120"), + tool_id: schemas_string() + }), + schemas_object({ + type: schemas_literal("direct") + }) + ]).optional() + }), + schemas_object({ + type: schemas_literal("mcp_tool_use"), + id: schemas_string(), + name: schemas_string(), + input: unknown(), + server_name: schemas_string() + }), + schemas_object({ + type: schemas_literal("mcp_tool_result"), + tool_use_id: schemas_string(), + is_error: schemas_boolean(), + content: schemas_array(union([ + schemas_string(), + schemas_object({ + type: schemas_literal("text"), + text: schemas_string() + }) + ])) + }), + schemas_object({ + type: schemas_literal("web_fetch_tool_result"), + tool_use_id: schemas_string(), + content: union([ + schemas_object({ + type: schemas_literal("web_fetch_result"), + url: schemas_string(), + retrieved_at: schemas_string(), + content: schemas_object({ + type: schemas_literal("document"), + title: schemas_string().nullable(), + citations: schemas_object({ + enabled: schemas_boolean() + }).optional(), + source: union([ + schemas_object({ + type: schemas_literal("base64"), + media_type: schemas_literal("application/pdf"), + data: schemas_string() + }), + schemas_object({ + type: schemas_literal("text"), + media_type: schemas_literal("text/plain"), + data: schemas_string() + }) + ]) + }) + }), + schemas_object({ + type: schemas_literal("web_fetch_tool_result_error"), + error_code: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("web_search_tool_result"), + tool_use_id: schemas_string(), + content: union([ + schemas_array(schemas_object({ + type: schemas_literal("web_search_result"), + url: schemas_string(), + title: schemas_string(), + encrypted_content: schemas_string(), + page_age: schemas_string().nullish() + })), + schemas_object({ + type: schemas_literal("web_search_tool_result_error"), + error_code: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("code_execution_tool_result"), + tool_use_id: schemas_string(), + content: union([ + schemas_object({ + type: schemas_literal("code_execution_result"), + stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number(), + content: schemas_array(schemas_object({ + type: schemas_literal("code_execution_output"), + file_id: schemas_string() + })).optional().default([]) + }), + schemas_object({ + type: schemas_literal("encrypted_code_execution_result"), + encrypted_stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number(), + content: schemas_array(schemas_object({ + type: schemas_literal("code_execution_output"), + file_id: schemas_string() + })).optional().default([]) + }), + schemas_object({ + type: schemas_literal("code_execution_tool_result_error"), + error_code: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("bash_code_execution_tool_result"), + tool_use_id: schemas_string(), + content: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("bash_code_execution_result"), + content: schemas_array(schemas_object({ + type: schemas_literal("bash_code_execution_output"), + file_id: schemas_string() + })), + stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number() + }), + schemas_object({ + type: schemas_literal("bash_code_execution_tool_result_error"), + error_code: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_tool_result"), + tool_use_id: schemas_string(), + content: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("text_editor_code_execution_tool_result_error"), + error_code: schemas_string() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_view_result"), + content: schemas_string(), + file_type: schemas_string(), + num_lines: schemas_number().nullable(), + start_line: schemas_number().nullable(), + total_lines: schemas_number().nullable() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_create_result"), + is_file_update: schemas_boolean() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_str_replace_result"), + lines: schemas_array(schemas_string()).nullable(), + new_lines: schemas_number().nullable(), + new_start: schemas_number().nullable(), + old_lines: schemas_number().nullable(), + old_start: schemas_number().nullable() + }) + ]) + }), + schemas_object({ + type: schemas_literal("tool_search_tool_result"), + tool_use_id: schemas_string(), + content: union([ + schemas_object({ + type: schemas_literal("tool_search_tool_search_result"), + tool_references: schemas_array(schemas_object({ + type: schemas_literal("tool_reference"), + tool_name: schemas_string() + })) + }), + schemas_object({ + type: schemas_literal("tool_search_tool_result_error"), + error_code: schemas_string() + }) + ]) + }) + ])), + stop_reason: schemas_string().nullish(), + stop_sequence: schemas_string().nullish(), + usage: looseObject({ + input_tokens: schemas_number(), + output_tokens: schemas_number(), + cache_creation_input_tokens: schemas_number().nullish(), + cache_read_input_tokens: schemas_number().nullish(), + iterations: schemas_array(schemas_object({ + type: union([ + schemas_literal("compaction"), + schemas_literal("message") + ]), + input_tokens: schemas_number(), + output_tokens: schemas_number() + })).nullish() + }), + container: schemas_object({ + expires_at: schemas_string(), + id: schemas_string(), + skills: schemas_array(schemas_object({ + type: union([ + schemas_literal("anthropic"), + schemas_literal("custom") + ]), + skill_id: schemas_string(), + version: schemas_string() + })).nullish() + }).nullish(), + context_management: schemas_object({ + applied_edits: schemas_array(union([ + schemas_object({ + type: schemas_literal("clear_tool_uses_20250919"), + cleared_tool_uses: schemas_number(), + cleared_input_tokens: schemas_number() + }), + schemas_object({ + type: schemas_literal("clear_thinking_20251015"), + cleared_thinking_turns: schemas_number(), + cleared_input_tokens: schemas_number() + }), + schemas_object({ + type: schemas_literal("compact_20260112") + }) + ])) + }).nullish() + }))); + var anthropicMessagesChunkSchema = dist_lazySchema(()=>dist_zodSchema(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("message_start"), + message: schemas_object({ + id: schemas_string().nullish(), + model: schemas_string().nullish(), + role: schemas_string().nullish(), + usage: looseObject({ + input_tokens: schemas_number(), + cache_creation_input_tokens: schemas_number().nullish(), + cache_read_input_tokens: schemas_number().nullish() + }), + content: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("tool_use"), + id: schemas_string(), + name: schemas_string(), + input: unknown(), + caller: union([ + schemas_object({ + type: schemas_literal("code_execution_20250825"), + tool_id: schemas_string() + }), + schemas_object({ + type: schemas_literal("code_execution_20260120"), + tool_id: schemas_string() + }), + schemas_object({ + type: schemas_literal("direct") + }) + ]).optional() + }) + ])).nullish(), + stop_reason: schemas_string().nullish(), + container: schemas_object({ + expires_at: schemas_string(), + id: schemas_string() + }).nullish() + }) + }), + schemas_object({ + type: schemas_literal("content_block_start"), + index: schemas_number(), + content_block: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("text"), + text: schemas_string() + }), + schemas_object({ + type: schemas_literal("thinking"), + thinking: schemas_string() + }), + schemas_object({ + type: schemas_literal("tool_use"), + id: schemas_string(), + name: schemas_string(), + input: schemas_record(schemas_string(), unknown()).optional(), + caller: union([ + schemas_object({ + type: schemas_literal("code_execution_20250825"), + tool_id: schemas_string() + }), + schemas_object({ + type: schemas_literal("code_execution_20260120"), + tool_id: schemas_string() + }), + schemas_object({ + type: schemas_literal("direct") + }) + ]).optional() + }), + schemas_object({ + type: schemas_literal("redacted_thinking"), + data: schemas_string() + }), + schemas_object({ + type: schemas_literal("compaction"), + content: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("server_tool_use"), + id: schemas_string(), + name: schemas_string(), + input: schemas_record(schemas_string(), unknown()).nullish(), + caller: union([ + schemas_object({ + type: schemas_literal("code_execution_20260120"), + tool_id: schemas_string() + }), + schemas_object({ + type: schemas_literal("direct") + }) + ]).optional() + }), + schemas_object({ + type: schemas_literal("mcp_tool_use"), + id: schemas_string(), + name: schemas_string(), + input: unknown(), + server_name: schemas_string() + }), + schemas_object({ + type: schemas_literal("mcp_tool_result"), + tool_use_id: schemas_string(), + is_error: schemas_boolean(), + content: schemas_array(union([ + schemas_string(), + schemas_object({ + type: schemas_literal("text"), + text: schemas_string() + }) + ])) + }), + schemas_object({ + type: schemas_literal("web_fetch_tool_result"), + tool_use_id: schemas_string(), + content: union([ + schemas_object({ + type: schemas_literal("web_fetch_result"), + url: schemas_string(), + retrieved_at: schemas_string(), + content: schemas_object({ + type: schemas_literal("document"), + title: schemas_string().nullable(), + citations: schemas_object({ + enabled: schemas_boolean() + }).optional(), + source: union([ + schemas_object({ + type: schemas_literal("base64"), + media_type: schemas_literal("application/pdf"), + data: schemas_string() + }), + schemas_object({ + type: schemas_literal("text"), + media_type: schemas_literal("text/plain"), + data: schemas_string() + }) + ]) + }) + }), + schemas_object({ + type: schemas_literal("web_fetch_tool_result_error"), + error_code: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("web_search_tool_result"), + tool_use_id: schemas_string(), + content: union([ + schemas_array(schemas_object({ + type: schemas_literal("web_search_result"), + url: schemas_string(), + title: schemas_string(), + encrypted_content: schemas_string(), + page_age: schemas_string().nullish() + })), + schemas_object({ + type: schemas_literal("web_search_tool_result_error"), + error_code: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("code_execution_tool_result"), + tool_use_id: schemas_string(), + content: union([ + schemas_object({ + type: schemas_literal("code_execution_result"), + stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number(), + content: schemas_array(schemas_object({ + type: schemas_literal("code_execution_output"), + file_id: schemas_string() + })).optional().default([]) + }), + schemas_object({ + type: schemas_literal("encrypted_code_execution_result"), + encrypted_stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number(), + content: schemas_array(schemas_object({ + type: schemas_literal("code_execution_output"), + file_id: schemas_string() + })).optional().default([]) + }), + schemas_object({ + type: schemas_literal("code_execution_tool_result_error"), + error_code: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("bash_code_execution_tool_result"), + tool_use_id: schemas_string(), + content: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("bash_code_execution_result"), + content: schemas_array(schemas_object({ + type: schemas_literal("bash_code_execution_output"), + file_id: schemas_string() + })), + stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number() + }), + schemas_object({ + type: schemas_literal("bash_code_execution_tool_result_error"), + error_code: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_tool_result"), + tool_use_id: schemas_string(), + content: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("text_editor_code_execution_tool_result_error"), + error_code: schemas_string() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_view_result"), + content: schemas_string(), + file_type: schemas_string(), + num_lines: schemas_number().nullable(), + start_line: schemas_number().nullable(), + total_lines: schemas_number().nullable() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_create_result"), + is_file_update: schemas_boolean() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_str_replace_result"), + lines: schemas_array(schemas_string()).nullable(), + new_lines: schemas_number().nullable(), + new_start: schemas_number().nullable(), + old_lines: schemas_number().nullable(), + old_start: schemas_number().nullable() + }) + ]) + }), + schemas_object({ + type: schemas_literal("tool_search_tool_result"), + tool_use_id: schemas_string(), + content: union([ + schemas_object({ + type: schemas_literal("tool_search_tool_search_result"), + tool_references: schemas_array(schemas_object({ + type: schemas_literal("tool_reference"), + tool_name: schemas_string() + })) + }), + schemas_object({ + type: schemas_literal("tool_search_tool_result_error"), + error_code: schemas_string() + }) + ]) + }) + ]) + }), + schemas_object({ + type: schemas_literal("content_block_delta"), + index: schemas_number(), + delta: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("input_json_delta"), + partial_json: schemas_string() + }), + schemas_object({ + type: schemas_literal("text_delta"), + text: schemas_string() + }), + schemas_object({ + type: schemas_literal("thinking_delta"), + thinking: schemas_string() + }), + schemas_object({ + type: schemas_literal("signature_delta"), + signature: schemas_string() + }), + schemas_object({ + type: schemas_literal("compaction_delta"), + content: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("citations_delta"), + citation: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("web_search_result_location"), + cited_text: schemas_string(), + url: schemas_string(), + title: schemas_string(), + encrypted_index: schemas_string() + }), + schemas_object({ + type: schemas_literal("page_location"), + cited_text: schemas_string(), + document_index: schemas_number(), + document_title: schemas_string().nullable(), + start_page_number: schemas_number(), + end_page_number: schemas_number() + }), + schemas_object({ + type: schemas_literal("char_location"), + cited_text: schemas_string(), + document_index: schemas_number(), + document_title: schemas_string().nullable(), + start_char_index: schemas_number(), + end_char_index: schemas_number() + }) + ]) + }) + ]) + }), + schemas_object({ + type: schemas_literal("content_block_stop"), + index: schemas_number() + }), + schemas_object({ + type: schemas_literal("error"), + error: schemas_object({ + type: schemas_string(), + message: schemas_string() + }) + }), + schemas_object({ + type: schemas_literal("message_delta"), + delta: schemas_object({ + stop_reason: schemas_string().nullish(), + stop_sequence: schemas_string().nullish(), + container: schemas_object({ + expires_at: schemas_string(), + id: schemas_string(), + skills: schemas_array(schemas_object({ + type: union([ + schemas_literal("anthropic"), + schemas_literal("custom") + ]), + skill_id: schemas_string(), + version: schemas_string() + })).nullish() + }).nullish() + }), + usage: looseObject({ + input_tokens: schemas_number().nullish(), + output_tokens: schemas_number(), + cache_creation_input_tokens: schemas_number().nullish(), + cache_read_input_tokens: schemas_number().nullish(), + iterations: schemas_array(schemas_object({ + type: union([ + schemas_literal("compaction"), + schemas_literal("message") + ]), + input_tokens: schemas_number(), + output_tokens: schemas_number() + })).nullish() + }), + context_management: schemas_object({ + applied_edits: schemas_array(union([ + schemas_object({ + type: schemas_literal("clear_tool_uses_20250919"), + cleared_tool_uses: schemas_number(), + cleared_input_tokens: schemas_number() + }), + schemas_object({ + type: schemas_literal("clear_thinking_20251015"), + cleared_thinking_turns: schemas_number(), + cleared_input_tokens: schemas_number() + }), + schemas_object({ + type: schemas_literal("compact_20260112") + }) + ])) + }).nullish() + }), + schemas_object({ + type: schemas_literal("message_stop") + }), + schemas_object({ + type: schemas_literal("ping") + }) + ]))); + var anthropicReasoningMetadataSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + signature: schemas_string().optional(), + redactedData: schemas_string().optional() + }))); + var anthropicFilePartProviderOptions = schemas_object({ + citations: schemas_object({ + enabled: schemas_boolean() + }).optional(), + title: schemas_string().optional(), + context: schemas_string().optional() + }); + var anthropicLanguageModelOptions = schemas_object({ + sendReasoning: schemas_boolean().optional(), + structuredOutputMode: schemas_enum([ + "outputFormat", + "jsonTool", + "auto" + ]).optional(), + thinking: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("adaptive") + }), + schemas_object({ + type: schemas_literal("enabled"), + budgetTokens: schemas_number().optional() + }), + schemas_object({ + type: schemas_literal("disabled") + }) + ]).optional(), + disableParallelToolUse: schemas_boolean().optional(), + cacheControl: schemas_object({ + type: schemas_literal("ephemeral"), + ttl: union([ + schemas_literal("5m"), + schemas_literal("1h") + ]).optional() + }).optional(), + metadata: schemas_object({ + userId: schemas_string().optional() + }).optional(), + mcpServers: schemas_array(schemas_object({ + type: schemas_literal("url"), + name: schemas_string(), + url: schemas_string(), + authorizationToken: schemas_string().nullish(), + toolConfiguration: schemas_object({ + enabled: schemas_boolean().nullish(), + allowedTools: schemas_array(schemas_string()).nullish() + }).nullish() + })).optional(), + container: schemas_object({ + id: schemas_string().optional(), + skills: schemas_array(schemas_object({ + type: union([ + schemas_literal("anthropic"), + schemas_literal("custom") + ]), + skillId: schemas_string(), + version: schemas_string().optional() + })).optional() + }).optional(), + toolStreaming: schemas_boolean().optional(), + effort: schemas_enum([ + "low", + "medium", + "high", + "max" + ]).optional(), + speed: schemas_enum([ + "fast", + "standard" + ]).optional(), + inferenceGeo: schemas_enum([ + "us", + "global" + ]).optional(), + anthropicBeta: schemas_array(schemas_string()).optional(), + contextManagement: schemas_object({ + edits: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("clear_tool_uses_20250919"), + trigger: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("input_tokens"), + value: schemas_number() + }), + schemas_object({ + type: schemas_literal("tool_uses"), + value: schemas_number() + }) + ]).optional(), + keep: schemas_object({ + type: schemas_literal("tool_uses"), + value: schemas_number() + }).optional(), + clearAtLeast: schemas_object({ + type: schemas_literal("input_tokens"), + value: schemas_number() + }).optional(), + clearToolInputs: schemas_boolean().optional(), + excludeTools: schemas_array(schemas_string()).optional() + }), + schemas_object({ + type: schemas_literal("clear_thinking_20251015"), + keep: union([ + schemas_literal("all"), + schemas_object({ + type: schemas_literal("thinking_turns"), + value: schemas_number() + }) + ]).optional() + }), + schemas_object({ + type: schemas_literal("compact_20260112"), + trigger: schemas_object({ + type: schemas_literal("input_tokens"), + value: schemas_number() + }).optional(), + pauseAfterCompaction: schemas_boolean().optional(), + instructions: schemas_string().optional() + }) + ])) + }).optional() + }); + var MAX_CACHE_BREAKPOINTS = 4; + function getCacheControl(providerMetadata) { + var _a; + const anthropic2 = null == providerMetadata ? void 0 : providerMetadata.anthropic; + const cacheControlValue = null != (_a = null == anthropic2 ? void 0 : anthropic2.cacheControl) ? _a : null == anthropic2 ? void 0 : anthropic2.cache_control; + return cacheControlValue; + } + var CacheControlValidator = class { + constructor(){ + this.breakpointCount = 0; + this.warnings = []; + } + getCacheControl(providerMetadata, context) { + const cacheControlValue = getCacheControl(providerMetadata); + if (!cacheControlValue) return; + if (!context.canCache) return void this.warnings.push({ + type: "unsupported", + feature: "cache_control on non-cacheable context", + details: `cache_control cannot be set on ${context.type}. It will be ignored.` + }); + this.breakpointCount++; + if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) return void this.warnings.push({ + type: "unsupported", + feature: "cacheControl breakpoint limit", + details: `Maximum ${MAX_CACHE_BREAKPOINTS} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.` + }); + return cacheControlValue; + } + getWarnings() { + return this.warnings; + } + }; + var textEditor_20250728ArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + maxCharacters: schemas_number().optional() + }))); + var textEditor_20250728InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + command: schemas_enum([ + "view", + "create", + "str_replace", + "insert" + ]), + path: schemas_string(), + file_text: schemas_string().optional(), + insert_line: schemas_number().int().optional(), + new_str: schemas_string().optional(), + insert_text: schemas_string().optional(), + old_str: schemas_string().optional(), + view_range: schemas_array(schemas_number().int()).optional() + }))); + var factory = createProviderToolFactory({ + id: "anthropic.text_editor_20250728", + inputSchema: textEditor_20250728InputSchema + }); + var textEditor_20250728 = (args = {})=>factory(args); + var webSearch_20260209ArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + maxUses: schemas_number().optional(), + allowedDomains: schemas_array(schemas_string()).optional(), + blockedDomains: schemas_array(schemas_string()).optional(), + userLocation: schemas_object({ + type: schemas_literal("approximate"), + city: schemas_string().optional(), + region: schemas_string().optional(), + country: schemas_string().optional(), + timezone: schemas_string().optional() + }).optional() + }))); + var webSearch_20260209OutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_array(schemas_object({ + url: schemas_string(), + title: schemas_string().nullable(), + pageAge: schemas_string().nullable(), + encryptedContent: schemas_string(), + type: schemas_literal("web_search_result") + })))); + var webSearch_20260209InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + query: schemas_string() + }))); + var factory2 = createProviderToolFactoryWithOutputSchema({ + id: "anthropic.web_search_20260209", + inputSchema: webSearch_20260209InputSchema, + outputSchema: webSearch_20260209OutputSchema, + supportsDeferredResults: true + }); + var webSearch_20260209 = (args = {})=>factory2(args); + var webSearch_20250305ArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + maxUses: schemas_number().optional(), + allowedDomains: schemas_array(schemas_string()).optional(), + blockedDomains: schemas_array(schemas_string()).optional(), + userLocation: schemas_object({ + type: schemas_literal("approximate"), + city: schemas_string().optional(), + region: schemas_string().optional(), + country: schemas_string().optional(), + timezone: schemas_string().optional() + }).optional() + }))); + var webSearch_20250305OutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_array(schemas_object({ + url: schemas_string(), + title: schemas_string().nullable(), + pageAge: schemas_string().nullable(), + encryptedContent: schemas_string(), + type: schemas_literal("web_search_result") + })))); + var webSearch_20250305InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + query: schemas_string() + }))); + var factory3 = createProviderToolFactoryWithOutputSchema({ + id: "anthropic.web_search_20250305", + inputSchema: webSearch_20250305InputSchema, + outputSchema: webSearch_20250305OutputSchema, + supportsDeferredResults: true + }); + var webSearch_20250305 = (args = {})=>factory3(args); + var webFetch_20260209ArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + maxUses: schemas_number().optional(), + allowedDomains: schemas_array(schemas_string()).optional(), + blockedDomains: schemas_array(schemas_string()).optional(), + citations: schemas_object({ + enabled: schemas_boolean() + }).optional(), + maxContentTokens: schemas_number().optional() + }))); + var webFetch_20260209OutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + type: schemas_literal("web_fetch_result"), + url: schemas_string(), + content: schemas_object({ + type: schemas_literal("document"), + title: schemas_string().nullable(), + citations: schemas_object({ + enabled: schemas_boolean() + }).optional(), + source: union([ + schemas_object({ + type: schemas_literal("base64"), + mediaType: schemas_literal("application/pdf"), + data: schemas_string() + }), + schemas_object({ + type: schemas_literal("text"), + mediaType: schemas_literal("text/plain"), + data: schemas_string() + }) + ]) + }), + retrievedAt: schemas_string().nullable() + }))); + var webFetch_20260209InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + url: schemas_string() + }))); + var factory4 = createProviderToolFactoryWithOutputSchema({ + id: "anthropic.web_fetch_20260209", + inputSchema: webFetch_20260209InputSchema, + outputSchema: webFetch_20260209OutputSchema, + supportsDeferredResults: true + }); + var webFetch_20260209 = (args = {})=>factory4(args); + var webFetch_20250910ArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + maxUses: schemas_number().optional(), + allowedDomains: schemas_array(schemas_string()).optional(), + blockedDomains: schemas_array(schemas_string()).optional(), + citations: schemas_object({ + enabled: schemas_boolean() + }).optional(), + maxContentTokens: schemas_number().optional() + }))); + var webFetch_20250910OutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + type: schemas_literal("web_fetch_result"), + url: schemas_string(), + content: schemas_object({ + type: schemas_literal("document"), + title: schemas_string().nullable(), + citations: schemas_object({ + enabled: schemas_boolean() + }).optional(), + source: union([ + schemas_object({ + type: schemas_literal("base64"), + mediaType: schemas_literal("application/pdf"), + data: schemas_string() + }), + schemas_object({ + type: schemas_literal("text"), + mediaType: schemas_literal("text/plain"), + data: schemas_string() + }) + ]) + }), + retrievedAt: schemas_string().nullable() + }))); + var webFetch_20250910InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + url: schemas_string() + }))); + var factory5 = createProviderToolFactoryWithOutputSchema({ + id: "anthropic.web_fetch_20250910", + inputSchema: webFetch_20250910InputSchema, + outputSchema: webFetch_20250910OutputSchema, + supportsDeferredResults: true + }); + var webFetch_20250910 = (args = {})=>factory5(args); + async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools }) { + var _a; + tools = (null == tools ? void 0 : tools.length) ? tools : void 0; + const toolWarnings = []; + const betas = /* @__PURE__ */ new Set(); + const validator = cacheControlValidator || new CacheControlValidator(); + if (null == tools) return { + tools: void 0, + toolChoice: void 0, + toolWarnings, + betas + }; + const anthropicTools2 = []; + for (const tool of tools)switch(tool.type){ + case "function": + { + const cacheControl = validator.getCacheControl(tool.providerOptions, { + type: "tool definition", + canCache: true + }); + const anthropicOptions = null == (_a = tool.providerOptions) ? void 0 : _a.anthropic; + const eagerInputStreaming = null == anthropicOptions ? void 0 : anthropicOptions.eagerInputStreaming; + const deferLoading = null == anthropicOptions ? void 0 : anthropicOptions.deferLoading; + const allowedCallers = null == anthropicOptions ? void 0 : anthropicOptions.allowedCallers; + if (!supportsStrictTools && null != tool.strict) toolWarnings.push({ + type: "unsupported", + feature: "strict", + details: `Tool '${tool.name}' has strict: ${tool.strict}, but strict mode is not supported by this provider. The strict property will be ignored.` + }); + anthropicTools2.push({ + name: tool.name, + description: tool.description, + input_schema: tool.inputSchema, + cache_control: cacheControl, + ...eagerInputStreaming ? { + eager_input_streaming: true + } : {}, + ...true === supportsStrictTools && null != tool.strict ? { + strict: tool.strict + } : {}, + ...null != deferLoading ? { + defer_loading: deferLoading + } : {}, + ...null != allowedCallers ? { + allowed_callers: allowedCallers + } : {}, + ...null != tool.inputExamples ? { + input_examples: tool.inputExamples.map((example)=>example.input) + } : {} + }); + if (true === supportsStructuredOutput) betas.add("structured-outputs-2025-11-13"); + if (null != tool.inputExamples || null != allowedCallers) betas.add("advanced-tool-use-2025-11-20"); + break; + } + case "provider": + switch(tool.id){ + case "anthropic.code_execution_20250522": + betas.add("code-execution-2025-05-22"); + anthropicTools2.push({ + type: "code_execution_20250522", + name: "code_execution", + cache_control: void 0 + }); + break; + case "anthropic.code_execution_20250825": + betas.add("code-execution-2025-08-25"); + anthropicTools2.push({ + type: "code_execution_20250825", + name: "code_execution" + }); + break; + case "anthropic.code_execution_20260120": + anthropicTools2.push({ + type: "code_execution_20260120", + name: "code_execution" + }); + break; + case "anthropic.computer_20250124": + betas.add("computer-use-2025-01-24"); + anthropicTools2.push({ + name: "computer", + type: "computer_20250124", + display_width_px: tool.args.displayWidthPx, + display_height_px: tool.args.displayHeightPx, + display_number: tool.args.displayNumber, + cache_control: void 0 + }); + break; + case "anthropic.computer_20251124": + betas.add("computer-use-2025-11-24"); + anthropicTools2.push({ + name: "computer", + type: "computer_20251124", + display_width_px: tool.args.displayWidthPx, + display_height_px: tool.args.displayHeightPx, + display_number: tool.args.displayNumber, + enable_zoom: tool.args.enableZoom, + cache_control: void 0 + }); + break; + case "anthropic.computer_20241022": + betas.add("computer-use-2024-10-22"); + anthropicTools2.push({ + name: "computer", + type: "computer_20241022", + display_width_px: tool.args.displayWidthPx, + display_height_px: tool.args.displayHeightPx, + display_number: tool.args.displayNumber, + cache_control: void 0 + }); + break; + case "anthropic.text_editor_20250124": + betas.add("computer-use-2025-01-24"); + anthropicTools2.push({ + name: "str_replace_editor", + type: "text_editor_20250124", + cache_control: void 0 + }); + break; + case "anthropic.text_editor_20241022": + betas.add("computer-use-2024-10-22"); + anthropicTools2.push({ + name: "str_replace_editor", + type: "text_editor_20241022", + cache_control: void 0 + }); + break; + case "anthropic.text_editor_20250429": + betas.add("computer-use-2025-01-24"); + anthropicTools2.push({ + name: "str_replace_based_edit_tool", + type: "text_editor_20250429", + cache_control: void 0 + }); + break; + case "anthropic.text_editor_20250728": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: textEditor_20250728ArgsSchema + }); + anthropicTools2.push({ + name: "str_replace_based_edit_tool", + type: "text_editor_20250728", + max_characters: args.maxCharacters, + cache_control: void 0 + }); + break; + } + case "anthropic.bash_20250124": + betas.add("computer-use-2025-01-24"); + anthropicTools2.push({ + name: "bash", + type: "bash_20250124", + cache_control: void 0 + }); + break; + case "anthropic.bash_20241022": + betas.add("computer-use-2024-10-22"); + anthropicTools2.push({ + name: "bash", + type: "bash_20241022", + cache_control: void 0 + }); + break; + case "anthropic.memory_20250818": + betas.add("context-management-2025-06-27"); + anthropicTools2.push({ + name: "memory", + type: "memory_20250818" + }); + break; + case "anthropic.web_fetch_20250910": + { + betas.add("web-fetch-2025-09-10"); + const args = await dist_validateTypes({ + value: tool.args, + schema: webFetch_20250910ArgsSchema + }); + anthropicTools2.push({ + type: "web_fetch_20250910", + name: "web_fetch", + max_uses: args.maxUses, + allowed_domains: args.allowedDomains, + blocked_domains: args.blockedDomains, + citations: args.citations, + max_content_tokens: args.maxContentTokens, + cache_control: void 0 + }); + break; + } + case "anthropic.web_fetch_20260209": + { + betas.add("code-execution-web-tools-2026-02-09"); + const args = await dist_validateTypes({ + value: tool.args, + schema: webFetch_20260209ArgsSchema + }); + anthropicTools2.push({ + type: "web_fetch_20260209", + name: "web_fetch", + max_uses: args.maxUses, + allowed_domains: args.allowedDomains, + blocked_domains: args.blockedDomains, + citations: args.citations, + max_content_tokens: args.maxContentTokens, + cache_control: void 0 + }); + break; + } + case "anthropic.web_search_20250305": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: webSearch_20250305ArgsSchema + }); + anthropicTools2.push({ + type: "web_search_20250305", + name: "web_search", + max_uses: args.maxUses, + allowed_domains: args.allowedDomains, + blocked_domains: args.blockedDomains, + user_location: args.userLocation, + cache_control: void 0 + }); + break; + } + case "anthropic.web_search_20260209": + { + betas.add("code-execution-web-tools-2026-02-09"); + const args = await dist_validateTypes({ + value: tool.args, + schema: webSearch_20260209ArgsSchema + }); + anthropicTools2.push({ + type: "web_search_20260209", + name: "web_search", + max_uses: args.maxUses, + allowed_domains: args.allowedDomains, + blocked_domains: args.blockedDomains, + user_location: args.userLocation, + cache_control: void 0 + }); + break; + } + case "anthropic.tool_search_regex_20251119": + anthropicTools2.push({ + type: "tool_search_tool_regex_20251119", + name: "tool_search_tool_regex" + }); + break; + case "anthropic.tool_search_bm25_20251119": + anthropicTools2.push({ + type: "tool_search_tool_bm25_20251119", + name: "tool_search_tool_bm25" + }); + break; + default: + toolWarnings.push({ + type: "unsupported", + feature: `provider-defined tool ${tool.id}` + }); + break; + } + break; + default: + toolWarnings.push({ + type: "unsupported", + feature: `tool ${tool}` + }); + break; + } + if (null == toolChoice) return { + tools: anthropicTools2, + toolChoice: disableParallelToolUse ? { + type: "auto", + disable_parallel_tool_use: disableParallelToolUse + } : void 0, + toolWarnings, + betas + }; + const type = toolChoice.type; + switch(type){ + case "auto": + return { + tools: anthropicTools2, + toolChoice: { + type: "auto", + disable_parallel_tool_use: disableParallelToolUse + }, + toolWarnings, + betas + }; + case "required": + return { + tools: anthropicTools2, + toolChoice: { + type: "any", + disable_parallel_tool_use: disableParallelToolUse + }, + toolWarnings, + betas + }; + case "none": + return { + tools: void 0, + toolChoice: void 0, + toolWarnings, + betas + }; + case "tool": + return { + tools: anthropicTools2, + toolChoice: { + type: "tool", + name: toolChoice.toolName, + disable_parallel_tool_use: disableParallelToolUse + }, + toolWarnings, + betas + }; + default: + { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `tool choice type: ${_exhaustiveCheck}` + }); + } + } + } + function convertAnthropicMessagesUsage({ usage, rawUsage }) { + var _a, _b; + const cacheCreationTokens = null != (_a = usage.cache_creation_input_tokens) ? _a : 0; + const cacheReadTokens = null != (_b = usage.cache_read_input_tokens) ? _b : 0; + let inputTokens; + let outputTokens; + if (usage.iterations && usage.iterations.length > 0) { + const totals = usage.iterations.reduce((acc, iter)=>({ + input: acc.input + iter.input_tokens, + output: acc.output + iter.output_tokens + }), { + input: 0, + output: 0 + }); + inputTokens = totals.input; + outputTokens = totals.output; + } else { + inputTokens = usage.input_tokens; + outputTokens = usage.output_tokens; + } + return { + inputTokens: { + total: inputTokens + cacheCreationTokens + cacheReadTokens, + noCache: inputTokens, + cacheRead: cacheReadTokens, + cacheWrite: cacheCreationTokens + }, + outputTokens: { + total: outputTokens, + text: void 0, + reasoning: void 0 + }, + raw: null != rawUsage ? rawUsage : usage + }; + } + var codeExecution_20250522OutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + type: schemas_literal("code_execution_result"), + stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number(), + content: schemas_array(schemas_object({ + type: schemas_literal("code_execution_output"), + file_id: schemas_string() + })).optional().default([]) + }))); + var codeExecution_20250522InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + code: schemas_string() + }))); + var factory6 = createProviderToolFactoryWithOutputSchema({ + id: "anthropic.code_execution_20250522", + inputSchema: codeExecution_20250522InputSchema, + outputSchema: codeExecution_20250522OutputSchema + }); + var codeExecution_20250522 = (args = {})=>factory6(args); + var codeExecution_20250825OutputSchema = dist_lazySchema(()=>dist_zodSchema(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("code_execution_result"), + stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number(), + content: schemas_array(schemas_object({ + type: schemas_literal("code_execution_output"), + file_id: schemas_string() + })).optional().default([]) + }), + schemas_object({ + type: schemas_literal("bash_code_execution_result"), + content: schemas_array(schemas_object({ + type: schemas_literal("bash_code_execution_output"), + file_id: schemas_string() + })), + stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number() + }), + schemas_object({ + type: schemas_literal("bash_code_execution_tool_result_error"), + error_code: schemas_string() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_tool_result_error"), + error_code: schemas_string() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_view_result"), + content: schemas_string(), + file_type: schemas_string(), + num_lines: schemas_number().nullable(), + start_line: schemas_number().nullable(), + total_lines: schemas_number().nullable() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_create_result"), + is_file_update: schemas_boolean() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_str_replace_result"), + lines: schemas_array(schemas_string()).nullable(), + new_lines: schemas_number().nullable(), + new_start: schemas_number().nullable(), + old_lines: schemas_number().nullable(), + old_start: schemas_number().nullable() + }) + ]))); + var codeExecution_20250825InputSchema = dist_lazySchema(()=>dist_zodSchema(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("programmatic-tool-call"), + code: schemas_string() + }), + schemas_object({ + type: schemas_literal("bash_code_execution"), + command: schemas_string() + }), + discriminatedUnion("command", [ + schemas_object({ + type: schemas_literal("text_editor_code_execution"), + command: schemas_literal("view"), + path: schemas_string() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution"), + command: schemas_literal("create"), + path: schemas_string(), + file_text: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution"), + command: schemas_literal("str_replace"), + path: schemas_string(), + old_str: schemas_string(), + new_str: schemas_string() + }) + ]) + ]))); + var factory7 = createProviderToolFactoryWithOutputSchema({ + id: "anthropic.code_execution_20250825", + inputSchema: codeExecution_20250825InputSchema, + outputSchema: codeExecution_20250825OutputSchema, + supportsDeferredResults: true + }); + var codeExecution_20250825 = (args = {})=>factory7(args); + var codeExecution_20260120OutputSchema = dist_lazySchema(()=>dist_zodSchema(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("code_execution_result"), + stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number(), + content: schemas_array(schemas_object({ + type: schemas_literal("code_execution_output"), + file_id: schemas_string() + })).optional().default([]) + }), + schemas_object({ + type: schemas_literal("encrypted_code_execution_result"), + encrypted_stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number(), + content: schemas_array(schemas_object({ + type: schemas_literal("code_execution_output"), + file_id: schemas_string() + })).optional().default([]) + }), + schemas_object({ + type: schemas_literal("bash_code_execution_result"), + content: schemas_array(schemas_object({ + type: schemas_literal("bash_code_execution_output"), + file_id: schemas_string() + })), + stdout: schemas_string(), + stderr: schemas_string(), + return_code: schemas_number() + }), + schemas_object({ + type: schemas_literal("bash_code_execution_tool_result_error"), + error_code: schemas_string() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_tool_result_error"), + error_code: schemas_string() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_view_result"), + content: schemas_string(), + file_type: schemas_string(), + num_lines: schemas_number().nullable(), + start_line: schemas_number().nullable(), + total_lines: schemas_number().nullable() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_create_result"), + is_file_update: schemas_boolean() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution_str_replace_result"), + lines: schemas_array(schemas_string()).nullable(), + new_lines: schemas_number().nullable(), + new_start: schemas_number().nullable(), + old_lines: schemas_number().nullable(), + old_start: schemas_number().nullable() + }) + ]))); + var codeExecution_20260120InputSchema = dist_lazySchema(()=>dist_zodSchema(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("programmatic-tool-call"), + code: schemas_string() + }), + schemas_object({ + type: schemas_literal("bash_code_execution"), + command: schemas_string() + }), + discriminatedUnion("command", [ + schemas_object({ + type: schemas_literal("text_editor_code_execution"), + command: schemas_literal("view"), + path: schemas_string() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution"), + command: schemas_literal("create"), + path: schemas_string(), + file_text: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("text_editor_code_execution"), + command: schemas_literal("str_replace"), + path: schemas_string(), + old_str: schemas_string(), + new_str: schemas_string() + }) + ]) + ]))); + var factory8 = createProviderToolFactoryWithOutputSchema({ + id: "anthropic.code_execution_20260120", + inputSchema: codeExecution_20260120InputSchema, + outputSchema: codeExecution_20260120OutputSchema, + supportsDeferredResults: true + }); + var codeExecution_20260120 = (args = {})=>factory8(args); + var toolSearchRegex_20251119OutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_array(schemas_object({ + type: schemas_literal("tool_reference"), + toolName: schemas_string() + })))); + var toolSearchRegex_20251119InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + pattern: schemas_string(), + limit: schemas_number().optional() + }))); + var factory9 = createProviderToolFactoryWithOutputSchema({ + id: "anthropic.tool_search_regex_20251119", + inputSchema: toolSearchRegex_20251119InputSchema, + outputSchema: toolSearchRegex_20251119OutputSchema, + supportsDeferredResults: true + }); + var toolSearchRegex_20251119 = (args = {})=>factory9(args); + function convertToString(data) { + if ("string" == typeof data) return new TextDecoder().decode(convertBase64ToUint8Array(data)); + if (data instanceof Uint8Array) return new TextDecoder().decode(data); + if (data instanceof URL) throw new UnsupportedFunctionalityError({ + functionality: "URL-based text documents are not supported for citations" + }); + throw new UnsupportedFunctionalityError({ + functionality: `unsupported data type for text documents: ${typeof data}` + }); + } + function isUrlData(data) { + return data instanceof URL || isUrlString(data); + } + function isUrlString(data) { + return "string" == typeof data && /^https?:\/\//i.test(data); + } + function getUrlString(data) { + return data instanceof URL ? data.toString() : data; + } + async function convertToAnthropicMessagesPrompt({ prompt, sendReasoning, warnings, cacheControlValidator, toolNameMapping }) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s; + const betas = /* @__PURE__ */ new Set(); + const blocks = groupIntoBlocks(prompt); + const validator = cacheControlValidator || new CacheControlValidator(); + let system; + const messages = []; + async function shouldEnableCitations(providerMetadata) { + var _a2, _b2; + const anthropicOptions = await parseProviderOptions({ + provider: "anthropic", + providerOptions: providerMetadata, + schema: anthropicFilePartProviderOptions + }); + return null != (_b2 = null == (_a2 = null == anthropicOptions ? void 0 : anthropicOptions.citations) ? void 0 : _a2.enabled) ? _b2 : false; + } + async function getDocumentMetadata(providerMetadata) { + const anthropicOptions = await parseProviderOptions({ + provider: "anthropic", + providerOptions: providerMetadata, + schema: anthropicFilePartProviderOptions + }); + return { + title: null == anthropicOptions ? void 0 : anthropicOptions.title, + context: null == anthropicOptions ? void 0 : anthropicOptions.context + }; + } + for(let i = 0; i < blocks.length; i++){ + const block = blocks[i]; + const isLastBlock = i === blocks.length - 1; + const type = block.type; + switch(type){ + case "system": + if (null != system) throw new UnsupportedFunctionalityError({ + functionality: "Multiple system messages that are separated by user/assistant messages" + }); + system = block.messages.map(({ content, providerOptions })=>({ + type: "text", + text: content, + cache_control: validator.getCacheControl(providerOptions, { + type: "system message", + canCache: true + }) + })); + break; + case "user": + { + const anthropicContent = []; + for (const message of block.messages){ + const { role, content } = message; + switch(role){ + case "user": + for(let j = 0; j < content.length; j++){ + const part = content[j]; + const isLastPart = j === content.length - 1; + const cacheControl = null != (_a = validator.getCacheControl(part.providerOptions, { + type: "user message part", + canCache: true + })) ? _a : isLastPart ? validator.getCacheControl(message.providerOptions, { + type: "user message", + canCache: true + }) : void 0; + switch(part.type){ + case "text": + anthropicContent.push({ + type: "text", + text: part.text, + cache_control: cacheControl + }); + break; + case "file": + if (part.mediaType.startsWith("image/")) anthropicContent.push({ + type: "image", + source: isUrlData(part.data) ? { + type: "url", + url: getUrlString(part.data) + } : { + type: "base64", + media_type: "image/*" === part.mediaType ? "image/jpeg" : part.mediaType, + data: convertToBase64(part.data) + }, + cache_control: cacheControl + }); + else if ("application/pdf" === part.mediaType) { + betas.add("pdfs-2024-09-25"); + const enableCitations = await shouldEnableCitations(part.providerOptions); + const metadata = await getDocumentMetadata(part.providerOptions); + anthropicContent.push({ + type: "document", + source: isUrlData(part.data) ? { + type: "url", + url: getUrlString(part.data) + } : { + type: "base64", + media_type: "application/pdf", + data: convertToBase64(part.data) + }, + title: null != (_b = metadata.title) ? _b : part.filename, + ...metadata.context && { + context: metadata.context + }, + ...enableCitations && { + citations: { + enabled: true + } + }, + cache_control: cacheControl + }); + } else if ("text/plain" === part.mediaType) { + const enableCitations = await shouldEnableCitations(part.providerOptions); + const metadata = await getDocumentMetadata(part.providerOptions); + anthropicContent.push({ + type: "document", + source: isUrlData(part.data) ? { + type: "url", + url: getUrlString(part.data) + } : { + type: "text", + media_type: "text/plain", + data: convertToString(part.data) + }, + title: null != (_c = metadata.title) ? _c : part.filename, + ...metadata.context && { + context: metadata.context + }, + ...enableCitations && { + citations: { + enabled: true + } + }, + cache_control: cacheControl + }); + } else throw new UnsupportedFunctionalityError({ + functionality: `media type: ${part.mediaType}` + }); + break; + } + } + break; + case "tool": + for(let i2 = 0; i2 < content.length; i2++){ + const part = content[i2]; + if ("tool-approval-response" === part.type) continue; + const isLastPart = i2 === content.length - 1; + const cacheControl = null != (_d = validator.getCacheControl(part.providerOptions, { + type: "tool result part", + canCache: true + })) ? _d : isLastPart ? validator.getCacheControl(message.providerOptions, { + type: "tool result message", + canCache: true + }) : void 0; + const output = part.output; + let contentValue; + switch(output.type){ + case "content": + contentValue = output.value.map((contentPart)=>{ + var _a2; + switch(contentPart.type){ + case "text": + return { + type: "text", + text: contentPart.text + }; + case "image-data": + return { + type: "image", + source: { + type: "base64", + media_type: contentPart.mediaType, + data: contentPart.data + } + }; + case "image-url": + return { + type: "image", + source: { + type: "url", + url: contentPart.url + } + }; + case "file-url": + return { + type: "document", + source: { + type: "url", + url: contentPart.url + } + }; + case "file-data": + if ("application/pdf" === contentPart.mediaType) { + betas.add("pdfs-2024-09-25"); + return { + type: "document", + source: { + type: "base64", + media_type: contentPart.mediaType, + data: contentPart.data + } + }; + } + warnings.push({ + type: "other", + message: `unsupported tool content part type: ${contentPart.type} with media type: ${contentPart.mediaType}` + }); + return; + case "custom": + { + const anthropicOptions = null == (_a2 = contentPart.providerOptions) ? void 0 : _a2.anthropic; + if ((null == anthropicOptions ? void 0 : anthropicOptions.type) === "tool-reference") return { + type: "tool_reference", + tool_name: anthropicOptions.toolName + }; + warnings.push({ + type: "other", + message: "unsupported custom tool content part" + }); + return; + } + default: + return void warnings.push({ + type: "other", + message: `unsupported tool content part type: ${contentPart.type}` + }); + } + }).filter(dist_isNonNullable); + break; + case "text": + case "error-text": + contentValue = output.value; + break; + case "execution-denied": + contentValue = null != (_e = output.reason) ? _e : "Tool execution denied."; + break; + case "json": + case "error-json": + default: + contentValue = JSON.stringify(output.value); + break; + } + anthropicContent.push({ + type: "tool_result", + tool_use_id: part.toolCallId, + content: contentValue, + is_error: "error-text" === output.type || "error-json" === output.type ? true : void 0, + cache_control: cacheControl + }); + } + break; + default: + { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + messages.push({ + role: "user", + content: anthropicContent + }); + break; + } + case "assistant": + { + const anthropicContent = []; + const mcpToolUseIds = /* @__PURE__ */ new Set(); + for(let j = 0; j < block.messages.length; j++){ + const message = block.messages[j]; + const isLastMessage = j === block.messages.length - 1; + const { content } = message; + for(let k = 0; k < content.length; k++){ + const part = content[k]; + const isLastContentPart = k === content.length - 1; + const cacheControl = null != (_f = validator.getCacheControl(part.providerOptions, { + type: "assistant message part", + canCache: true + })) ? _f : isLastContentPart ? validator.getCacheControl(message.providerOptions, { + type: "assistant message", + canCache: true + }) : void 0; + switch(part.type){ + case "text": + { + const textMetadata = null == (_g = part.providerOptions) ? void 0 : _g.anthropic; + if ((null == textMetadata ? void 0 : textMetadata.type) === "compaction") anthropicContent.push({ + type: "compaction", + content: part.text, + cache_control: cacheControl + }); + else anthropicContent.push({ + type: "text", + text: isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text, + cache_control: cacheControl + }); + break; + } + case "reasoning": + if (sendReasoning) { + const reasoningMetadata = await parseProviderOptions({ + provider: "anthropic", + providerOptions: part.providerOptions, + schema: anthropicReasoningMetadataSchema + }); + if (null != reasoningMetadata) if (null != reasoningMetadata.signature) { + validator.getCacheControl(part.providerOptions, { + type: "thinking block", + canCache: false + }); + anthropicContent.push({ + type: "thinking", + thinking: part.text, + signature: reasoningMetadata.signature + }); + } else if (null != reasoningMetadata.redactedData) { + validator.getCacheControl(part.providerOptions, { + type: "redacted thinking block", + canCache: false + }); + anthropicContent.push({ + type: "redacted_thinking", + data: reasoningMetadata.redactedData + }); + } else warnings.push({ + type: "other", + message: "unsupported reasoning metadata" + }); + else warnings.push({ + type: "other", + message: "unsupported reasoning metadata" + }); + } else warnings.push({ + type: "other", + message: "sending reasoning content is disabled for this model" + }); + break; + case "tool-call": + { + if (part.providerExecuted) { + const providerToolName = toolNameMapping.toProviderToolName(part.toolName); + const isMcpToolUse = (null == (_i = null == (_h = part.providerOptions) ? void 0 : _h.anthropic) ? void 0 : _i.type) === "mcp-tool-use"; + if (isMcpToolUse) { + mcpToolUseIds.add(part.toolCallId); + const serverName = null == (_k = null == (_j = part.providerOptions) ? void 0 : _j.anthropic) ? void 0 : _k.serverName; + if (null == serverName || "string" != typeof serverName) { + warnings.push({ + type: "other", + message: "mcp tool use server name is required and must be a string" + }); + break; + } + anthropicContent.push({ + type: "mcp_tool_use", + id: part.toolCallId, + name: part.toolName, + input: part.input, + server_name: serverName, + cache_control: cacheControl + }); + } else if ("code_execution" === providerToolName && null != part.input && "object" == typeof part.input && "type" in part.input && "string" == typeof part.input.type && ("bash_code_execution" === part.input.type || "text_editor_code_execution" === part.input.type)) anthropicContent.push({ + type: "server_tool_use", + id: part.toolCallId, + name: part.input.type, + input: part.input, + cache_control: cacheControl + }); + else if ("code_execution" === providerToolName && null != part.input && "object" == typeof part.input && "type" in part.input && "programmatic-tool-call" === part.input.type) { + const { type: _1, ...inputWithoutType } = part.input; + anthropicContent.push({ + type: "server_tool_use", + id: part.toolCallId, + name: "code_execution", + input: inputWithoutType, + cache_control: cacheControl + }); + } else if ("code_execution" === providerToolName || "web_fetch" === providerToolName || "web_search" === providerToolName) anthropicContent.push({ + type: "server_tool_use", + id: part.toolCallId, + name: providerToolName, + input: part.input, + cache_control: cacheControl + }); + else if ("tool_search_tool_regex" === providerToolName || "tool_search_tool_bm25" === providerToolName) anthropicContent.push({ + type: "server_tool_use", + id: part.toolCallId, + name: providerToolName, + input: part.input, + cache_control: cacheControl + }); + else warnings.push({ + type: "other", + message: `provider executed tool call for tool ${part.toolName} is not supported` + }); + break; + } + const callerOptions = null == (_l = part.providerOptions) ? void 0 : _l.anthropic; + const caller = (null == callerOptions ? void 0 : callerOptions.caller) ? ("code_execution_20250825" === callerOptions.caller.type || "code_execution_20260120" === callerOptions.caller.type) && callerOptions.caller.toolId ? { + type: callerOptions.caller.type, + tool_id: callerOptions.caller.toolId + } : "direct" === callerOptions.caller.type ? { + type: "direct" + } : void 0 : void 0; + anthropicContent.push({ + type: "tool_use", + id: part.toolCallId, + name: part.toolName, + input: part.input, + ...caller && { + caller + }, + cache_control: cacheControl + }); + break; + } + case "tool-result": + { + const providerToolName = toolNameMapping.toProviderToolName(part.toolName); + if (mcpToolUseIds.has(part.toolCallId)) { + const output = part.output; + if ("json" !== output.type && "error-json" !== output.type) { + warnings.push({ + type: "other", + message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` + }); + break; + } + anthropicContent.push({ + type: "mcp_tool_result", + tool_use_id: part.toolCallId, + is_error: "error-json" === output.type, + content: output.value, + cache_control: cacheControl + }); + } else if ("code_execution" === providerToolName) { + const output = part.output; + if ("error-text" === output.type || "error-json" === output.type) { + let errorInfo = {}; + try { + if ("string" == typeof output.value) errorInfo = JSON.parse(output.value); + else if ("object" == typeof output.value && null !== output.value) errorInfo = output.value; + } catch (e) {} + if ("code_execution_tool_result_error" === errorInfo.type) anthropicContent.push({ + type: "code_execution_tool_result", + tool_use_id: part.toolCallId, + content: { + type: "code_execution_tool_result_error", + error_code: null != (_m = errorInfo.errorCode) ? _m : "unknown" + }, + cache_control: cacheControl + }); + else anthropicContent.push({ + type: "bash_code_execution_tool_result", + tool_use_id: part.toolCallId, + cache_control: cacheControl, + content: { + type: "bash_code_execution_tool_result_error", + error_code: null != (_n = errorInfo.errorCode) ? _n : "unknown" + } + }); + break; + } + if ("json" !== output.type) { + warnings.push({ + type: "other", + message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` + }); + break; + } + if (null == output.value || "object" != typeof output.value || !("type" in output.value) || "string" != typeof output.value.type) { + warnings.push({ + type: "other", + message: `provider executed tool result output value is not a valid code execution result for tool ${part.toolName}` + }); + break; + } + if ("code_execution_result" === output.value.type) { + const codeExecutionOutput = await dist_validateTypes({ + value: output.value, + schema: codeExecution_20250522OutputSchema + }); + anthropicContent.push({ + type: "code_execution_tool_result", + tool_use_id: part.toolCallId, + content: { + type: codeExecutionOutput.type, + stdout: codeExecutionOutput.stdout, + stderr: codeExecutionOutput.stderr, + return_code: codeExecutionOutput.return_code, + content: null != (_o = codeExecutionOutput.content) ? _o : [] + }, + cache_control: cacheControl + }); + } else if ("encrypted_code_execution_result" === output.value.type) { + const codeExecutionOutput = await dist_validateTypes({ + value: output.value, + schema: codeExecution_20260120OutputSchema + }); + if ("encrypted_code_execution_result" === codeExecutionOutput.type) anthropicContent.push({ + type: "code_execution_tool_result", + tool_use_id: part.toolCallId, + content: { + type: codeExecutionOutput.type, + encrypted_stdout: codeExecutionOutput.encrypted_stdout, + stderr: codeExecutionOutput.stderr, + return_code: codeExecutionOutput.return_code, + content: null != (_p = codeExecutionOutput.content) ? _p : [] + }, + cache_control: cacheControl + }); + } else { + const codeExecutionOutput = await dist_validateTypes({ + value: output.value, + schema: codeExecution_20250825OutputSchema + }); + if ("code_execution_result" === codeExecutionOutput.type) anthropicContent.push({ + type: "code_execution_tool_result", + tool_use_id: part.toolCallId, + content: { + type: codeExecutionOutput.type, + stdout: codeExecutionOutput.stdout, + stderr: codeExecutionOutput.stderr, + return_code: codeExecutionOutput.return_code, + content: null != (_q = codeExecutionOutput.content) ? _q : [] + }, + cache_control: cacheControl + }); + else if ("bash_code_execution_result" === codeExecutionOutput.type || "bash_code_execution_tool_result_error" === codeExecutionOutput.type) anthropicContent.push({ + type: "bash_code_execution_tool_result", + tool_use_id: part.toolCallId, + cache_control: cacheControl, + content: codeExecutionOutput + }); + else anthropicContent.push({ + type: "text_editor_code_execution_tool_result", + tool_use_id: part.toolCallId, + cache_control: cacheControl, + content: codeExecutionOutput + }); + } + break; + } + if ("web_fetch" === providerToolName) { + const output = part.output; + if ("error-json" === output.type) { + let errorValue = {}; + try { + if ("string" == typeof output.value) errorValue = JSON.parse(output.value); + else if ("object" == typeof output.value && null !== output.value) errorValue = output.value; + } catch (e) { + const extractedErrorCode = null == (_r = output.value) ? void 0 : _r.errorCode; + errorValue = { + errorCode: "string" == typeof extractedErrorCode ? extractedErrorCode : "unavailable" + }; + } + anthropicContent.push({ + type: "web_fetch_tool_result", + tool_use_id: part.toolCallId, + content: { + type: "web_fetch_tool_result_error", + error_code: null != (_s = errorValue.errorCode) ? _s : "unavailable" + }, + cache_control: cacheControl + }); + break; + } + if ("json" !== output.type) { + warnings.push({ + type: "other", + message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` + }); + break; + } + const webFetchOutput = await dist_validateTypes({ + value: output.value, + schema: webFetch_20250910OutputSchema + }); + anthropicContent.push({ + type: "web_fetch_tool_result", + tool_use_id: part.toolCallId, + content: { + type: "web_fetch_result", + url: webFetchOutput.url, + retrieved_at: webFetchOutput.retrievedAt, + content: { + type: "document", + title: webFetchOutput.content.title, + citations: webFetchOutput.content.citations, + source: { + type: webFetchOutput.content.source.type, + media_type: webFetchOutput.content.source.mediaType, + data: webFetchOutput.content.source.data + } + } + }, + cache_control: cacheControl + }); + break; + } + if ("web_search" === providerToolName) { + const output = part.output; + if ("json" !== output.type) { + warnings.push({ + type: "other", + message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` + }); + break; + } + const webSearchOutput = await dist_validateTypes({ + value: output.value, + schema: webSearch_20250305OutputSchema + }); + anthropicContent.push({ + type: "web_search_tool_result", + tool_use_id: part.toolCallId, + content: webSearchOutput.map((result)=>({ + url: result.url, + title: result.title, + page_age: result.pageAge, + encrypted_content: result.encryptedContent, + type: result.type + })), + cache_control: cacheControl + }); + break; + } + if ("tool_search_tool_regex" === providerToolName || "tool_search_tool_bm25" === providerToolName) { + const output = part.output; + if ("json" !== output.type) { + warnings.push({ + type: "other", + message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported` + }); + break; + } + const toolSearchOutput = await dist_validateTypes({ + value: output.value, + schema: toolSearchRegex_20251119OutputSchema + }); + const toolReferences = toolSearchOutput.map((ref)=>({ + type: "tool_reference", + tool_name: ref.toolName + })); + anthropicContent.push({ + type: "tool_search_tool_result", + tool_use_id: part.toolCallId, + content: { + type: "tool_search_tool_search_result", + tool_references: toolReferences + }, + cache_control: cacheControl + }); + break; + } + warnings.push({ + type: "other", + message: `provider executed tool result for tool ${part.toolName} is not supported` + }); + break; + } + } + } + } + messages.push({ + role: "assistant", + content: anthropicContent + }); + break; + } + default: + { + const _exhaustiveCheck = type; + throw new Error(`content type: ${_exhaustiveCheck}`); + } + } + } + return { + prompt: { + system, + messages + }, + betas + }; + } + function groupIntoBlocks(prompt) { + const blocks = []; + let currentBlock; + for (const message of prompt){ + const { role } = message; + switch(role){ + case "system": + if ((null == currentBlock ? void 0 : currentBlock.type) !== "system") { + currentBlock = { + type: "system", + messages: [] + }; + blocks.push(currentBlock); + } + currentBlock.messages.push(message); + break; + case "assistant": + if ((null == currentBlock ? void 0 : currentBlock.type) !== "assistant") { + currentBlock = { + type: "assistant", + messages: [] + }; + blocks.push(currentBlock); + } + currentBlock.messages.push(message); + break; + case "user": + if ((null == currentBlock ? void 0 : currentBlock.type) !== "user") { + currentBlock = { + type: "user", + messages: [] + }; + blocks.push(currentBlock); + } + currentBlock.messages.push(message); + break; + case "tool": + if ((null == currentBlock ? void 0 : currentBlock.type) !== "user") { + currentBlock = { + type: "user", + messages: [] + }; + blocks.push(currentBlock); + } + currentBlock.messages.push(message); + break; + default: + { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return blocks; + } + function mapAnthropicStopReason({ finishReason, isJsonResponseFromTool }) { + switch(finishReason){ + case "pause_turn": + case "end_turn": + case "stop_sequence": + return "stop"; + case "refusal": + return "content-filter"; + case "tool_use": + return isJsonResponseFromTool ? "stop" : "tool-calls"; + case "max_tokens": + case "model_context_window_exceeded": + return "length"; + case "compaction": + return "other"; + default: + return "other"; + } + } + function createCitationSource(citation, citationDocuments, generateId3) { + var _a; + if ("web_search_result_location" === citation.type) return { + type: "source", + sourceType: "url", + id: generateId3(), + url: citation.url, + title: citation.title, + providerMetadata: { + anthropic: { + citedText: citation.cited_text, + encryptedIndex: citation.encrypted_index + } + } + }; + if ("page_location" !== citation.type && "char_location" !== citation.type) return; + const documentInfo = citationDocuments[citation.document_index]; + if (!documentInfo) return; + return { + type: "source", + sourceType: "document", + id: generateId3(), + mediaType: documentInfo.mediaType, + title: null != (_a = citation.document_title) ? _a : documentInfo.title, + filename: documentInfo.filename, + providerMetadata: { + anthropic: "page_location" === citation.type ? { + citedText: citation.cited_text, + startPageNumber: citation.start_page_number, + endPageNumber: citation.end_page_number + } : { + citedText: citation.cited_text, + startCharIndex: citation.start_char_index, + endCharIndex: citation.end_char_index + } + } + }; + } + var AnthropicMessagesLanguageModel = class { + constructor(modelId, config){ + this.specificationVersion = "v3"; + var _a; + this.modelId = modelId; + this.config = config; + this.generateId = null != (_a = config.generateId) ? _a : generateId; + } + supportsUrl(url) { + return "https:" === url.protocol; + } + get provider() { + return this.config.provider; + } + get providerOptionsName() { + const provider = this.config.provider; + const dotIndex = provider.indexOf("."); + return -1 === dotIndex ? provider : provider.substring(0, dotIndex); + } + get supportedUrls() { + var _a, _b, _c; + return null != (_c = null == (_b = (_a = this.config).supportedUrls) ? void 0 : _b.call(_a)) ? _c : {}; + } + async getArgs({ userSuppliedBetas, prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions, stream }) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i; + const warnings = []; + if (null != frequencyPenalty) warnings.push({ + type: "unsupported", + feature: "frequencyPenalty" + }); + if (null != presencePenalty) warnings.push({ + type: "unsupported", + feature: "presencePenalty" + }); + if (null != seed) warnings.push({ + type: "unsupported", + feature: "seed" + }); + if (null != temperature && temperature > 1) { + warnings.push({ + type: "unsupported", + feature: "temperature", + details: `${temperature} exceeds anthropic maximum of 1.0. clamped to 1.0` + }); + temperature = 1; + } else if (null != temperature && temperature < 0) { + warnings.push({ + type: "unsupported", + feature: "temperature", + details: `${temperature} is below anthropic minimum of 0. clamped to 0` + }); + temperature = 0; + } + if ((null == responseFormat ? void 0 : responseFormat.type) === "json") { + if (null == responseFormat.schema) warnings.push({ + type: "unsupported", + feature: "responseFormat", + details: "JSON response format requires a schema. The response format is ignored." + }); + } + const providerOptionsName = this.providerOptionsName; + const canonicalOptions = await parseProviderOptions({ + provider: "anthropic", + providerOptions, + schema: anthropicLanguageModelOptions + }); + const customProviderOptions = "anthropic" !== providerOptionsName ? await parseProviderOptions({ + provider: providerOptionsName, + providerOptions, + schema: anthropicLanguageModelOptions + }) : null; + const usedCustomProviderKey = null != customProviderOptions; + const anthropicOptions = Object.assign({}, null != canonicalOptions ? canonicalOptions : {}, null != customProviderOptions ? customProviderOptions : {}); + const { maxOutputTokens: maxOutputTokensForModel, supportsStructuredOutput: modelSupportsStructuredOutput, isKnownModel } = getModelCapabilities(this.modelId); + const isAnthropicModel = isKnownModel || this.modelId.startsWith("claude-"); + const supportsStructuredOutput = (null != (_a = this.config.supportsNativeStructuredOutput) ? _a : true) && modelSupportsStructuredOutput; + const supportsStrictTools = (null != (_b = this.config.supportsStrictTools) ? _b : true) && modelSupportsStructuredOutput; + const structureOutputMode = null != (_c = null == anthropicOptions ? void 0 : anthropicOptions.structuredOutputMode) ? _c : "auto"; + const useStructuredOutput = "outputFormat" === structureOutputMode || "auto" === structureOutputMode && supportsStructuredOutput; + const jsonResponseTool = (null == responseFormat ? void 0 : responseFormat.type) !== "json" || null == responseFormat.schema || useStructuredOutput ? void 0 : { + type: "function", + name: "json", + description: "Respond with a JSON object.", + inputSchema: responseFormat.schema + }; + const contextManagement = null == anthropicOptions ? void 0 : anthropicOptions.contextManagement; + const cacheControlValidator = new CacheControlValidator(); + const toolNameMapping = createToolNameMapping({ + tools, + providerToolNames: { + "anthropic.code_execution_20250522": "code_execution", + "anthropic.code_execution_20250825": "code_execution", + "anthropic.code_execution_20260120": "code_execution", + "anthropic.computer_20241022": "computer", + "anthropic.computer_20250124": "computer", + "anthropic.text_editor_20241022": "str_replace_editor", + "anthropic.text_editor_20250124": "str_replace_editor", + "anthropic.text_editor_20250429": "str_replace_based_edit_tool", + "anthropic.text_editor_20250728": "str_replace_based_edit_tool", + "anthropic.bash_20241022": "bash", + "anthropic.bash_20250124": "bash", + "anthropic.memory_20250818": "memory", + "anthropic.web_search_20250305": "web_search", + "anthropic.web_search_20260209": "web_search", + "anthropic.web_fetch_20250910": "web_fetch", + "anthropic.web_fetch_20260209": "web_fetch", + "anthropic.tool_search_regex_20251119": "tool_search_tool_regex", + "anthropic.tool_search_bm25_20251119": "tool_search_tool_bm25" + } + }); + const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({ + prompt, + sendReasoning: null != (_d = null == anthropicOptions ? void 0 : anthropicOptions.sendReasoning) ? _d : true, + warnings, + cacheControlValidator, + toolNameMapping + }); + const thinkingType = null == (_e = null == anthropicOptions ? void 0 : anthropicOptions.thinking) ? void 0 : _e.type; + const isThinking = "enabled" === thinkingType || "adaptive" === thinkingType; + let thinkingBudget = "enabled" === thinkingType ? null == (_f = null == anthropicOptions ? void 0 : anthropicOptions.thinking) ? void 0 : _f.budgetTokens : void 0; + const maxTokens = null != maxOutputTokens ? maxOutputTokens : maxOutputTokensForModel; + const baseArgs = { + model: this.modelId, + max_tokens: maxTokens, + temperature, + top_k: topK, + top_p: topP, + stop_sequences: stopSequences, + ...isThinking && { + thinking: { + type: thinkingType, + ...null != thinkingBudget && { + budget_tokens: thinkingBudget + } + } + }, + ...((null == anthropicOptions ? void 0 : anthropicOptions.effort) || useStructuredOutput && (null == responseFormat ? void 0 : responseFormat.type) === "json" && null != responseFormat.schema) && { + output_config: { + ...(null == anthropicOptions ? void 0 : anthropicOptions.effort) && { + effort: anthropicOptions.effort + }, + ...useStructuredOutput && (null == responseFormat ? void 0 : responseFormat.type) === "json" && null != responseFormat.schema && { + format: { + type: "json_schema", + schema: responseFormat.schema + } + } + } + }, + ...(null == anthropicOptions ? void 0 : anthropicOptions.speed) && { + speed: anthropicOptions.speed + }, + ...(null == anthropicOptions ? void 0 : anthropicOptions.inferenceGeo) && { + inference_geo: anthropicOptions.inferenceGeo + }, + ...(null == anthropicOptions ? void 0 : anthropicOptions.cacheControl) && { + cache_control: anthropicOptions.cacheControl + }, + ...(null == (_g = null == anthropicOptions ? void 0 : anthropicOptions.metadata) ? void 0 : _g.userId) != null && { + metadata: { + user_id: anthropicOptions.metadata.userId + } + }, + ...(null == anthropicOptions ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0 && { + mcp_servers: anthropicOptions.mcpServers.map((server)=>({ + type: server.type, + name: server.name, + url: server.url, + authorization_token: server.authorizationToken, + tool_configuration: server.toolConfiguration ? { + allowed_tools: server.toolConfiguration.allowedTools, + enabled: server.toolConfiguration.enabled + } : void 0 + })) + }, + ...(null == anthropicOptions ? void 0 : anthropicOptions.container) && { + container: anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0 ? { + id: anthropicOptions.container.id, + skills: anthropicOptions.container.skills.map((skill)=>({ + type: skill.type, + skill_id: skill.skillId, + version: skill.version + })) + } : anthropicOptions.container.id + }, + system: messagesPrompt.system, + messages: messagesPrompt.messages, + ...contextManagement && { + context_management: { + edits: contextManagement.edits.map((edit)=>{ + const strategy = edit.type; + switch(strategy){ + case "clear_tool_uses_20250919": + return { + type: edit.type, + ...void 0 !== edit.trigger && { + trigger: edit.trigger + }, + ...void 0 !== edit.keep && { + keep: edit.keep + }, + ...void 0 !== edit.clearAtLeast && { + clear_at_least: edit.clearAtLeast + }, + ...void 0 !== edit.clearToolInputs && { + clear_tool_inputs: edit.clearToolInputs + }, + ...void 0 !== edit.excludeTools && { + exclude_tools: edit.excludeTools + } + }; + case "clear_thinking_20251015": + return { + type: edit.type, + ...void 0 !== edit.keep && { + keep: edit.keep + } + }; + case "compact_20260112": + return { + type: edit.type, + ...void 0 !== edit.trigger && { + trigger: edit.trigger + }, + ...void 0 !== edit.pauseAfterCompaction && { + pause_after_compaction: edit.pauseAfterCompaction + }, + ...void 0 !== edit.instructions && { + instructions: edit.instructions + } + }; + default: + warnings.push({ + type: "other", + message: `Unknown context management strategy: ${strategy}` + }); + return; + } + }).filter((edit)=>void 0 !== edit) + } + } + }; + if (isThinking) { + if ("enabled" === thinkingType && null == thinkingBudget) { + warnings.push({ + type: "compatibility", + feature: "extended thinking", + details: "thinking budget is required when thinking is enabled. using default budget of 1024 tokens." + }); + baseArgs.thinking = { + type: "enabled", + budget_tokens: 1024 + }; + thinkingBudget = 1024; + } + if (null != baseArgs.temperature) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported", + feature: "temperature", + details: "temperature is not supported when thinking is enabled" + }); + } + if (null != topK) { + baseArgs.top_k = void 0; + warnings.push({ + type: "unsupported", + feature: "topK", + details: "topK is not supported when thinking is enabled" + }); + } + if (null != topP) { + baseArgs.top_p = void 0; + warnings.push({ + type: "unsupported", + feature: "topP", + details: "topP is not supported when thinking is enabled" + }); + } + baseArgs.max_tokens = maxTokens + (null != thinkingBudget ? thinkingBudget : 0); + } else if (isAnthropicModel && null != topP && null != temperature) { + warnings.push({ + type: "unsupported", + feature: "topP", + details: "topP is not supported when temperature is set. topP is ignored." + }); + baseArgs.top_p = void 0; + } + if (isKnownModel && baseArgs.max_tokens > maxOutputTokensForModel) { + if (null != maxOutputTokens) warnings.push({ + type: "unsupported", + feature: "maxOutputTokens", + details: `${baseArgs.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${maxOutputTokensForModel} max output tokens. The max output tokens have been limited to ${maxOutputTokensForModel}.` + }); + baseArgs.max_tokens = maxOutputTokensForModel; + } + if ((null == anthropicOptions ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0) betas.add("mcp-client-2025-04-04"); + if (contextManagement) { + betas.add("context-management-2025-06-27"); + if (contextManagement.edits.some((e)=>"compact_20260112" === e.type)) betas.add("compact-2026-01-12"); + } + if ((null == anthropicOptions ? void 0 : anthropicOptions.container) && anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0) { + betas.add("code-execution-2025-08-25"); + betas.add("skills-2025-10-02"); + betas.add("files-api-2025-04-14"); + if (!(null == tools ? void 0 : tools.some((tool)=>"provider" === tool.type && ("anthropic.code_execution_20250825" === tool.id || "anthropic.code_execution_20260120" === tool.id)))) warnings.push({ + type: "other", + message: "code execution tool is required when using skills" + }); + } + if (null == anthropicOptions ? void 0 : anthropicOptions.effort) betas.add("effort-2025-11-24"); + if ((null == anthropicOptions ? void 0 : anthropicOptions.speed) === "fast") betas.add("fast-mode-2026-02-01"); + if (stream && (null != (_h = null == anthropicOptions ? void 0 : anthropicOptions.toolStreaming) ? _h : true)) betas.add("fine-grained-tool-streaming-2025-05-14"); + const { tools: anthropicTools2, toolChoice: anthropicToolChoice, toolWarnings, betas: toolsBetas } = await prepareTools(null != jsonResponseTool ? { + tools: [ + ...null != tools ? tools : [], + jsonResponseTool + ], + toolChoice: { + type: "required" + }, + disableParallelToolUse: true, + cacheControlValidator, + supportsStructuredOutput: false, + supportsStrictTools + } : { + tools: null != tools ? tools : [], + toolChoice, + disableParallelToolUse: null == anthropicOptions ? void 0 : anthropicOptions.disableParallelToolUse, + cacheControlValidator, + supportsStructuredOutput, + supportsStrictTools + }); + const cacheWarnings = cacheControlValidator.getWarnings(); + return { + args: { + ...baseArgs, + tools: anthropicTools2, + tool_choice: anthropicToolChoice, + stream: true === stream ? true : void 0 + }, + warnings: [ + ...warnings, + ...toolWarnings, + ...cacheWarnings + ], + betas: /* @__PURE__ */ new Set([ + ...betas, + ...toolsBetas, + ...userSuppliedBetas, + ...null != (_i = null == anthropicOptions ? void 0 : anthropicOptions.anthropicBeta) ? _i : [] + ]), + usesJsonResponseTool: null != jsonResponseTool, + toolNameMapping, + providerOptionsName, + usedCustomProviderKey + }; + } + async getHeaders({ betas, headers }) { + return combineHeaders(await dist_resolve(this.config.headers), headers, betas.size > 0 ? { + "anthropic-beta": Array.from(betas).join(",") + } : {}); + } + async getBetasFromHeaders(requestHeaders) { + var _a, _b; + const configHeaders = await dist_resolve(this.config.headers); + const configBetaHeader = null != (_a = configHeaders["anthropic-beta"]) ? _a : ""; + const requestBetaHeader = null != (_b = null == requestHeaders ? void 0 : requestHeaders["anthropic-beta"]) ? _b : ""; + return new Set([ + ...configBetaHeader.toLowerCase().split(","), + ...requestBetaHeader.toLowerCase().split(",") + ].map((beta)=>beta.trim()).filter((beta)=>"" !== beta)); + } + buildRequestUrl(isStreaming) { + var _a, _b, _c; + return null != (_c = null == (_b = (_a = this.config).buildRequestUrl) ? void 0 : _b.call(_a, this.config.baseURL, isStreaming)) ? _c : `${this.config.baseURL}/messages`; + } + transformRequestBody(args, betas) { + var _a, _b, _c; + return null != (_c = null == (_b = (_a = this.config).transformRequestBody) ? void 0 : _b.call(_a, args, betas)) ? _c : args; + } + extractCitationDocuments(prompt) { + const isCitationPart = (part)=>{ + var _a, _b; + if ("file" !== part.type) return false; + if ("application/pdf" !== part.mediaType && "text/plain" !== part.mediaType) return false; + const anthropic2 = null == (_a = part.providerOptions) ? void 0 : _a.anthropic; + const citationsConfig = null == anthropic2 ? void 0 : anthropic2.citations; + return null != (_b = null == citationsConfig ? void 0 : citationsConfig.enabled) ? _b : false; + }; + return prompt.filter((message)=>"user" === message.role).flatMap((message)=>message.content).filter(isCitationPart).map((part)=>{ + var _a; + const filePart = part; + return { + title: null != (_a = filePart.filename) ? _a : "Untitled Document", + filename: filePart.filename, + mediaType: filePart.mediaType + }; + }); + } + async doGenerate(options1) { + var _a, _b, _c, _d, _e, _f, _g; + const { args, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({ + ...options1, + stream: false, + userSuppliedBetas: await this.getBetasFromHeaders(options1.headers) + }); + const citationDocuments = [ + ...this.extractCitationDocuments(options1.prompt) + ]; + const markCodeExecutionDynamic = hasWebTool20260209WithoutCodeExecution(args.tools); + const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({ + url: this.buildRequestUrl(false), + headers: await this.getHeaders({ + betas, + headers: options1.headers + }), + body: this.transformRequestBody(args, betas), + failedResponseHandler: anthropicFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(anthropicMessagesResponseSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + const content = []; + const mcpToolCalls = {}; + const serverToolCalls = {}; + let isJsonResponseFromTool = false; + for (const part of response.content)switch(part.type){ + case "text": + if (!usesJsonResponseTool) { + content.push({ + type: "text", + text: part.text + }); + if (part.citations) for (const citation of part.citations){ + const source = createCitationSource(citation, citationDocuments, this.generateId); + if (source) content.push(source); + } + } + break; + case "thinking": + content.push({ + type: "reasoning", + text: part.thinking, + providerMetadata: { + anthropic: { + signature: part.signature + } + } + }); + break; + case "redacted_thinking": + content.push({ + type: "reasoning", + text: "", + providerMetadata: { + anthropic: { + redactedData: part.data + } + } + }); + break; + case "compaction": + content.push({ + type: "text", + text: part.content, + providerMetadata: { + anthropic: { + type: "compaction" + } + } + }); + break; + case "tool_use": + { + const isJsonResponseTool = usesJsonResponseTool && "json" === part.name; + if (isJsonResponseTool) { + isJsonResponseFromTool = true; + content.push({ + type: "text", + text: JSON.stringify(part.input) + }); + } else { + const caller = part.caller; + const callerInfo = caller ? { + type: caller.type, + toolId: "tool_id" in caller ? caller.tool_id : void 0 + } : void 0; + content.push({ + type: "tool-call", + toolCallId: part.id, + toolName: part.name, + input: JSON.stringify(part.input), + ...callerInfo && { + providerMetadata: { + anthropic: { + caller: callerInfo + } + } + } + }); + } + break; + } + case "server_tool_use": + if ("text_editor_code_execution" === part.name || "bash_code_execution" === part.name) content.push({ + type: "tool-call", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName("code_execution"), + input: JSON.stringify({ + type: part.name, + ...part.input + }), + providerExecuted: true + }); + else if ("web_search" === part.name || "code_execution" === part.name || "web_fetch" === part.name) { + const inputToSerialize = "code_execution" === part.name && null != part.input && "object" == typeof part.input && "code" in part.input && !("type" in part.input) ? { + type: "programmatic-tool-call", + ...part.input + } : part.input; + content.push({ + type: "tool-call", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName(part.name), + input: JSON.stringify(inputToSerialize), + providerExecuted: true, + ...markCodeExecutionDynamic && "code_execution" === part.name ? { + dynamic: true + } : {} + }); + } else if ("tool_search_tool_regex" === part.name || "tool_search_tool_bm25" === part.name) { + serverToolCalls[part.id] = part.name; + content.push({ + type: "tool-call", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName(part.name), + input: JSON.stringify(part.input), + providerExecuted: true + }); + } + break; + case "mcp_tool_use": + mcpToolCalls[part.id] = { + type: "tool-call", + toolCallId: part.id, + toolName: part.name, + input: JSON.stringify(part.input), + providerExecuted: true, + dynamic: true, + providerMetadata: { + anthropic: { + type: "mcp-tool-use", + serverName: part.server_name + } + } + }; + content.push(mcpToolCalls[part.id]); + break; + case "mcp_tool_result": + content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: mcpToolCalls[part.tool_use_id].toolName, + isError: part.is_error, + result: part.content, + dynamic: true, + providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata + }); + break; + case "web_fetch_tool_result": + if ("web_fetch_result" === part.content.type) { + citationDocuments.push({ + title: null != (_a = part.content.content.title) ? _a : part.content.url, + mediaType: part.content.content.source.media_type + }); + content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("web_fetch"), + result: { + type: "web_fetch_result", + url: part.content.url, + retrievedAt: part.content.retrieved_at, + content: { + type: part.content.content.type, + title: part.content.content.title, + citations: part.content.content.citations, + source: { + type: part.content.content.source.type, + mediaType: part.content.content.source.media_type, + data: part.content.content.source.data + } + } + } + }); + } else if ("web_fetch_tool_result_error" === part.content.type) content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("web_fetch"), + isError: true, + result: { + type: "web_fetch_tool_result_error", + errorCode: part.content.error_code + } + }); + break; + case "web_search_tool_result": + if (Array.isArray(part.content)) { + content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("web_search"), + result: part.content.map((result)=>{ + var _a2; + return { + url: result.url, + title: result.title, + pageAge: null != (_a2 = result.page_age) ? _a2 : null, + encryptedContent: result.encrypted_content, + type: result.type + }; + }) + }); + for (const result of part.content)content.push({ + type: "source", + sourceType: "url", + id: this.generateId(), + url: result.url, + title: result.title, + providerMetadata: { + anthropic: { + pageAge: null != (_b = result.page_age) ? _b : null + } + } + }); + } else content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("web_search"), + isError: true, + result: { + type: "web_search_tool_result_error", + errorCode: part.content.error_code + } + }); + break; + case "code_execution_tool_result": + if ("code_execution_result" === part.content.type) content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("code_execution"), + result: { + type: part.content.type, + stdout: part.content.stdout, + stderr: part.content.stderr, + return_code: part.content.return_code, + content: null != (_c = part.content.content) ? _c : [] + } + }); + else if ("encrypted_code_execution_result" === part.content.type) content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("code_execution"), + result: { + type: part.content.type, + encrypted_stdout: part.content.encrypted_stdout, + stderr: part.content.stderr, + return_code: part.content.return_code, + content: null != (_d = part.content.content) ? _d : [] + } + }); + else if ("code_execution_tool_result_error" === part.content.type) content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("code_execution"), + isError: true, + result: { + type: "code_execution_tool_result_error", + errorCode: part.content.error_code + } + }); + break; + case "bash_code_execution_tool_result": + case "text_editor_code_execution_tool_result": + content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("code_execution"), + result: part.content + }); + break; + case "tool_search_tool_result": + { + let providerToolName = serverToolCalls[part.tool_use_id]; + if (null == providerToolName) { + const bm25CustomName = toolNameMapping.toCustomToolName("tool_search_tool_bm25"); + toolNameMapping.toCustomToolName("tool_search_tool_regex"); + providerToolName = "tool_search_tool_bm25" !== bm25CustomName ? "tool_search_tool_bm25" : "tool_search_tool_regex"; + } + if ("tool_search_tool_search_result" === part.content.type) content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName(providerToolName), + result: part.content.tool_references.map((ref)=>({ + type: ref.type, + toolName: ref.tool_name + })) + }); + else content.push({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName(providerToolName), + isError: true, + result: { + type: "tool_search_tool_result_error", + errorCode: part.content.error_code + } + }); + break; + } + } + return { + content, + finishReason: { + unified: mapAnthropicStopReason({ + finishReason: response.stop_reason, + isJsonResponseFromTool + }), + raw: null != (_e = response.stop_reason) ? _e : void 0 + }, + usage: convertAnthropicMessagesUsage({ + usage: response.usage + }), + request: { + body: args + }, + response: { + id: null != (_f = response.id) ? _f : void 0, + modelId: null != (_g = response.model) ? _g : void 0, + headers: responseHeaders, + body: rawResponse + }, + warnings, + providerMetadata: (()=>{ + var _a2, _b2, _c2, _d2, _e2; + const anthropicMetadata = { + usage: response.usage, + cacheCreationInputTokens: null != (_a2 = response.usage.cache_creation_input_tokens) ? _a2 : null, + stopSequence: null != (_b2 = response.stop_sequence) ? _b2 : null, + iterations: response.usage.iterations ? response.usage.iterations.map((iter)=>({ + type: iter.type, + inputTokens: iter.input_tokens, + outputTokens: iter.output_tokens + })) : null, + container: response.container ? { + expiresAt: response.container.expires_at, + id: response.container.id, + skills: null != (_d2 = null == (_c2 = response.container.skills) ? void 0 : _c2.map((skill)=>({ + type: skill.type, + skillId: skill.skill_id, + version: skill.version + }))) ? _d2 : null + } : null, + contextManagement: null != (_e2 = mapAnthropicResponseContextManagement(response.context_management)) ? _e2 : null + }; + const providerMetadata = { + anthropic: anthropicMetadata + }; + if (usedCustomProviderKey && "anthropic" !== providerOptionsName) providerMetadata[providerOptionsName] = anthropicMetadata; + return providerMetadata; + })() + }; + } + async doStream(options1) { + var _a, _b; + const { args: body, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({ + ...options1, + stream: true, + userSuppliedBetas: await this.getBetasFromHeaders(options1.headers) + }); + const citationDocuments = [ + ...this.extractCitationDocuments(options1.prompt) + ]; + const markCodeExecutionDynamic = hasWebTool20260209WithoutCodeExecution(body.tools); + const url = this.buildRequestUrl(true); + const { responseHeaders, value: response } = await postJsonToApi({ + url, + headers: await this.getHeaders({ + betas, + headers: options1.headers + }), + body: this.transformRequestBody(body, betas), + failedResponseHandler: anthropicFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler(anthropicMessagesChunkSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + let finishReason = { + unified: "other", + raw: void 0 + }; + const usage = { + input_tokens: 0, + output_tokens: 0, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + iterations: null + }; + const contentBlocks = {}; + const mcpToolCalls = {}; + const serverToolCalls = {}; + let contextManagement = null; + let rawUsage; + let cacheCreationInputTokens = null; + let stopSequence = null; + let container = null; + let isJsonResponseFromTool = false; + let blockType; + const generateId3 = this.generateId; + const transformedStream = response.pipeThrough(new TransformStream({ + start (controller) { + controller.enqueue({ + type: "stream-start", + warnings + }); + }, + transform (chunk, controller) { + var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n; + if (options1.includeRawChunks) controller.enqueue({ + type: "raw", + rawValue: chunk.rawValue + }); + if (!chunk.success) return void controller.enqueue({ + type: "error", + error: chunk.error + }); + const value1 = chunk.value; + switch(value1.type){ + case "ping": + return; + case "content_block_start": + { + const part = value1.content_block; + const contentBlockType = part.type; + blockType = contentBlockType; + switch(contentBlockType){ + case "text": + if (usesJsonResponseTool) return; + contentBlocks[value1.index] = { + type: "text" + }; + controller.enqueue({ + type: "text-start", + id: String(value1.index) + }); + return; + case "thinking": + contentBlocks[value1.index] = { + type: "reasoning" + }; + controller.enqueue({ + type: "reasoning-start", + id: String(value1.index) + }); + return; + case "redacted_thinking": + contentBlocks[value1.index] = { + type: "reasoning" + }; + controller.enqueue({ + type: "reasoning-start", + id: String(value1.index), + providerMetadata: { + anthropic: { + redactedData: part.data + } + } + }); + return; + case "compaction": + contentBlocks[value1.index] = { + type: "text" + }; + controller.enqueue({ + type: "text-start", + id: String(value1.index), + providerMetadata: { + anthropic: { + type: "compaction" + } + } + }); + return; + case "tool_use": + { + const isJsonResponseTool = usesJsonResponseTool && "json" === part.name; + if (isJsonResponseTool) { + isJsonResponseFromTool = true; + contentBlocks[value1.index] = { + type: "text" + }; + controller.enqueue({ + type: "text-start", + id: String(value1.index) + }); + } else { + const caller = part.caller; + const callerInfo = caller ? { + type: caller.type, + toolId: "tool_id" in caller ? caller.tool_id : void 0 + } : void 0; + const hasNonEmptyInput = part.input && Object.keys(part.input).length > 0; + const initialInput = hasNonEmptyInput ? JSON.stringify(part.input) : ""; + contentBlocks[value1.index] = { + type: "tool-call", + toolCallId: part.id, + toolName: part.name, + input: initialInput, + firstDelta: 0 === initialInput.length, + ...callerInfo && { + caller: callerInfo + } + }; + controller.enqueue({ + type: "tool-input-start", + id: part.id, + toolName: part.name + }); + } + return; + } + case "server_tool_use": + if ([ + "web_fetch", + "web_search", + "code_execution", + "text_editor_code_execution", + "bash_code_execution" + ].includes(part.name)) { + const providerToolName = "text_editor_code_execution" === part.name || "bash_code_execution" === part.name ? "code_execution" : part.name; + const customToolName = toolNameMapping.toCustomToolName(providerToolName); + const finalInput = null != part.input && "object" == typeof part.input && Object.keys(part.input).length > 0 ? JSON.stringify(part.input) : ""; + contentBlocks[value1.index] = { + type: "tool-call", + toolCallId: part.id, + toolName: customToolName, + input: finalInput, + providerExecuted: true, + ...markCodeExecutionDynamic && "code_execution" === providerToolName ? { + dynamic: true + } : {}, + firstDelta: true, + providerToolName: part.name + }; + controller.enqueue({ + type: "tool-input-start", + id: part.id, + toolName: customToolName, + providerExecuted: true, + ...markCodeExecutionDynamic && "code_execution" === providerToolName ? { + dynamic: true + } : {} + }); + } else if ("tool_search_tool_regex" === part.name || "tool_search_tool_bm25" === part.name) { + serverToolCalls[part.id] = part.name; + const customToolName = toolNameMapping.toCustomToolName(part.name); + contentBlocks[value1.index] = { + type: "tool-call", + toolCallId: part.id, + toolName: customToolName, + input: "", + providerExecuted: true, + firstDelta: true, + providerToolName: part.name + }; + controller.enqueue({ + type: "tool-input-start", + id: part.id, + toolName: customToolName, + providerExecuted: true + }); + } + return; + case "web_fetch_tool_result": + if ("web_fetch_result" === part.content.type) { + citationDocuments.push({ + title: null != (_a2 = part.content.content.title) ? _a2 : part.content.url, + mediaType: part.content.content.source.media_type + }); + controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("web_fetch"), + result: { + type: "web_fetch_result", + url: part.content.url, + retrievedAt: part.content.retrieved_at, + content: { + type: part.content.content.type, + title: part.content.content.title, + citations: part.content.content.citations, + source: { + type: part.content.content.source.type, + mediaType: part.content.content.source.media_type, + data: part.content.content.source.data + } + } + } + }); + } else if ("web_fetch_tool_result_error" === part.content.type) controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("web_fetch"), + isError: true, + result: { + type: "web_fetch_tool_result_error", + errorCode: part.content.error_code + } + }); + return; + case "web_search_tool_result": + if (Array.isArray(part.content)) { + controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("web_search"), + result: part.content.map((result)=>{ + var _a3; + return { + url: result.url, + title: result.title, + pageAge: null != (_a3 = result.page_age) ? _a3 : null, + encryptedContent: result.encrypted_content, + type: result.type + }; + }) + }); + for (const result of part.content)controller.enqueue({ + type: "source", + sourceType: "url", + id: generateId3(), + url: result.url, + title: result.title, + providerMetadata: { + anthropic: { + pageAge: null != (_b2 = result.page_age) ? _b2 : null + } + } + }); + } else controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("web_search"), + isError: true, + result: { + type: "web_search_tool_result_error", + errorCode: part.content.error_code + } + }); + return; + case "code_execution_tool_result": + if ("code_execution_result" === part.content.type) controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("code_execution"), + result: { + type: part.content.type, + stdout: part.content.stdout, + stderr: part.content.stderr, + return_code: part.content.return_code, + content: null != (_c = part.content.content) ? _c : [] + } + }); + else if ("encrypted_code_execution_result" === part.content.type) controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("code_execution"), + result: { + type: part.content.type, + encrypted_stdout: part.content.encrypted_stdout, + stderr: part.content.stderr, + return_code: part.content.return_code, + content: null != (_d = part.content.content) ? _d : [] + } + }); + else if ("code_execution_tool_result_error" === part.content.type) controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("code_execution"), + isError: true, + result: { + type: "code_execution_tool_result_error", + errorCode: part.content.error_code + } + }); + return; + case "bash_code_execution_tool_result": + case "text_editor_code_execution_tool_result": + return void controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName("code_execution"), + result: part.content + }); + case "tool_search_tool_result": + { + let providerToolName = serverToolCalls[part.tool_use_id]; + if (null == providerToolName) { + const bm25CustomName = toolNameMapping.toCustomToolName("tool_search_tool_bm25"); + toolNameMapping.toCustomToolName("tool_search_tool_regex"); + providerToolName = "tool_search_tool_bm25" !== bm25CustomName ? "tool_search_tool_bm25" : "tool_search_tool_regex"; + } + if ("tool_search_tool_search_result" === part.content.type) controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName(providerToolName), + result: part.content.tool_references.map((ref)=>({ + type: ref.type, + toolName: ref.tool_name + })) + }); + else controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: toolNameMapping.toCustomToolName(providerToolName), + isError: true, + result: { + type: "tool_search_tool_result_error", + errorCode: part.content.error_code + } + }); + return; + } + case "mcp_tool_use": + mcpToolCalls[part.id] = { + type: "tool-call", + toolCallId: part.id, + toolName: part.name, + input: JSON.stringify(part.input), + providerExecuted: true, + dynamic: true, + providerMetadata: { + anthropic: { + type: "mcp-tool-use", + serverName: part.server_name + } + } + }; + controller.enqueue(mcpToolCalls[part.id]); + return; + case "mcp_tool_result": + return void controller.enqueue({ + type: "tool-result", + toolCallId: part.tool_use_id, + toolName: mcpToolCalls[part.tool_use_id].toolName, + isError: part.is_error, + result: part.content, + dynamic: true, + providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata + }); + default: + { + const _exhaustiveCheck = contentBlockType; + throw new Error(`Unsupported content block type: ${_exhaustiveCheck}`); + } + } + } + case "content_block_stop": + if (null != contentBlocks[value1.index]) { + const contentBlock = contentBlocks[value1.index]; + switch(contentBlock.type){ + case "text": + controller.enqueue({ + type: "text-end", + id: String(value1.index) + }); + break; + case "reasoning": + controller.enqueue({ + type: "reasoning-end", + id: String(value1.index) + }); + break; + case "tool-call": + const isJsonResponseTool = usesJsonResponseTool && "json" === contentBlock.toolName; + if (!isJsonResponseTool) { + controller.enqueue({ + type: "tool-input-end", + id: contentBlock.toolCallId + }); + let finalInput = "" === contentBlock.input ? "{}" : contentBlock.input; + if ("code_execution" === contentBlock.providerToolName) try { + const parsed = JSON.parse(finalInput); + if (null != parsed && "object" == typeof parsed && "code" in parsed && !("type" in parsed)) finalInput = JSON.stringify({ + type: "programmatic-tool-call", + ...parsed + }); + } catch (e) {} + controller.enqueue({ + type: "tool-call", + toolCallId: contentBlock.toolCallId, + toolName: contentBlock.toolName, + input: finalInput, + providerExecuted: contentBlock.providerExecuted, + ...markCodeExecutionDynamic && "code_execution" === contentBlock.providerToolName ? { + dynamic: true + } : {}, + ...contentBlock.caller && { + providerMetadata: { + anthropic: { + caller: contentBlock.caller + } + } + } + }); + } + break; + } + delete contentBlocks[value1.index]; + } + blockType = void 0; + return; + case "content_block_delta": + { + const deltaType = value1.delta.type; + switch(deltaType){ + case "text_delta": + if (usesJsonResponseTool) return; + controller.enqueue({ + type: "text-delta", + id: String(value1.index), + delta: value1.delta.text + }); + return; + case "thinking_delta": + return void controller.enqueue({ + type: "reasoning-delta", + id: String(value1.index), + delta: value1.delta.thinking + }); + case "signature_delta": + if ("thinking" === blockType) controller.enqueue({ + type: "reasoning-delta", + id: String(value1.index), + delta: "", + providerMetadata: { + anthropic: { + signature: value1.delta.signature + } + } + }); + return; + case "compaction_delta": + if (null != value1.delta.content) controller.enqueue({ + type: "text-delta", + id: String(value1.index), + delta: value1.delta.content + }); + return; + case "input_json_delta": + { + const contentBlock = contentBlocks[value1.index]; + let delta = value1.delta.partial_json; + if (0 === delta.length) return; + if (isJsonResponseFromTool) { + if ((null == contentBlock ? void 0 : contentBlock.type) !== "text") return; + controller.enqueue({ + type: "text-delta", + id: String(value1.index), + delta + }); + } else { + if ((null == contentBlock ? void 0 : contentBlock.type) !== "tool-call") return; + if (contentBlock.firstDelta && ("bash_code_execution" === contentBlock.providerToolName || "text_editor_code_execution" === contentBlock.providerToolName)) delta = `{"type": "${contentBlock.providerToolName}",${delta.substring(1)}`; + controller.enqueue({ + type: "tool-input-delta", + id: contentBlock.toolCallId, + delta + }); + contentBlock.input += delta; + contentBlock.firstDelta = false; + } + return; + } + case "citations_delta": + { + const citation = value1.delta.citation; + const source = createCitationSource(citation, citationDocuments, generateId3); + if (source) controller.enqueue(source); + return; + } + default: + { + const _exhaustiveCheck = deltaType; + throw new Error(`Unsupported delta type: ${_exhaustiveCheck}`); + } + } + } + case "message_start": + usage.input_tokens = value1.message.usage.input_tokens; + usage.cache_read_input_tokens = null != (_e = value1.message.usage.cache_read_input_tokens) ? _e : 0; + usage.cache_creation_input_tokens = null != (_f = value1.message.usage.cache_creation_input_tokens) ? _f : 0; + rawUsage = { + ...value1.message.usage + }; + cacheCreationInputTokens = null != (_g = value1.message.usage.cache_creation_input_tokens) ? _g : null; + if (null != value1.message.container) container = { + expiresAt: value1.message.container.expires_at, + id: value1.message.container.id, + skills: null + }; + if (null != value1.message.stop_reason) finishReason = { + unified: mapAnthropicStopReason({ + finishReason: value1.message.stop_reason, + isJsonResponseFromTool + }), + raw: value1.message.stop_reason + }; + controller.enqueue({ + type: "response-metadata", + id: null != (_h = value1.message.id) ? _h : void 0, + modelId: null != (_i = value1.message.model) ? _i : void 0 + }); + if (null != value1.message.content) for(let contentIndex = 0; contentIndex < value1.message.content.length; contentIndex++){ + const part = value1.message.content[contentIndex]; + if ("tool_use" === part.type) { + const caller = part.caller; + const callerInfo = caller ? { + type: caller.type, + toolId: "tool_id" in caller ? caller.tool_id : void 0 + } : void 0; + controller.enqueue({ + type: "tool-input-start", + id: part.id, + toolName: part.name + }); + const inputStr = JSON.stringify(null != (_j = part.input) ? _j : {}); + controller.enqueue({ + type: "tool-input-delta", + id: part.id, + delta: inputStr + }); + controller.enqueue({ + type: "tool-input-end", + id: part.id + }); + controller.enqueue({ + type: "tool-call", + toolCallId: part.id, + toolName: part.name, + input: inputStr, + ...callerInfo && { + providerMetadata: { + anthropic: { + caller: callerInfo + } + } + } + }); + } + } + return; + case "message_delta": + if (null != value1.usage.input_tokens && usage.input_tokens !== value1.usage.input_tokens) usage.input_tokens = value1.usage.input_tokens; + usage.output_tokens = value1.usage.output_tokens; + if (null != value1.usage.cache_read_input_tokens) usage.cache_read_input_tokens = value1.usage.cache_read_input_tokens; + if (null != value1.usage.cache_creation_input_tokens) { + usage.cache_creation_input_tokens = value1.usage.cache_creation_input_tokens; + cacheCreationInputTokens = value1.usage.cache_creation_input_tokens; + } + if (null != value1.usage.iterations) usage.iterations = value1.usage.iterations; + finishReason = { + unified: mapAnthropicStopReason({ + finishReason: value1.delta.stop_reason, + isJsonResponseFromTool + }), + raw: null != (_k = value1.delta.stop_reason) ? _k : void 0 + }; + stopSequence = null != (_l = value1.delta.stop_sequence) ? _l : null; + container = null != value1.delta.container ? { + expiresAt: value1.delta.container.expires_at, + id: value1.delta.container.id, + skills: null != (_n = null == (_m = value1.delta.container.skills) ? void 0 : _m.map((skill)=>({ + type: skill.type, + skillId: skill.skill_id, + version: skill.version + }))) ? _n : null + } : null; + if (value1.context_management) contextManagement = mapAnthropicResponseContextManagement(value1.context_management); + rawUsage = { + ...rawUsage, + ...value1.usage + }; + return; + case "message_stop": + { + const anthropicMetadata = { + usage: null != rawUsage ? rawUsage : null, + cacheCreationInputTokens, + stopSequence, + iterations: usage.iterations ? usage.iterations.map((iter)=>({ + type: iter.type, + inputTokens: iter.input_tokens, + outputTokens: iter.output_tokens + })) : null, + container, + contextManagement + }; + const providerMetadata = { + anthropic: anthropicMetadata + }; + if (usedCustomProviderKey && "anthropic" !== providerOptionsName) providerMetadata[providerOptionsName] = anthropicMetadata; + controller.enqueue({ + type: "finish", + finishReason, + usage: convertAnthropicMessagesUsage({ + usage, + rawUsage + }), + providerMetadata + }); + return; + } + case "error": + return void controller.enqueue({ + type: "error", + error: value1.error + }); + default: + { + const _exhaustiveCheck = value1; + throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`); + } + } + } + })); + const [streamForFirstChunk, streamForConsumer] = transformedStream.tee(); + const firstChunkReader = streamForFirstChunk.getReader(); + try { + await firstChunkReader.read(); + let result = await firstChunkReader.read(); + if ((null == (_a = result.value) ? void 0 : _a.type) === "raw") result = await firstChunkReader.read(); + if ((null == (_b = result.value) ? void 0 : _b.type) === "error") { + const error = result.value.error; + throw new APICallError({ + message: error.message, + url, + requestBodyValues: body, + statusCode: "overloaded_error" === error.type ? 529 : 500, + responseHeaders, + responseBody: JSON.stringify(error), + isRetryable: "overloaded_error" === error.type + }); + } + } finally{ + firstChunkReader.cancel().catch(()=>{}); + firstChunkReader.releaseLock(); + } + return { + stream: streamForConsumer, + request: { + body + }, + response: { + headers: responseHeaders + } + }; + } + }; + function getModelCapabilities(modelId) { + if (modelId.includes("claude-sonnet-4-6") || modelId.includes("claude-opus-4-6")) return { + maxOutputTokens: 128e3, + supportsStructuredOutput: true, + isKnownModel: true + }; + if (modelId.includes("claude-sonnet-4-5") || modelId.includes("claude-opus-4-5") || modelId.includes("claude-haiku-4-5")) return { + maxOutputTokens: 64e3, + supportsStructuredOutput: true, + isKnownModel: true + }; + if (modelId.includes("claude-opus-4-1")) return { + maxOutputTokens: 32e3, + supportsStructuredOutput: true, + isKnownModel: true + }; + if (modelId.includes("claude-sonnet-4-")) return { + maxOutputTokens: 64e3, + supportsStructuredOutput: false, + isKnownModel: true + }; + if (modelId.includes("claude-opus-4-")) return { + maxOutputTokens: 32e3, + supportsStructuredOutput: false, + isKnownModel: true + }; + else if (modelId.includes("claude-3-haiku")) return { + maxOutputTokens: 4096, + supportsStructuredOutput: false, + isKnownModel: true + }; + else return { + maxOutputTokens: 4096, + supportsStructuredOutput: false, + isKnownModel: false + }; + } + function hasWebTool20260209WithoutCodeExecution(tools) { + if (!tools) return false; + let hasWebTool20260209 = false; + let hasCodeExecutionTool = false; + for (const tool of tools){ + if ("type" in tool && ("web_fetch_20260209" === tool.type || "web_search_20260209" === tool.type)) { + hasWebTool20260209 = true; + continue; + } + if ("code_execution" === tool.name) { + hasCodeExecutionTool = true; + break; + } + } + return hasWebTool20260209 && !hasCodeExecutionTool; + } + function mapAnthropicResponseContextManagement(contextManagement) { + return contextManagement ? { + appliedEdits: contextManagement.applied_edits.map((edit)=>{ + const strategy = edit.type; + switch(strategy){ + case "clear_tool_uses_20250919": + return { + type: edit.type, + clearedToolUses: edit.cleared_tool_uses, + clearedInputTokens: edit.cleared_input_tokens + }; + case "clear_thinking_20251015": + return { + type: edit.type, + clearedThinkingTurns: edit.cleared_thinking_turns, + clearedInputTokens: edit.cleared_input_tokens + }; + case "compact_20260112": + return { + type: edit.type + }; + } + }).filter((edit)=>void 0 !== edit) + } : null; + } + var bash_20241022InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + command: schemas_string(), + restart: schemas_boolean().optional() + }))); + var bash_20241022 = createProviderToolFactory({ + id: "anthropic.bash_20241022", + inputSchema: bash_20241022InputSchema + }); + var bash_20250124InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + command: schemas_string(), + restart: schemas_boolean().optional() + }))); + var bash_20250124 = createProviderToolFactory({ + id: "anthropic.bash_20250124", + inputSchema: bash_20250124InputSchema + }); + var computer_20241022InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + action: schemas_enum([ + "key", + "type", + "mouse_move", + "left_click", + "left_click_drag", + "right_click", + "middle_click", + "double_click", + "screenshot", + "cursor_position" + ]), + coordinate: schemas_array(schemas_number().int()).optional(), + text: schemas_string().optional() + }))); + var computer_20241022 = createProviderToolFactory({ + id: "anthropic.computer_20241022", + inputSchema: computer_20241022InputSchema + }); + var computer_20250124InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + action: schemas_enum([ + "key", + "hold_key", + "type", + "cursor_position", + "mouse_move", + "left_mouse_down", + "left_mouse_up", + "left_click", + "left_click_drag", + "right_click", + "middle_click", + "double_click", + "triple_click", + "scroll", + "wait", + "screenshot" + ]), + coordinate: tuple([ + schemas_number().int(), + schemas_number().int() + ]).optional(), + duration: schemas_number().optional(), + scroll_amount: schemas_number().optional(), + scroll_direction: schemas_enum([ + "up", + "down", + "left", + "right" + ]).optional(), + start_coordinate: tuple([ + schemas_number().int(), + schemas_number().int() + ]).optional(), + text: schemas_string().optional() + }))); + var computer_20250124 = createProviderToolFactory({ + id: "anthropic.computer_20250124", + inputSchema: computer_20250124InputSchema + }); + var computer_20251124InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + action: schemas_enum([ + "key", + "hold_key", + "type", + "cursor_position", + "mouse_move", + "left_mouse_down", + "left_mouse_up", + "left_click", + "left_click_drag", + "right_click", + "middle_click", + "double_click", + "triple_click", + "scroll", + "wait", + "screenshot", + "zoom" + ]), + coordinate: tuple([ + schemas_number().int(), + schemas_number().int() + ]).optional(), + duration: schemas_number().optional(), + region: tuple([ + schemas_number().int(), + schemas_number().int(), + schemas_number().int(), + schemas_number().int() + ]).optional(), + scroll_amount: schemas_number().optional(), + scroll_direction: schemas_enum([ + "up", + "down", + "left", + "right" + ]).optional(), + start_coordinate: tuple([ + schemas_number().int(), + schemas_number().int() + ]).optional(), + text: schemas_string().optional() + }))); + var computer_20251124 = createProviderToolFactory({ + id: "anthropic.computer_20251124", + inputSchema: computer_20251124InputSchema + }); + var memory_20250818InputSchema = dist_lazySchema(()=>dist_zodSchema(discriminatedUnion("command", [ + schemas_object({ + command: schemas_literal("view"), + path: schemas_string(), + view_range: tuple([ + schemas_number(), + schemas_number() + ]).optional() + }), + schemas_object({ + command: schemas_literal("create"), + path: schemas_string(), + file_text: schemas_string() + }), + schemas_object({ + command: schemas_literal("str_replace"), + path: schemas_string(), + old_str: schemas_string(), + new_str: schemas_string() + }), + schemas_object({ + command: schemas_literal("insert"), + path: schemas_string(), + insert_line: schemas_number(), + insert_text: schemas_string() + }), + schemas_object({ + command: schemas_literal("delete"), + path: schemas_string() + }), + schemas_object({ + command: schemas_literal("rename"), + old_path: schemas_string(), + new_path: schemas_string() + }) + ]))); + var memory_20250818 = createProviderToolFactory({ + id: "anthropic.memory_20250818", + inputSchema: memory_20250818InputSchema + }); + var textEditor_20241022InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + command: schemas_enum([ + "view", + "create", + "str_replace", + "insert", + "undo_edit" + ]), + path: schemas_string(), + file_text: schemas_string().optional(), + insert_line: schemas_number().int().optional(), + new_str: schemas_string().optional(), + insert_text: schemas_string().optional(), + old_str: schemas_string().optional(), + view_range: schemas_array(schemas_number().int()).optional() + }))); + var textEditor_20241022 = createProviderToolFactory({ + id: "anthropic.text_editor_20241022", + inputSchema: textEditor_20241022InputSchema + }); + var textEditor_20250124InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + command: schemas_enum([ + "view", + "create", + "str_replace", + "insert", + "undo_edit" + ]), + path: schemas_string(), + file_text: schemas_string().optional(), + insert_line: schemas_number().int().optional(), + new_str: schemas_string().optional(), + insert_text: schemas_string().optional(), + old_str: schemas_string().optional(), + view_range: schemas_array(schemas_number().int()).optional() + }))); + var textEditor_20250124 = createProviderToolFactory({ + id: "anthropic.text_editor_20250124", + inputSchema: textEditor_20250124InputSchema + }); + var textEditor_20250429InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + command: schemas_enum([ + "view", + "create", + "str_replace", + "insert" + ]), + path: schemas_string(), + file_text: schemas_string().optional(), + insert_line: schemas_number().int().optional(), + new_str: schemas_string().optional(), + insert_text: schemas_string().optional(), + old_str: schemas_string().optional(), + view_range: schemas_array(schemas_number().int()).optional() + }))); + var textEditor_20250429 = createProviderToolFactory({ + id: "anthropic.text_editor_20250429", + inputSchema: textEditor_20250429InputSchema + }); + var toolSearchBm25_20251119OutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_array(schemas_object({ + type: schemas_literal("tool_reference"), + toolName: schemas_string() + })))); + var toolSearchBm25_20251119InputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + query: schemas_string(), + limit: schemas_number().optional() + }))); + var factory10 = createProviderToolFactoryWithOutputSchema({ + id: "anthropic.tool_search_bm25_20251119", + inputSchema: toolSearchBm25_20251119InputSchema, + outputSchema: toolSearchBm25_20251119OutputSchema, + supportsDeferredResults: true + }); + var toolSearchBm25_20251119 = (args = {})=>factory10(args); + var anthropicTools = { + bash_20241022, + bash_20250124, + codeExecution_20250522, + codeExecution_20250825, + codeExecution_20260120, + computer_20241022, + computer_20250124, + computer_20251124, + memory_20250818, + textEditor_20241022, + textEditor_20250124, + textEditor_20250429, + textEditor_20250728, + webFetch_20250910, + webFetch_20260209, + webSearch_20250305, + webSearch_20260209, + toolSearchRegex_20251119, + toolSearchBm25_20251119 + }; + function createAnthropic(options1 = {}) { + var _a, _b; + const baseURL = null != (_a = withoutTrailingSlash(loadOptionalSetting({ + settingValue: options1.baseURL, + environmentVariableName: "ANTHROPIC_BASE_URL" + }))) ? _a : "https://api.anthropic.com/v1"; + const providerName = null != (_b = options1.name) ? _b : "anthropic.messages"; + if (options1.apiKey && options1.authToken) throw new InvalidArgumentError({ + argument: "apiKey/authToken", + message: "Both apiKey and authToken were provided. Please use only one authentication method." + }); + const getHeaders = ()=>{ + const authHeaders = options1.authToken ? { + Authorization: `Bearer ${options1.authToken}` + } : { + "x-api-key": loadApiKey({ + apiKey: options1.apiKey, + environmentVariableName: "ANTHROPIC_API_KEY", + description: "Anthropic" + }) + }; + return withUserAgentSuffix({ + "anthropic-version": "2023-06-01", + ...authHeaders, + ...options1.headers + }, `ai-sdk/anthropic/${anthropic_dist_VERSION}`); + }; + const createChatModel = (modelId)=>{ + var _a2; + return new AnthropicMessagesLanguageModel(modelId, { + provider: providerName, + baseURL, + headers: getHeaders, + fetch: options1.fetch, + generateId: null != (_a2 = options1.generateId) ? _a2 : generateId, + supportedUrls: ()=>({ + "image/*": [ + /^https?:\/\/.*$/ + ], + "application/pdf": [ + /^https?:\/\/.*$/ + ] + }) + }); + }; + const provider = function(modelId) { + if (new.target) throw new Error("The Anthropic model function cannot be called with the new keyword."); + return createChatModel(modelId); + }; + provider.specificationVersion = "v3"; + provider.languageModel = createChatModel; + provider.chat = createChatModel; + provider.messages = createChatModel; + provider.embeddingModel = (modelId)=>{ + throw new NoSuchModelError({ + modelId, + modelType: "embeddingModel" + }); + }; + provider.textEmbeddingModel = provider.embeddingModel; + provider.imageModel = (modelId)=>{ + throw new NoSuchModelError({ + modelId, + modelType: "imageModel" + }); + }; + provider.tools = anthropicTools; + return provider; + } + createAnthropic(); + function convertToDeepSeekChatMessages({ prompt, responseFormat }) { + var _a; + const messages = []; + const warnings = []; + if ((null == responseFormat ? void 0 : responseFormat.type) === "json") if (null == responseFormat.schema) messages.push({ + role: "system", + content: "Return JSON." + }); + else { + messages.push({ + role: "system", + content: "Return JSON that conforms to the following schema: " + JSON.stringify(responseFormat.schema) + }); + warnings.push({ + type: "compatibility", + feature: "responseFormat JSON schema", + details: "JSON response schema is injected into the system message." + }); + } + let lastUserMessageIndex = -1; + for(let i = prompt.length - 1; i >= 0; i--)if ("user" === prompt[i].role) { + lastUserMessageIndex = i; + break; + } + let index = -1; + for (const { role, content } of prompt){ + index++; + switch(role){ + case "system": + messages.push({ + role: "system", + content + }); + break; + case "user": + { + let userContent = ""; + for (const part of content)if ("text" === part.type) userContent += part.text; + else warnings.push({ + type: "unsupported", + feature: `user message part type: ${part.type}` + }); + messages.push({ + role: "user", + content: userContent + }); + break; + } + case "assistant": + { + let text = ""; + let reasoning; + const toolCalls = []; + for (const part of content)switch(part.type){ + case "text": + text += part.text; + break; + case "reasoning": + if (index <= lastUserMessageIndex) break; + if (null == reasoning) reasoning = part.text; + else reasoning += part.text; + break; + case "tool-call": + toolCalls.push({ + id: part.toolCallId, + type: "function", + function: { + name: part.toolName, + arguments: JSON.stringify(part.input) + } + }); + break; + } + messages.push({ + role: "assistant", + content: text, + reasoning_content: reasoning, + tool_calls: toolCalls.length > 0 ? toolCalls : void 0 + }); + break; + } + case "tool": + for (const toolResponse of content){ + if ("tool-approval-response" === toolResponse.type) continue; + const output = toolResponse.output; + let contentValue; + switch(output.type){ + case "text": + case "error-text": + contentValue = output.value; + break; + case "execution-denied": + contentValue = null != (_a = output.reason) ? _a : "Tool execution denied."; + break; + case "content": + case "json": + case "error-json": + contentValue = JSON.stringify(output.value); + break; + } + messages.push({ + role: "tool", + tool_call_id: toolResponse.toolCallId, + content: contentValue + }); + } + break; + default: + warnings.push({ + type: "unsupported", + feature: `message role: ${role}` + }); + break; + } + } + return { + messages, + warnings + }; + } + function convertDeepSeekUsage(usage) { + var _a, _b, _c, _d, _e; + if (null == usage) return { + inputTokens: { + total: void 0, + noCache: void 0, + cacheRead: void 0, + cacheWrite: void 0 + }, + outputTokens: { + total: void 0, + text: void 0, + reasoning: void 0 + }, + raw: void 0 + }; + const promptTokens = null != (_a = usage.prompt_tokens) ? _a : 0; + const completionTokens = null != (_b = usage.completion_tokens) ? _b : 0; + const cacheReadTokens = null != (_c = usage.prompt_cache_hit_tokens) ? _c : 0; + const reasoningTokens = null != (_e = null == (_d = usage.completion_tokens_details) ? void 0 : _d.reasoning_tokens) ? _e : 0; + return { + inputTokens: { + total: promptTokens, + noCache: promptTokens - cacheReadTokens, + cacheRead: cacheReadTokens, + cacheWrite: void 0 + }, + outputTokens: { + total: completionTokens, + text: completionTokens - reasoningTokens, + reasoning: reasoningTokens + }, + raw: usage + }; + } + var tokenUsageSchema = schemas_object({ + prompt_tokens: schemas_number().nullish(), + completion_tokens: schemas_number().nullish(), + prompt_cache_hit_tokens: schemas_number().nullish(), + prompt_cache_miss_tokens: schemas_number().nullish(), + total_tokens: schemas_number().nullish(), + completion_tokens_details: schemas_object({ + reasoning_tokens: schemas_number().nullish() + }).nullish() + }).nullish(); + var deepSeekErrorSchema = schemas_object({ + error: schemas_object({ + message: schemas_string(), + type: schemas_string().nullish(), + param: any().nullish(), + code: union([ + schemas_string(), + schemas_number() + ]).nullish() + }) + }); + var deepseekChatResponseSchema = schemas_object({ + id: schemas_string().nullish(), + created: schemas_number().nullish(), + model: schemas_string().nullish(), + choices: schemas_array(schemas_object({ + message: schemas_object({ + role: schemas_literal("assistant").nullish(), + content: schemas_string().nullish(), + reasoning_content: schemas_string().nullish(), + tool_calls: schemas_array(schemas_object({ + id: schemas_string().nullish(), + function: schemas_object({ + name: schemas_string(), + arguments: schemas_string() + }) + })).nullish() + }), + finish_reason: schemas_string().nullish() + })), + usage: tokenUsageSchema + }); + var deepseekChatChunkSchema = dist_lazySchema(()=>dist_zodSchema(union([ + schemas_object({ + id: schemas_string().nullish(), + created: schemas_number().nullish(), + model: schemas_string().nullish(), + choices: schemas_array(schemas_object({ + delta: schemas_object({ + role: schemas_enum([ + "assistant" + ]).nullish(), + content: schemas_string().nullish(), + reasoning_content: schemas_string().nullish(), + tool_calls: schemas_array(schemas_object({ + index: schemas_number(), + id: schemas_string().nullish(), + function: schemas_object({ + name: schemas_string().nullish(), + arguments: schemas_string().nullish() + }) + })).nullish() + }).nullish(), + finish_reason: schemas_string().nullish() + })), + usage: tokenUsageSchema + }), + deepSeekErrorSchema + ]))); + var deepseekLanguageModelOptions = schemas_object({ + thinking: schemas_object({ + type: schemas_enum([ + "enabled", + "disabled" + ]).optional() + }).optional() + }); + function dist_prepareTools({ tools, toolChoice }) { + tools = (null == tools ? void 0 : tools.length) ? tools : void 0; + const toolWarnings = []; + if (null == tools) return { + tools: void 0, + toolChoice: void 0, + toolWarnings + }; + const deepseekTools = []; + for (const tool of tools)if ("provider" === tool.type) toolWarnings.push({ + type: "unsupported", + feature: `provider-defined tool ${tool.id}` + }); + else deepseekTools.push({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.inputSchema, + ...null != tool.strict ? { + strict: tool.strict + } : {} + } + }); + if (null == toolChoice) return { + tools: deepseekTools, + toolChoice: void 0, + toolWarnings + }; + const type = null == toolChoice ? void 0 : toolChoice.type; + switch(type){ + case "auto": + case "none": + case "required": + return { + tools: deepseekTools, + toolChoice: type, + toolWarnings + }; + case "tool": + return { + tools: deepseekTools, + toolChoice: { + type: "function", + function: { + name: toolChoice.toolName + } + }, + toolWarnings + }; + default: + return { + tools: deepseekTools, + toolChoice: void 0, + toolWarnings: [ + ...toolWarnings, + { + type: "unsupported", + feature: `tool choice type: ${type}` + } + ] + }; + } + } + function getResponseMetadata({ id, model, created }) { + return { + id: null != id ? id : void 0, + modelId: null != model ? model : void 0, + timestamp: null != created ? new Date(1e3 * created) : void 0 + }; + } + function mapDeepSeekFinishReason(finishReason) { + switch(finishReason){ + case "stop": + return "stop"; + case "length": + return "length"; + case "content_filter": + return "content-filter"; + case "tool_calls": + return "tool-calls"; + case "insufficient_system_resource": + return "error"; + default: + return "other"; + } + } + var DeepSeekChatLanguageModel = class { + constructor(modelId, config){ + this.specificationVersion = "v3"; + this.supportedUrls = {}; + this.modelId = modelId; + this.config = config; + this.failedResponseHandler = createJsonErrorResponseHandler({ + errorSchema: deepSeekErrorSchema, + errorToMessage: (error)=>error.error.message + }); + } + get provider() { + return this.config.provider; + } + get providerOptionsName() { + return this.config.provider.split(".")[0].trim(); + } + async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, providerOptions, stopSequences, responseFormat, seed, toolChoice, tools }) { + var _a, _b; + const deepseekOptions = null != (_a = await parseProviderOptions({ + provider: this.providerOptionsName, + providerOptions, + schema: deepseekLanguageModelOptions + })) ? _a : {}; + const { messages, warnings } = convertToDeepSeekChatMessages({ + prompt, + responseFormat + }); + if (null != topK) warnings.push({ + type: "unsupported", + feature: "topK" + }); + if (null != seed) warnings.push({ + type: "unsupported", + feature: "seed" + }); + const { tools: deepseekTools, toolChoice: deepseekToolChoices, toolWarnings } = dist_prepareTools({ + tools, + toolChoice + }); + return { + args: { + model: this.modelId, + max_tokens: maxOutputTokens, + temperature, + top_p: topP, + frequency_penalty: frequencyPenalty, + presence_penalty: presencePenalty, + response_format: (null == responseFormat ? void 0 : responseFormat.type) === "json" ? { + type: "json_object" + } : void 0, + stop: stopSequences, + messages, + tools: deepseekTools, + tool_choice: deepseekToolChoices, + thinking: (null == (_b = deepseekOptions.thinking) ? void 0 : _b.type) != null ? { + type: deepseekOptions.thinking.type + } : void 0 + }, + warnings: [ + ...warnings, + ...toolWarnings + ] + }; + } + async doGenerate(options1) { + var _a, _b, _c, _d; + const { args, warnings } = await this.getArgs({ + ...options1 + }); + const { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options1.headers), + body: args, + failedResponseHandler: this.failedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(deepseekChatResponseSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + const choice = responseBody.choices[0]; + const content = []; + const reasoning = choice.message.reasoning_content; + if (null != reasoning && reasoning.length > 0) content.push({ + type: "reasoning", + text: reasoning + }); + if (null != choice.message.tool_calls) for (const toolCall of choice.message.tool_calls)content.push({ + type: "tool-call", + toolCallId: null != (_a = toolCall.id) ? _a : generateId(), + toolName: toolCall.function.name, + input: toolCall.function.arguments + }); + const text = choice.message.content; + if (null != text && text.length > 0) content.push({ + type: "text", + text + }); + return { + content, + finishReason: { + unified: mapDeepSeekFinishReason(choice.finish_reason), + raw: null != (_b = choice.finish_reason) ? _b : void 0 + }, + usage: convertDeepSeekUsage(responseBody.usage), + providerMetadata: { + [this.providerOptionsName]: { + promptCacheHitTokens: null == (_c = responseBody.usage) ? void 0 : _c.prompt_cache_hit_tokens, + promptCacheMissTokens: null == (_d = responseBody.usage) ? void 0 : _d.prompt_cache_miss_tokens + } + }, + request: { + body: args + }, + response: { + ...getResponseMetadata(responseBody), + headers: responseHeaders, + body: rawResponse + }, + warnings + }; + } + async doStream(options1) { + const { args, warnings } = await this.getArgs({ + ...options1 + }); + const body = { + ...args, + stream: true, + stream_options: { + include_usage: true + } + }; + const { responseHeaders, value: response } = await postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options1.headers), + body, + failedResponseHandler: this.failedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler(deepseekChatChunkSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + const toolCalls = []; + let finishReason = { + unified: "other", + raw: void 0 + }; + let usage; + let isFirstChunk = true; + const providerOptionsName = this.providerOptionsName; + let isActiveReasoning = false; + let isActiveText = false; + return { + stream: response.pipeThrough(new TransformStream({ + start (controller) { + controller.enqueue({ + type: "stream-start", + warnings + }); + }, + transform (chunk, controller) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l; + if (options1.includeRawChunks) controller.enqueue({ + type: "raw", + rawValue: chunk.rawValue + }); + if (!chunk.success) { + finishReason = { + unified: "error", + raw: void 0 + }; + controller.enqueue({ + type: "error", + error: chunk.error + }); + return; + } + const value1 = chunk.value; + if ("error" in value1) { + finishReason = { + unified: "error", + raw: void 0 + }; + controller.enqueue({ + type: "error", + error: value1.error.message + }); + return; + } + if (isFirstChunk) { + isFirstChunk = false; + controller.enqueue({ + type: "response-metadata", + ...getResponseMetadata(value1) + }); + } + if (null != value1.usage) usage = value1.usage; + const choice = value1.choices[0]; + if ((null == choice ? void 0 : choice.finish_reason) != null) finishReason = { + unified: mapDeepSeekFinishReason(choice.finish_reason), + raw: choice.finish_reason + }; + if ((null == choice ? void 0 : choice.delta) == null) return; + const delta = choice.delta; + const reasoningContent = delta.reasoning_content; + if (reasoningContent) { + if (!isActiveReasoning) { + controller.enqueue({ + type: "reasoning-start", + id: "reasoning-0" + }); + isActiveReasoning = true; + } + controller.enqueue({ + type: "reasoning-delta", + id: "reasoning-0", + delta: reasoningContent + }); + } + if (delta.content) { + if (!isActiveText) { + controller.enqueue({ + type: "text-start", + id: "txt-0" + }); + isActiveText = true; + } + if (isActiveReasoning) { + controller.enqueue({ + type: "reasoning-end", + id: "reasoning-0" + }); + isActiveReasoning = false; + } + controller.enqueue({ + type: "text-delta", + id: "txt-0", + delta: delta.content + }); + } + if (null != delta.tool_calls) { + if (isActiveReasoning) { + controller.enqueue({ + type: "reasoning-end", + id: "reasoning-0" + }); + isActiveReasoning = false; + } + for (const toolCallDelta of delta.tool_calls){ + const index = toolCallDelta.index; + if (null == toolCalls[index]) { + if (null == toolCallDelta.id) throw new InvalidResponseDataError({ + data: toolCallDelta, + message: "Expected 'id' to be a string." + }); + if ((null == (_a = toolCallDelta.function) ? void 0 : _a.name) == null) throw new InvalidResponseDataError({ + data: toolCallDelta, + message: "Expected 'function.name' to be a string." + }); + controller.enqueue({ + type: "tool-input-start", + id: toolCallDelta.id, + toolName: toolCallDelta.function.name + }); + toolCalls[index] = { + id: toolCallDelta.id, + type: "function", + function: { + name: toolCallDelta.function.name, + arguments: null != (_b = toolCallDelta.function.arguments) ? _b : "" + }, + hasFinished: false + }; + const toolCall2 = toolCalls[index]; + if ((null == (_c = toolCall2.function) ? void 0 : _c.name) != null && (null == (_d = toolCall2.function) ? void 0 : _d.arguments) != null) { + if (toolCall2.function.arguments.length > 0) controller.enqueue({ + type: "tool-input-delta", + id: toolCall2.id, + delta: toolCall2.function.arguments + }); + if (isParsableJson(toolCall2.function.arguments)) { + controller.enqueue({ + type: "tool-input-end", + id: toolCall2.id + }); + controller.enqueue({ + type: "tool-call", + toolCallId: null != (_e = toolCall2.id) ? _e : generateId(), + toolName: toolCall2.function.name, + input: toolCall2.function.arguments + }); + toolCall2.hasFinished = true; + } + } + continue; + } + const toolCall = toolCalls[index]; + if (!toolCall.hasFinished) { + if ((null == (_f = toolCallDelta.function) ? void 0 : _f.arguments) != null) toolCall.function.arguments += null != (_h = null == (_g = toolCallDelta.function) ? void 0 : _g.arguments) ? _h : ""; + controller.enqueue({ + type: "tool-input-delta", + id: toolCall.id, + delta: null != (_i = toolCallDelta.function.arguments) ? _i : "" + }); + if ((null == (_j = toolCall.function) ? void 0 : _j.name) != null && (null == (_k = toolCall.function) ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) { + controller.enqueue({ + type: "tool-input-end", + id: toolCall.id + }); + controller.enqueue({ + type: "tool-call", + toolCallId: null != (_l = toolCall.id) ? _l : generateId(), + toolName: toolCall.function.name, + input: toolCall.function.arguments + }); + toolCall.hasFinished = true; + } + } + } + } + }, + flush (controller) { + var _a, _b, _c; + if (isActiveReasoning) controller.enqueue({ + type: "reasoning-end", + id: "reasoning-0" + }); + if (isActiveText) controller.enqueue({ + type: "text-end", + id: "txt-0" + }); + for (const toolCall of toolCalls.filter((toolCall2)=>!toolCall2.hasFinished)){ + controller.enqueue({ + type: "tool-input-end", + id: toolCall.id + }); + controller.enqueue({ + type: "tool-call", + toolCallId: null != (_a = toolCall.id) ? _a : generateId(), + toolName: toolCall.function.name, + input: toolCall.function.arguments + }); + } + controller.enqueue({ + type: "finish", + finishReason, + usage: convertDeepSeekUsage(usage), + providerMetadata: { + [providerOptionsName]: { + promptCacheHitTokens: null != (_b = null == usage ? void 0 : usage.prompt_cache_hit_tokens) ? _b : void 0, + promptCacheMissTokens: null != (_c = null == usage ? void 0 : usage.prompt_cache_miss_tokens) ? _c : void 0 + } + } + }); + } + })), + request: { + body + }, + response: { + headers: responseHeaders + } + }; + } + }; + var deepseek_dist_VERSION = "2.0.29"; + function createDeepSeek(options1 = {}) { + var _a; + const baseURL = withoutTrailingSlash(null != (_a = options1.baseURL) ? _a : "https://api.deepseek.com"); + const getHeaders = ()=>withUserAgentSuffix({ + Authorization: `Bearer ${loadApiKey({ + apiKey: options1.apiKey, + environmentVariableName: "DEEPSEEK_API_KEY", + description: "DeepSeek API key" + })}`, + ...options1.headers + }, `ai-sdk/deepseek/${deepseek_dist_VERSION}`); + const createLanguageModel = (modelId)=>new DeepSeekChatLanguageModel(modelId, { + provider: "deepseek.chat", + url: ({ path })=>`${baseURL}${path}`, + headers: getHeaders, + fetch: options1.fetch + }); + const provider = (modelId)=>createLanguageModel(modelId); + provider.specificationVersion = "v3"; + provider.languageModel = createLanguageModel; + provider.chat = createLanguageModel; + provider.embeddingModel = (modelId)=>{ + throw new NoSuchModelError({ + modelId, + modelType: "embeddingModel" + }); + }; + provider.textEmbeddingModel = provider.embeddingModel; + provider.imageModel = (modelId)=>{ + throw new NoSuchModelError({ + modelId, + modelType: "imageModel" + }); + }; + return provider; + } + createDeepSeek(); + var google_dist_VERSION = "3.0.63"; + var googleErrorDataSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + error: schemas_object({ + code: schemas_number().nullable(), + message: schemas_string(), + status: schemas_string() + }) + }))); + var googleFailedResponseHandler = createJsonErrorResponseHandler({ + errorSchema: googleErrorDataSchema, + errorToMessage: (data)=>data.error.message + }); + var googleEmbeddingContentPartSchema = union([ + schemas_object({ + text: schemas_string() + }), + schemas_object({ + inlineData: schemas_object({ + mimeType: schemas_string(), + data: schemas_string() + }) + }) + ]); + var googleEmbeddingModelOptions = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + outputDimensionality: schemas_number().optional(), + taskType: schemas_enum([ + "SEMANTIC_SIMILARITY", + "CLASSIFICATION", + "CLUSTERING", + "RETRIEVAL_DOCUMENT", + "RETRIEVAL_QUERY", + "QUESTION_ANSWERING", + "FACT_VERIFICATION", + "CODE_RETRIEVAL_QUERY" + ]).optional(), + content: schemas_array(schemas_array(googleEmbeddingContentPartSchema).min(1).nullable()).optional() + }))); + var GoogleGenerativeAIEmbeddingModel = class { + constructor(modelId, config){ + this.specificationVersion = "v3"; + this.maxEmbeddingsPerCall = 2048; + this.supportsParallelCalls = true; + this.modelId = modelId; + this.config = config; + } + get provider() { + return this.config.provider; + } + async doEmbed({ values, headers, abortSignal, providerOptions }) { + const googleOptions = await parseProviderOptions({ + provider: "google", + providerOptions, + schema: googleEmbeddingModelOptions + }); + if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError({ + provider: this.provider, + modelId: this.modelId, + maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, + values + }); + const mergedHeaders = combineHeaders(await dist_resolve(this.config.headers), headers); + const multimodalContent = null == googleOptions ? void 0 : googleOptions.content; + if (null != multimodalContent && multimodalContent.length !== values.length) throw new Error(`The number of multimodal content entries (${multimodalContent.length}) must match the number of values (${values.length}).`); + if (1 === values.length) { + const valueParts = null == multimodalContent ? void 0 : multimodalContent[0]; + const textPart = values[0] ? [ + { + text: values[0] + } + ] : []; + const parts = null != valueParts ? [ + ...textPart, + ...valueParts + ] : [ + { + text: values[0] + } + ]; + const { responseHeaders: responseHeaders2, value: response2, rawValue: rawValue2 } = await postJsonToApi({ + url: `${this.config.baseURL}/models/${this.modelId}:embedContent`, + headers: mergedHeaders, + body: { + model: `models/${this.modelId}`, + content: { + parts + }, + outputDimensionality: null == googleOptions ? void 0 : googleOptions.outputDimensionality, + taskType: null == googleOptions ? void 0 : googleOptions.taskType + }, + failedResponseHandler: googleFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(googleGenerativeAISingleEmbeddingResponseSchema), + abortSignal, + fetch: this.config.fetch + }); + return { + warnings: [], + embeddings: [ + response2.embedding.values + ], + usage: void 0, + response: { + headers: responseHeaders2, + body: rawValue2 + } + }; + } + const { responseHeaders, value: response, rawValue } = await postJsonToApi({ + url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`, + headers: mergedHeaders, + body: { + requests: values.map((value1, index)=>{ + const valueParts = null == multimodalContent ? void 0 : multimodalContent[index]; + const textPart = value1 ? [ + { + text: value1 + } + ] : []; + return { + model: `models/${this.modelId}`, + content: { + role: "user", + parts: null != valueParts ? [ + ...textPart, + ...valueParts + ] : [ + { + text: value1 + } + ] + }, + outputDimensionality: null == googleOptions ? void 0 : googleOptions.outputDimensionality, + taskType: null == googleOptions ? void 0 : googleOptions.taskType + }; + }) + }, + failedResponseHandler: googleFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(googleGenerativeAITextEmbeddingResponseSchema), + abortSignal, + fetch: this.config.fetch + }); + return { + warnings: [], + embeddings: response.embeddings.map((item)=>item.values), + usage: void 0, + response: { + headers: responseHeaders, + body: rawValue + } + }; + } + }; + var googleGenerativeAITextEmbeddingResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + embeddings: schemas_array(schemas_object({ + values: schemas_array(schemas_number()) + })) + }))); + var googleGenerativeAISingleEmbeddingResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + embedding: schemas_object({ + values: schemas_array(schemas_number()) + }) + }))); + function convertGoogleGenerativeAIUsage(usage) { + var _a, _b, _c, _d; + if (null == usage) return { + inputTokens: { + total: void 0, + noCache: void 0, + cacheRead: void 0, + cacheWrite: void 0 + }, + outputTokens: { + total: void 0, + text: void 0, + reasoning: void 0 + }, + raw: void 0 + }; + const promptTokens = null != (_a = usage.promptTokenCount) ? _a : 0; + const candidatesTokens = null != (_b = usage.candidatesTokenCount) ? _b : 0; + const cachedContentTokens = null != (_c = usage.cachedContentTokenCount) ? _c : 0; + const thoughtsTokens = null != (_d = usage.thoughtsTokenCount) ? _d : 0; + return { + inputTokens: { + total: promptTokens, + noCache: promptTokens - cachedContentTokens, + cacheRead: cachedContentTokens, + cacheWrite: void 0 + }, + outputTokens: { + total: candidatesTokens + thoughtsTokens, + text: candidatesTokens, + reasoning: thoughtsTokens + }, + raw: usage + }; + } + function convertJSONSchemaToOpenAPISchema(jsonSchema, isRoot = true) { + if (null == jsonSchema) return; + if (isEmptyObjectSchema(jsonSchema)) { + if (isRoot) return; + if ("object" == typeof jsonSchema && jsonSchema.description) return { + type: "object", + description: jsonSchema.description + }; + return { + type: "object" + }; + } + if ("boolean" == typeof jsonSchema) return { + type: "boolean", + properties: {} + }; + const { type, description, required, properties, items, allOf, anyOf, oneOf, format, const: constValue, minLength, enum: enumValues } = jsonSchema; + const result = {}; + if (description) result.description = description; + if (required) result.required = required; + if (format) result.format = format; + if (void 0 !== constValue) result.enum = [ + constValue + ]; + if (type) if (Array.isArray(type)) { + const hasNull = type.includes("null"); + const nonNullTypes = type.filter((t)=>"null" !== t); + if (0 === nonNullTypes.length) result.type = "null"; + else { + result.anyOf = nonNullTypes.map((t)=>({ + type: t + })); + if (hasNull) result.nullable = true; + } + } else result.type = type; + if (void 0 !== enumValues) result.enum = enumValues; + if (null != properties) result.properties = Object.entries(properties).reduce((acc, [key, value1])=>{ + acc[key] = convertJSONSchemaToOpenAPISchema(value1, false); + return acc; + }, {}); + if (items) result.items = Array.isArray(items) ? items.map((item)=>convertJSONSchemaToOpenAPISchema(item, false)) : convertJSONSchemaToOpenAPISchema(items, false); + if (allOf) result.allOf = allOf.map((item)=>convertJSONSchemaToOpenAPISchema(item, false)); + if (anyOf) if (anyOf.some((schema)=>"object" == typeof schema && (null == schema ? void 0 : schema.type) === "null")) { + const nonNullSchemas = anyOf.filter((schema)=>!("object" == typeof schema && (null == schema ? void 0 : schema.type) === "null")); + if (1 === nonNullSchemas.length) { + const converted = convertJSONSchemaToOpenAPISchema(nonNullSchemas[0], false); + if ("object" == typeof converted) { + result.nullable = true; + Object.assign(result, converted); + } + } else { + result.anyOf = nonNullSchemas.map((item)=>convertJSONSchemaToOpenAPISchema(item, false)); + result.nullable = true; + } + } else result.anyOf = anyOf.map((item)=>convertJSONSchemaToOpenAPISchema(item, false)); + if (oneOf) result.oneOf = oneOf.map((item)=>convertJSONSchemaToOpenAPISchema(item, false)); + if (void 0 !== minLength) result.minLength = minLength; + return result; + } + function isEmptyObjectSchema(jsonSchema) { + return null != jsonSchema && "object" == typeof jsonSchema && "object" === jsonSchema.type && (null == jsonSchema.properties || 0 === Object.keys(jsonSchema.properties).length) && !jsonSchema.additionalProperties; + } + var dataUrlRegex = /^data:([^;,]+);base64,(.+)$/s; + function parseBase64DataUrl(value1) { + const match = dataUrlRegex.exec(value1); + if (null == match) return; + return { + mediaType: match[1], + data: match[2] + }; + } + function convertUrlToolResultPart(url) { + const parsedDataUrl = parseBase64DataUrl(url); + if (null == parsedDataUrl) return; + return { + inlineData: { + mimeType: parsedDataUrl.mediaType, + data: parsedDataUrl.data + } + }; + } + function appendToolResultParts(parts, toolName, outputValue) { + const functionResponseParts = []; + const responseTextParts = []; + for (const contentPart of outputValue)switch(contentPart.type){ + case "text": + responseTextParts.push(contentPart.text); + break; + case "image-data": + case "file-data": + functionResponseParts.push({ + inlineData: { + mimeType: contentPart.mediaType, + data: contentPart.data + } + }); + break; + case "image-url": + case "file-url": + { + const functionResponsePart = convertUrlToolResultPart(contentPart.url); + if (null != functionResponsePart) functionResponseParts.push(functionResponsePart); + else responseTextParts.push(JSON.stringify(contentPart)); + break; + } + default: + responseTextParts.push(JSON.stringify(contentPart)); + break; + } + parts.push({ + functionResponse: { + name: toolName, + response: { + name: toolName, + content: responseTextParts.length > 0 ? responseTextParts.join("\n") : "Tool executed successfully." + }, + ...functionResponseParts.length > 0 ? { + parts: functionResponseParts + } : {} + } + }); + } + function appendLegacyToolResultParts(parts, toolName, outputValue) { + for (const contentPart of outputValue)switch(contentPart.type){ + case "text": + parts.push({ + functionResponse: { + name: toolName, + response: { + name: toolName, + content: contentPart.text + } + } + }); + break; + case "image-data": + parts.push({ + inlineData: { + mimeType: String(contentPart.mediaType), + data: String(contentPart.data) + } + }, { + text: "Tool executed successfully and returned this image as a response" + }); + break; + default: + parts.push({ + text: JSON.stringify(contentPart) + }); + break; + } + } + function convertToGoogleGenerativeAIMessages(prompt, options1) { + var _a, _b, _c, _d, _e, _f, _g, _h; + const systemInstructionParts = []; + const contents = []; + let systemMessagesAllowed = true; + const isGemmaModel = null != (_a = null == options1 ? void 0 : options1.isGemmaModel) ? _a : false; + const providerOptionsName = null != (_b = null == options1 ? void 0 : options1.providerOptionsName) ? _b : "google"; + const supportsFunctionResponseParts = null != (_c = null == options1 ? void 0 : options1.supportsFunctionResponseParts) ? _c : true; + for (const { role, content } of prompt)switch(role){ + case "system": + if (!systemMessagesAllowed) throw new UnsupportedFunctionalityError({ + functionality: "system messages are only supported at the beginning of the conversation" + }); + systemInstructionParts.push({ + text: content + }); + break; + case "user": + { + systemMessagesAllowed = false; + const parts = []; + for (const part of content)switch(part.type){ + case "text": + parts.push({ + text: part.text + }); + break; + case "file": + { + const mediaType = "image/*" === part.mediaType ? "image/jpeg" : part.mediaType; + parts.push(part.data instanceof URL ? { + fileData: { + mimeType: mediaType, + fileUri: part.data.toString() + } + } : { + inlineData: { + mimeType: mediaType, + data: convertToBase64(part.data) + } + }); + break; + } + } + contents.push({ + role: "user", + parts + }); + break; + } + case "assistant": + systemMessagesAllowed = false; + contents.push({ + role: "model", + parts: content.map((part)=>{ + var _a2, _b2, _c2, _d2; + const providerOpts = null != (_d2 = null == (_a2 = part.providerOptions) ? void 0 : _a2[providerOptionsName]) ? _d2 : "google" !== providerOptionsName ? null == (_b2 = part.providerOptions) ? void 0 : _b2.google : null == (_c2 = part.providerOptions) ? void 0 : _c2.vertex; + const thoughtSignature = (null == providerOpts ? void 0 : providerOpts.thoughtSignature) != null ? String(providerOpts.thoughtSignature) : void 0; + switch(part.type){ + case "text": + return 0 === part.text.length ? void 0 : { + text: part.text, + thoughtSignature + }; + case "reasoning": + return 0 === part.text.length ? void 0 : { + text: part.text, + thought: true, + thoughtSignature + }; + case "file": + if (part.data instanceof URL) throw new UnsupportedFunctionalityError({ + functionality: "File data URLs in assistant messages are not supported" + }); + return { + inlineData: { + mimeType: part.mediaType, + data: convertToBase64(part.data) + }, + ...(null == providerOpts ? void 0 : providerOpts.thought) === true ? { + thought: true + } : {}, + thoughtSignature + }; + case "tool-call": + { + const serverToolCallId = (null == providerOpts ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0; + const serverToolType = (null == providerOpts ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0; + if (serverToolCallId && serverToolType) return { + toolCall: { + toolType: serverToolType, + args: "string" == typeof part.input ? JSON.parse(part.input) : part.input, + id: serverToolCallId + }, + thoughtSignature + }; + return { + functionCall: { + name: part.toolName, + args: part.input + }, + thoughtSignature + }; + } + case "tool-result": + { + const serverToolCallId = (null == providerOpts ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0; + const serverToolType = (null == providerOpts ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0; + if (serverToolCallId && serverToolType) return { + toolResponse: { + toolType: serverToolType, + response: "json" === part.output.type ? part.output.value : {}, + id: serverToolCallId + }, + thoughtSignature + }; + return; + } + } + }).filter((part)=>void 0 !== part) + }); + break; + case "tool": + { + systemMessagesAllowed = false; + const parts = []; + for (const part of content){ + if ("tool-approval-response" === part.type) continue; + const partProviderOpts = null != (_g = null == (_d = part.providerOptions) ? void 0 : _d[providerOptionsName]) ? _g : "google" !== providerOptionsName ? null == (_e = part.providerOptions) ? void 0 : _e.google : null == (_f = part.providerOptions) ? void 0 : _f.vertex; + const serverToolCallId = (null == partProviderOpts ? void 0 : partProviderOpts.serverToolCallId) != null ? String(partProviderOpts.serverToolCallId) : void 0; + const serverToolType = (null == partProviderOpts ? void 0 : partProviderOpts.serverToolType) != null ? String(partProviderOpts.serverToolType) : void 0; + if (serverToolCallId && serverToolType) { + const serverThoughtSignature = (null == partProviderOpts ? void 0 : partProviderOpts.thoughtSignature) != null ? String(partProviderOpts.thoughtSignature) : void 0; + if (contents.length > 0) { + const lastContent = contents[contents.length - 1]; + if ("model" === lastContent.role) { + lastContent.parts.push({ + toolResponse: { + toolType: serverToolType, + response: "json" === part.output.type ? part.output.value : {}, + id: serverToolCallId + }, + thoughtSignature: serverThoughtSignature + }); + continue; + } + } + } + const output = part.output; + if ("content" === output.type) if (supportsFunctionResponseParts) appendToolResultParts(parts, part.toolName, output.value); + else appendLegacyToolResultParts(parts, part.toolName, output.value); + else parts.push({ + functionResponse: { + name: part.toolName, + response: { + name: part.toolName, + content: "execution-denied" === output.type ? null != (_h = output.reason) ? _h : "Tool execution denied." : output.value + } + } + }); + } + contents.push({ + role: "user", + parts + }); + break; + } + } + if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && "user" === contents[0].role) { + const systemText = systemInstructionParts.map((part)=>part.text).join("\n\n"); + contents[0].parts.unshift({ + text: systemText + "\n\n" + }); + } + return { + systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { + parts: systemInstructionParts + } : void 0, + contents + }; + } + function getModelPath(modelId) { + return modelId.includes("/") ? modelId : `models/${modelId}`; + } + var googleLanguageModelOptions = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + responseModalities: schemas_array(schemas_enum([ + "TEXT", + "IMAGE" + ])).optional(), + thinkingConfig: schemas_object({ + thinkingBudget: schemas_number().optional(), + includeThoughts: schemas_boolean().optional(), + thinkingLevel: schemas_enum([ + "minimal", + "low", + "medium", + "high" + ]).optional() + }).optional(), + cachedContent: schemas_string().optional(), + structuredOutputs: schemas_boolean().optional(), + safetySettings: schemas_array(schemas_object({ + category: schemas_enum([ + "HARM_CATEGORY_UNSPECIFIED", + "HARM_CATEGORY_HATE_SPEECH", + "HARM_CATEGORY_DANGEROUS_CONTENT", + "HARM_CATEGORY_HARASSMENT", + "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "HARM_CATEGORY_CIVIC_INTEGRITY" + ]), + threshold: schemas_enum([ + "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + "BLOCK_LOW_AND_ABOVE", + "BLOCK_MEDIUM_AND_ABOVE", + "BLOCK_ONLY_HIGH", + "BLOCK_NONE", + "OFF" + ]) + })).optional(), + threshold: schemas_enum([ + "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + "BLOCK_LOW_AND_ABOVE", + "BLOCK_MEDIUM_AND_ABOVE", + "BLOCK_ONLY_HIGH", + "BLOCK_NONE", + "OFF" + ]).optional(), + audioTimestamp: schemas_boolean().optional(), + labels: schemas_record(schemas_string(), schemas_string()).optional(), + mediaResolution: schemas_enum([ + "MEDIA_RESOLUTION_UNSPECIFIED", + "MEDIA_RESOLUTION_LOW", + "MEDIA_RESOLUTION_MEDIUM", + "MEDIA_RESOLUTION_HIGH" + ]).optional(), + imageConfig: schemas_object({ + aspectRatio: schemas_enum([ + "1:1", + "2:3", + "3:2", + "3:4", + "4:3", + "4:5", + "5:4", + "9:16", + "16:9", + "21:9", + "1:8", + "8:1", + "1:4", + "4:1" + ]).optional(), + imageSize: schemas_enum([ + "1K", + "2K", + "4K", + "512" + ]).optional() + }).optional(), + retrievalConfig: schemas_object({ + latLng: schemas_object({ + latitude: schemas_number(), + longitude: schemas_number() + }).optional() + }).optional(), + streamFunctionCallArguments: schemas_boolean().optional(), + serviceTier: schemas_enum([ + "standard", + "flex", + "priority" + ]).optional() + }))); + var VertexServiceTierMap = { + standard: "SERVICE_TIER_STANDARD", + flex: "SERVICE_TIER_FLEX", + priority: "SERVICE_TIER_PRIORITY" + }; + function google_dist_prepareTools({ tools, toolChoice, modelId }) { + var _a, _b; + tools = (null == tools ? void 0 : tools.length) ? tools : void 0; + const toolWarnings = []; + const isLatest = [ + "gemini-flash-latest", + "gemini-flash-lite-latest", + "gemini-pro-latest" + ].some((id)=>id === modelId); + const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || modelId.includes("nano-banana") || isLatest; + const isGemini3orNewer = modelId.includes("gemini-3"); + const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3"); + if (null == tools) return { + tools: void 0, + toolConfig: void 0, + toolWarnings + }; + const hasFunctionTools = tools.some((tool)=>"function" === tool.type); + const hasProviderTools = tools.some((tool)=>"provider" === tool.type); + if (hasFunctionTools && hasProviderTools && !isGemini3orNewer) toolWarnings.push({ + type: "unsupported", + feature: "combination of function and provider-defined tools" + }); + if (hasProviderTools) { + const googleTools2 = []; + const ProviderTools = tools.filter((tool)=>"provider" === tool.type); + ProviderTools.forEach((tool)=>{ + switch(tool.id){ + case "google.google_search": + if (isGemini2orNewer) googleTools2.push({ + googleSearch: { + ...tool.args + } + }); + else toolWarnings.push({ + type: "unsupported", + feature: `provider-defined tool ${tool.id}`, + details: "Google Search requires Gemini 2.0 or newer." + }); + break; + case "google.enterprise_web_search": + if (isGemini2orNewer) googleTools2.push({ + enterpriseWebSearch: {} + }); + else toolWarnings.push({ + type: "unsupported", + feature: `provider-defined tool ${tool.id}`, + details: "Enterprise Web Search requires Gemini 2.0 or newer." + }); + break; + case "google.url_context": + if (isGemini2orNewer) googleTools2.push({ + urlContext: {} + }); + else toolWarnings.push({ + type: "unsupported", + feature: `provider-defined tool ${tool.id}`, + details: "The URL context tool is not supported with other Gemini models than Gemini 2." + }); + break; + case "google.code_execution": + if (isGemini2orNewer) googleTools2.push({ + codeExecution: {} + }); + else toolWarnings.push({ + type: "unsupported", + feature: `provider-defined tool ${tool.id}`, + details: "The code execution tool is not supported with other Gemini models than Gemini 2." + }); + break; + case "google.file_search": + if (supportsFileSearch) googleTools2.push({ + fileSearch: { + ...tool.args + } + }); + else toolWarnings.push({ + type: "unsupported", + feature: `provider-defined tool ${tool.id}`, + details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models." + }); + break; + case "google.vertex_rag_store": + if (isGemini2orNewer) googleTools2.push({ + retrieval: { + vertex_rag_store: { + rag_resources: { + rag_corpus: tool.args.ragCorpus + }, + similarity_top_k: tool.args.topK + } + } + }); + else toolWarnings.push({ + type: "unsupported", + feature: `provider-defined tool ${tool.id}`, + details: "The RAG store tool is not supported with other Gemini models than Gemini 2." + }); + break; + case "google.google_maps": + if (isGemini2orNewer) googleTools2.push({ + googleMaps: {} + }); + else toolWarnings.push({ + type: "unsupported", + feature: `provider-defined tool ${tool.id}`, + details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer." + }); + break; + default: + toolWarnings.push({ + type: "unsupported", + feature: `provider-defined tool ${tool.id}` + }); + break; + } + }); + if (hasFunctionTools && isGemini3orNewer && googleTools2.length > 0) { + const functionDeclarations2 = []; + for (const tool of tools)if ("function" === tool.type) functionDeclarations2.push({ + name: tool.name, + description: null != (_a = tool.description) ? _a : "", + parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema) + }); + const combinedToolConfig = { + functionCallingConfig: { + mode: "VALIDATED" + }, + includeServerSideToolInvocations: true + }; + if (null != toolChoice) switch(toolChoice.type){ + case "auto": + break; + case "none": + combinedToolConfig.functionCallingConfig = { + mode: "NONE" + }; + break; + case "required": + combinedToolConfig.functionCallingConfig = { + mode: "ANY" + }; + break; + case "tool": + combinedToolConfig.functionCallingConfig = { + mode: "ANY", + allowedFunctionNames: [ + toolChoice.toolName + ] + }; + break; + } + return { + tools: [ + ...googleTools2, + { + functionDeclarations: functionDeclarations2 + } + ], + toolConfig: combinedToolConfig, + toolWarnings + }; + } + return { + tools: googleTools2.length > 0 ? googleTools2 : void 0, + toolConfig: void 0, + toolWarnings + }; + } + const functionDeclarations = []; + let hasStrictTools = false; + for (const tool of tools)switch(tool.type){ + case "function": + functionDeclarations.push({ + name: tool.name, + description: null != (_b = tool.description) ? _b : "", + parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema) + }); + if (true === tool.strict) hasStrictTools = true; + break; + default: + toolWarnings.push({ + type: "unsupported", + feature: `function tool ${tool.name}` + }); + break; + } + if (null == toolChoice) return { + tools: [ + { + functionDeclarations + } + ], + toolConfig: hasStrictTools ? { + functionCallingConfig: { + mode: "VALIDATED" + } + } : void 0, + toolWarnings + }; + const type = toolChoice.type; + switch(type){ + case "auto": + return { + tools: [ + { + functionDeclarations + } + ], + toolConfig: { + functionCallingConfig: { + mode: hasStrictTools ? "VALIDATED" : "AUTO" + } + }, + toolWarnings + }; + case "none": + return { + tools: [ + { + functionDeclarations + } + ], + toolConfig: { + functionCallingConfig: { + mode: "NONE" + } + }, + toolWarnings + }; + case "required": + return { + tools: [ + { + functionDeclarations + } + ], + toolConfig: { + functionCallingConfig: { + mode: hasStrictTools ? "VALIDATED" : "ANY" + } + }, + toolWarnings + }; + case "tool": + return { + tools: [ + { + functionDeclarations + } + ], + toolConfig: { + functionCallingConfig: { + mode: hasStrictTools ? "VALIDATED" : "ANY", + allowedFunctionNames: [ + toolChoice.toolName + ] + } + }, + toolWarnings + }; + default: + { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `tool choice type: ${_exhaustiveCheck}` + }); + } + } + } + var GoogleJSONAccumulator = class { + constructor(){ + this.accumulatedArgs = {}; + this.jsonText = ""; + this.pathStack = []; + this.stringOpen = false; + } + processPartialArgs(partialArgs) { + let delta = ""; + for (const arg of partialArgs){ + const rawPath = arg.jsonPath.replace(/^\$\./, ""); + if (!rawPath) continue; + const segments = parsePath(rawPath); + const existingValue = getNestedValue(this.accumulatedArgs, segments); + const isStringContinuation = null != arg.stringValue && void 0 !== existingValue; + if (isStringContinuation) { + const escaped = JSON.stringify(arg.stringValue).slice(1, -1); + setNestedValue(this.accumulatedArgs, segments, existingValue + arg.stringValue); + delta += escaped; + continue; + } + const resolved = resolvePartialArgValue(arg); + if (null != resolved) { + setNestedValue(this.accumulatedArgs, segments, resolved.value); + delta += this.emitNavigationTo(segments, arg, resolved.json); + } + } + this.jsonText += delta; + return { + currentJSON: this.accumulatedArgs, + textDelta: delta + }; + } + finalize() { + const finalArgs = JSON.stringify(this.accumulatedArgs); + const closingDelta = finalArgs.slice(this.jsonText.length); + return { + finalJSON: finalArgs, + closingDelta + }; + } + ensureRoot() { + if (0 === this.pathStack.length) { + this.pathStack.push({ + segment: "", + isArray: false, + childCount: 0 + }); + return "{"; + } + return ""; + } + emitNavigationTo(targetSegments, arg, valueJson) { + let fragment = ""; + if (this.stringOpen) { + fragment += '"'; + this.stringOpen = false; + } + fragment += this.ensureRoot(); + const targetContainerSegments = targetSegments.slice(0, -1); + const leafSegment = targetSegments[targetSegments.length - 1]; + const commonDepth = this.findCommonStackDepth(targetContainerSegments); + fragment += this.closeDownTo(commonDepth); + fragment += this.openDownTo(targetContainerSegments, leafSegment); + fragment += this.emitLeaf(leafSegment, arg, valueJson); + return fragment; + } + findCommonStackDepth(targetContainer) { + const maxDepth = Math.min(this.pathStack.length - 1, targetContainer.length); + let common = 0; + for(let i = 0; i < maxDepth; i++)if (this.pathStack[i + 1].segment === targetContainer[i]) common++; + else break; + return common + 1; + } + closeDownTo(targetDepth) { + let fragment = ""; + while(this.pathStack.length > targetDepth){ + const entry = this.pathStack.pop(); + fragment += entry.isArray ? "]" : "}"; + } + return fragment; + } + openDownTo(targetContainer, leafSegment) { + let fragment = ""; + const startIdx = this.pathStack.length - 1; + for(let i = startIdx; i < targetContainer.length; i++){ + const seg = targetContainer[i]; + const parentEntry = this.pathStack[this.pathStack.length - 1]; + if (parentEntry.childCount > 0) fragment += ","; + parentEntry.childCount++; + if ("string" == typeof seg) fragment += `${JSON.stringify(seg)}:`; + const childSeg = i + 1 < targetContainer.length ? targetContainer[i + 1] : leafSegment; + const isArray = "number" == typeof childSeg; + fragment += isArray ? "[" : "{"; + this.pathStack.push({ + segment: seg, + isArray, + childCount: 0 + }); + } + return fragment; + } + emitLeaf(leafSegment, arg, valueJson) { + let fragment = ""; + const container = this.pathStack[this.pathStack.length - 1]; + if (container.childCount > 0) fragment += ","; + container.childCount++; + if ("string" == typeof leafSegment) fragment += `${JSON.stringify(leafSegment)}:`; + if (null != arg.stringValue && arg.willContinue) { + fragment += valueJson.slice(0, -1); + this.stringOpen = true; + } else fragment += valueJson; + return fragment; + } + }; + function parsePath(rawPath) { + const segments = []; + for (const part of rawPath.split(".")){ + const bracketIdx = part.indexOf("["); + if (-1 === bracketIdx) segments.push(part); + else { + if (bracketIdx > 0) segments.push(part.slice(0, bracketIdx)); + for (const m of part.matchAll(/\[(\d+)\]/g))segments.push(parseInt(m[1], 10)); + } + } + return segments; + } + function getNestedValue(obj, segments) { + let current = obj; + for (const seg of segments){ + if (null == current || "object" != typeof current) return; + current = current[seg]; + } + return current; + } + function setNestedValue(obj, segments, value1) { + let current = obj; + for(let i = 0; i < segments.length - 1; i++){ + const seg = segments[i]; + const nextSeg = segments[i + 1]; + if (null == current[seg]) current[seg] = "number" == typeof nextSeg ? [] : {}; + current = current[seg]; + } + current[segments[segments.length - 1]] = value1; + } + function resolvePartialArgValue(arg) { + var _a, _b; + const value1 = null != (_b = null != (_a = arg.stringValue) ? _a : arg.numberValue) ? _b : arg.boolValue; + if (null != value1) return { + value: value1, + json: JSON.stringify(value1) + }; + if ("nullValue" in arg) return { + value: null, + json: "null" + }; + } + function mapGoogleGenerativeAIFinishReason({ finishReason, hasToolCalls }) { + switch(finishReason){ + case "STOP": + return hasToolCalls ? "tool-calls" : "stop"; + case "MAX_TOKENS": + return "length"; + case "IMAGE_SAFETY": + case "RECITATION": + case "SAFETY": + case "BLOCKLIST": + case "PROHIBITED_CONTENT": + case "SPII": + return "content-filter"; + case "MALFORMED_FUNCTION_CALL": + return "error"; + case "FINISH_REASON_UNSPECIFIED": + case "OTHER": + default: + return "other"; + } + } + var GoogleGenerativeAILanguageModel = class { + constructor(modelId, config){ + this.specificationVersion = "v3"; + var _a; + this.modelId = modelId; + this.config = config; + this.generateId = null != (_a = config.generateId) ? _a : generateId; + } + get provider() { + return this.config.provider; + } + get supportedUrls() { + var _a, _b, _c; + return null != (_c = null == (_b = (_a = this.config).supportedUrls) ? void 0 : _b.call(_a)) ? _c : {}; + } + async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions }, { isStreaming = false } = {}) { + var _a, _b; + const warnings = []; + const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google"; + let googleOptions = await parseProviderOptions({ + provider: providerOptionsName, + providerOptions, + schema: googleLanguageModelOptions + }); + if (null == googleOptions && "google" !== providerOptionsName) googleOptions = await parseProviderOptions({ + provider: "google", + providerOptions, + schema: googleLanguageModelOptions + }); + const isVertexProvider = this.config.provider.startsWith("google.vertex."); + if ((null == tools ? void 0 : tools.some((tool)=>"provider" === tool.type && "google.vertex_rag_store" === tool.id)) && !isVertexProvider) warnings.push({ + type: "other", + message: `The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).` + }); + if ((null == googleOptions ? void 0 : googleOptions.streamFunctionCallArguments) && !isVertexProvider) warnings.push({ + type: "other", + message: `'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc` + }); + let sanitizedServiceTier = null == googleOptions ? void 0 : googleOptions.serviceTier; + if ((null == googleOptions ? void 0 : googleOptions.serviceTier) && isVertexProvider) sanitizedServiceTier = VertexServiceTierMap[googleOptions.serviceTier]; + const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-"); + const supportsFunctionResponseParts = this.modelId.startsWith("gemini-3"); + const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(prompt, { + isGemmaModel, + providerOptionsName, + supportsFunctionResponseParts + }); + const { tools: googleTools2, toolConfig: googleToolConfig, toolWarnings } = google_dist_prepareTools({ + tools, + toolChoice, + modelId: this.modelId + }); + const streamFunctionCallArguments = isStreaming && isVertexProvider ? null != (_a = null == googleOptions ? void 0 : googleOptions.streamFunctionCallArguments) ? _a : false : void 0; + const toolConfig = googleToolConfig || streamFunctionCallArguments || (null == googleOptions ? void 0 : googleOptions.retrievalConfig) ? { + ...googleToolConfig, + ...streamFunctionCallArguments && { + functionCallingConfig: { + ...null == googleToolConfig ? void 0 : googleToolConfig.functionCallingConfig, + streamFunctionCallArguments: true + } + }, + ...(null == googleOptions ? void 0 : googleOptions.retrievalConfig) && { + retrievalConfig: googleOptions.retrievalConfig + } + } : void 0; + return { + args: { + generationConfig: { + maxOutputTokens, + temperature, + topK, + topP, + frequencyPenalty, + presencePenalty, + stopSequences, + seed, + responseMimeType: (null == responseFormat ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0, + responseSchema: (null == responseFormat ? void 0 : responseFormat.type) === "json" && null != responseFormat.schema && (null != (_b = null == googleOptions ? void 0 : googleOptions.structuredOutputs) ? _b : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0, + ...(null == googleOptions ? void 0 : googleOptions.audioTimestamp) && { + audioTimestamp: googleOptions.audioTimestamp + }, + responseModalities: null == googleOptions ? void 0 : googleOptions.responseModalities, + thinkingConfig: null == googleOptions ? void 0 : googleOptions.thinkingConfig, + ...(null == googleOptions ? void 0 : googleOptions.mediaResolution) && { + mediaResolution: googleOptions.mediaResolution + }, + ...(null == googleOptions ? void 0 : googleOptions.imageConfig) && { + imageConfig: googleOptions.imageConfig + } + }, + contents, + systemInstruction: isGemmaModel ? void 0 : systemInstruction, + safetySettings: null == googleOptions ? void 0 : googleOptions.safetySettings, + tools: googleTools2, + toolConfig, + cachedContent: null == googleOptions ? void 0 : googleOptions.cachedContent, + labels: null == googleOptions ? void 0 : googleOptions.labels, + serviceTier: sanitizedServiceTier + }, + warnings: [ + ...warnings, + ...toolWarnings + ], + providerOptionsName + }; + } + async doGenerate(options1) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; + const { args, warnings, providerOptionsName } = await this.getArgs(options1); + const mergedHeaders = combineHeaders(await dist_resolve(this.config.headers), options1.headers); + const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({ + url: `${this.config.baseURL}/${getModelPath(this.modelId)}:generateContent`, + headers: mergedHeaders, + body: args, + failedResponseHandler: googleFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(dist_responseSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + const candidate = response.candidates[0]; + const content = []; + const parts = null != (_b = null == (_a = candidate.content) ? void 0 : _a.parts) ? _b : []; + const usageMetadata = response.usageMetadata; + let lastCodeExecutionToolCallId; + let lastServerToolCallId; + for (const part of parts)if ("executableCode" in part && (null == (_c = part.executableCode) ? void 0 : _c.code)) { + const toolCallId = this.config.generateId(); + lastCodeExecutionToolCallId = toolCallId; + content.push({ + type: "tool-call", + toolCallId, + toolName: "code_execution", + input: JSON.stringify(part.executableCode), + providerExecuted: true + }); + } else if ("codeExecutionResult" in part && part.codeExecutionResult) { + content.push({ + type: "tool-result", + toolCallId: lastCodeExecutionToolCallId, + toolName: "code_execution", + result: { + outcome: part.codeExecutionResult.outcome, + output: null != (_d = part.codeExecutionResult.output) ? _d : "" + } + }); + lastCodeExecutionToolCallId = void 0; + } else if ("text" in part && null != part.text) { + const thoughtSignatureMetadata = part.thoughtSignature ? { + [providerOptionsName]: { + thoughtSignature: part.thoughtSignature + } + } : void 0; + if (0 === part.text.length) { + if (null != thoughtSignatureMetadata && content.length > 0) { + const lastContent = content[content.length - 1]; + lastContent.providerMetadata = thoughtSignatureMetadata; + } + } else content.push({ + type: true === part.thought ? "reasoning" : "text", + text: part.text, + providerMetadata: thoughtSignatureMetadata + }); + } else if ("functionCall" in part && null != part.functionCall.name && null != part.functionCall.args) content.push({ + type: "tool-call", + toolCallId: this.config.generateId(), + toolName: part.functionCall.name, + input: JSON.stringify(part.functionCall.args), + providerMetadata: part.thoughtSignature ? { + [providerOptionsName]: { + thoughtSignature: part.thoughtSignature + } + } : void 0 + }); + else if ("inlineData" in part) { + const hasThought = true === part.thought; + const hasThoughtSignature = !!part.thoughtSignature; + content.push({ + type: "file", + data: part.inlineData.data, + mediaType: part.inlineData.mimeType, + providerMetadata: hasThought || hasThoughtSignature ? { + [providerOptionsName]: { + ...hasThought ? { + thought: true + } : {}, + ...hasThoughtSignature ? { + thoughtSignature: part.thoughtSignature + } : {} + } + } : void 0 + }); + } else if ("toolCall" in part && part.toolCall) { + const toolCallId = null != (_e = part.toolCall.id) ? _e : this.config.generateId(); + lastServerToolCallId = toolCallId; + content.push({ + type: "tool-call", + toolCallId, + toolName: `server:${part.toolCall.toolType}`, + input: JSON.stringify(null != (_f = part.toolCall.args) ? _f : {}), + providerExecuted: true, + dynamic: true, + providerMetadata: part.thoughtSignature ? { + [providerOptionsName]: { + thoughtSignature: part.thoughtSignature, + serverToolCallId: toolCallId, + serverToolType: part.toolCall.toolType + } + } : { + [providerOptionsName]: { + serverToolCallId: toolCallId, + serverToolType: part.toolCall.toolType + } + } + }); + } else if ("toolResponse" in part && part.toolResponse) { + const responseToolCallId = null != (_g = null != lastServerToolCallId ? lastServerToolCallId : part.toolResponse.id) ? _g : this.config.generateId(); + content.push({ + type: "tool-result", + toolCallId: responseToolCallId, + toolName: `server:${part.toolResponse.toolType}`, + result: null != (_h = part.toolResponse.response) ? _h : {}, + providerMetadata: part.thoughtSignature ? { + [providerOptionsName]: { + thoughtSignature: part.thoughtSignature, + serverToolCallId: responseToolCallId, + serverToolType: part.toolResponse.toolType + } + } : { + [providerOptionsName]: { + serverToolCallId: responseToolCallId, + serverToolType: part.toolResponse.toolType + } + } + }); + lastServerToolCallId = void 0; + } + const sources = null != (_i = extractSources({ + groundingMetadata: candidate.groundingMetadata, + generateId: this.config.generateId + })) ? _i : []; + for (const source of sources)content.push(source); + return { + content, + finishReason: { + unified: mapGoogleGenerativeAIFinishReason({ + finishReason: candidate.finishReason, + hasToolCalls: content.some((part)=>"tool-call" === part.type && !part.providerExecuted) + }), + raw: null != (_j = candidate.finishReason) ? _j : void 0 + }, + usage: convertGoogleGenerativeAIUsage(usageMetadata), + warnings, + providerMetadata: { + [providerOptionsName]: { + promptFeedback: null != (_k = response.promptFeedback) ? _k : null, + groundingMetadata: null != (_l = candidate.groundingMetadata) ? _l : null, + urlContextMetadata: null != (_m = candidate.urlContextMetadata) ? _m : null, + safetyRatings: null != (_n = candidate.safetyRatings) ? _n : null, + usageMetadata: null != usageMetadata ? usageMetadata : null, + finishMessage: null != (_o = candidate.finishMessage) ? _o : null, + serviceTier: null != (_p = response.serviceTier) ? _p : null + } + }, + request: { + body: args + }, + response: { + headers: responseHeaders, + body: rawResponse + } + }; + } + async doStream(options1) { + const { args, warnings, providerOptionsName } = await this.getArgs(options1, { + isStreaming: true + }); + const headers = combineHeaders(await dist_resolve(this.config.headers), options1.headers); + const { responseHeaders, value: response } = await postJsonToApi({ + url: `${this.config.baseURL}/${getModelPath(this.modelId)}:streamGenerateContent?alt=sse`, + headers, + body: args, + failedResponseHandler: googleFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler(dist_chunkSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + let finishReason = { + unified: "other", + raw: void 0 + }; + let usage; + let providerMetadata; + let lastGroundingMetadata = null; + let lastUrlContextMetadata = null; + let serviceTier = null; + const generateId3 = this.config.generateId; + let hasToolCalls = false; + let currentTextBlockId = null; + let currentReasoningBlockId = null; + let blockCounter = 0; + const emittedSourceUrls = /* @__PURE__ */ new Set(); + let lastCodeExecutionToolCallId; + let lastServerToolCallId; + const activeStreamingToolCalls = []; + return { + stream: response.pipeThrough(new TransformStream({ + start (controller) { + controller.enqueue({ + type: "stream-start", + warnings + }); + }, + transform (chunk, controller) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l; + if (options1.includeRawChunks) controller.enqueue({ + type: "raw", + rawValue: chunk.rawValue + }); + if (!chunk.success) return void controller.enqueue({ + type: "error", + error: chunk.error + }); + const value1 = chunk.value; + const usageMetadata = value1.usageMetadata; + if (null != usageMetadata) usage = usageMetadata; + if (null != value1.serviceTier) serviceTier = value1.serviceTier; + const candidate = null == (_a = value1.candidates) ? void 0 : _a[0]; + if (null == candidate) return; + const content = candidate.content; + if (null != candidate.groundingMetadata) lastGroundingMetadata = candidate.groundingMetadata; + if (null != candidate.urlContextMetadata) lastUrlContextMetadata = candidate.urlContextMetadata; + const sources = extractSources({ + groundingMetadata: candidate.groundingMetadata, + generateId: generateId3 + }); + if (null != sources) { + for (const source of sources)if ("url" === source.sourceType && !emittedSourceUrls.has(source.url)) { + emittedSourceUrls.add(source.url); + controller.enqueue(source); + } + } + if (null != content) { + const parts = null != (_b = content.parts) ? _b : []; + for (const part of parts)if ("executableCode" in part && (null == (_c = part.executableCode) ? void 0 : _c.code)) { + const toolCallId = generateId3(); + lastCodeExecutionToolCallId = toolCallId; + controller.enqueue({ + type: "tool-call", + toolCallId, + toolName: "code_execution", + input: JSON.stringify(part.executableCode), + providerExecuted: true + }); + } else if ("codeExecutionResult" in part && part.codeExecutionResult) { + const toolCallId = lastCodeExecutionToolCallId; + if (toolCallId) { + controller.enqueue({ + type: "tool-result", + toolCallId, + toolName: "code_execution", + result: { + outcome: part.codeExecutionResult.outcome, + output: null != (_d = part.codeExecutionResult.output) ? _d : "" + } + }); + lastCodeExecutionToolCallId = void 0; + } + } else if ("text" in part && null != part.text) { + const thoughtSignatureMetadata = part.thoughtSignature ? { + [providerOptionsName]: { + thoughtSignature: part.thoughtSignature + } + } : void 0; + if (0 === part.text.length) { + if (null != thoughtSignatureMetadata && null !== currentTextBlockId) controller.enqueue({ + type: "text-delta", + id: currentTextBlockId, + delta: "", + providerMetadata: thoughtSignatureMetadata + }); + } else if (true === part.thought) { + if (null !== currentTextBlockId) { + controller.enqueue({ + type: "text-end", + id: currentTextBlockId + }); + currentTextBlockId = null; + } + if (null === currentReasoningBlockId) { + currentReasoningBlockId = String(blockCounter++); + controller.enqueue({ + type: "reasoning-start", + id: currentReasoningBlockId, + providerMetadata: thoughtSignatureMetadata + }); + } + controller.enqueue({ + type: "reasoning-delta", + id: currentReasoningBlockId, + delta: part.text, + providerMetadata: thoughtSignatureMetadata + }); + } else { + if (null !== currentReasoningBlockId) { + controller.enqueue({ + type: "reasoning-end", + id: currentReasoningBlockId + }); + currentReasoningBlockId = null; + } + if (null === currentTextBlockId) { + currentTextBlockId = String(blockCounter++); + controller.enqueue({ + type: "text-start", + id: currentTextBlockId, + providerMetadata: thoughtSignatureMetadata + }); + } + controller.enqueue({ + type: "text-delta", + id: currentTextBlockId, + delta: part.text, + providerMetadata: thoughtSignatureMetadata + }); + } + } else if ("inlineData" in part) { + if (null !== currentTextBlockId) { + controller.enqueue({ + type: "text-end", + id: currentTextBlockId + }); + currentTextBlockId = null; + } + if (null !== currentReasoningBlockId) { + controller.enqueue({ + type: "reasoning-end", + id: currentReasoningBlockId + }); + currentReasoningBlockId = null; + } + const hasThought = true === part.thought; + const hasThoughtSignature = !!part.thoughtSignature; + const fileMeta = hasThought || hasThoughtSignature ? { + [providerOptionsName]: { + ...hasThought ? { + thought: true + } : {}, + ...hasThoughtSignature ? { + thoughtSignature: part.thoughtSignature + } : {} + } + } : void 0; + controller.enqueue({ + type: "file", + mediaType: part.inlineData.mimeType, + data: part.inlineData.data, + providerMetadata: fileMeta + }); + } else if ("toolCall" in part && part.toolCall) { + const toolCallId = null != (_e = part.toolCall.id) ? _e : generateId3(); + lastServerToolCallId = toolCallId; + const serverMeta = { + [providerOptionsName]: { + ...part.thoughtSignature ? { + thoughtSignature: part.thoughtSignature + } : {}, + serverToolCallId: toolCallId, + serverToolType: part.toolCall.toolType + } + }; + controller.enqueue({ + type: "tool-call", + toolCallId, + toolName: `server:${part.toolCall.toolType}`, + input: JSON.stringify(null != (_f = part.toolCall.args) ? _f : {}), + providerExecuted: true, + dynamic: true, + providerMetadata: serverMeta + }); + } else if ("toolResponse" in part && part.toolResponse) { + const responseToolCallId = null != (_g = null != lastServerToolCallId ? lastServerToolCallId : part.toolResponse.id) ? _g : generateId3(); + const serverMeta = { + [providerOptionsName]: { + ...part.thoughtSignature ? { + thoughtSignature: part.thoughtSignature + } : {}, + serverToolCallId: responseToolCallId, + serverToolType: part.toolResponse.toolType + } + }; + controller.enqueue({ + type: "tool-result", + toolCallId: responseToolCallId, + toolName: `server:${part.toolResponse.toolType}`, + result: null != (_h = part.toolResponse.response) ? _h : {}, + providerMetadata: serverMeta + }); + lastServerToolCallId = void 0; + } + for (const part of parts){ + if (!("functionCall" in part)) continue; + const providerMeta = part.thoughtSignature ? { + [providerOptionsName]: { + thoughtSignature: part.thoughtSignature + } + } : void 0; + const isStreamingChunk = null != part.functionCall.partialArgs || null != part.functionCall.name && true === part.functionCall.willContinue; + const isTerminalChunk = null == part.functionCall.name && null == part.functionCall.args && null == part.functionCall.partialArgs && null == part.functionCall.willContinue; + const isCompleteCall = null != part.functionCall.name && null != part.functionCall.args && null == part.functionCall.partialArgs; + if (isStreamingChunk) { + if (null != part.functionCall.name && true === part.functionCall.willContinue) { + const toolCallId = generateId3(); + const accumulator = new GoogleJSONAccumulator(); + activeStreamingToolCalls.push({ + toolCallId, + toolName: part.functionCall.name, + accumulator, + providerMetadata: providerMeta + }); + controller.enqueue({ + type: "tool-input-start", + id: toolCallId, + toolName: part.functionCall.name, + providerMetadata: providerMeta + }); + if (null != part.functionCall.partialArgs) { + const { textDelta } = accumulator.processPartialArgs(part.functionCall.partialArgs); + if (textDelta.length > 0) controller.enqueue({ + type: "tool-input-delta", + id: toolCallId, + delta: textDelta, + providerMetadata: providerMeta + }); + } + } else if (null != part.functionCall.partialArgs && activeStreamingToolCalls.length > 0) { + const active = activeStreamingToolCalls[activeStreamingToolCalls.length - 1]; + const { textDelta } = active.accumulator.processPartialArgs(part.functionCall.partialArgs); + if (textDelta.length > 0) controller.enqueue({ + type: "tool-input-delta", + id: active.toolCallId, + delta: textDelta, + providerMetadata: providerMeta + }); + } + } else if (isTerminalChunk && activeStreamingToolCalls.length > 0) { + const active = activeStreamingToolCalls.pop(); + const { finalJSON, closingDelta } = active.accumulator.finalize(); + if (closingDelta.length > 0) controller.enqueue({ + type: "tool-input-delta", + id: active.toolCallId, + delta: closingDelta, + providerMetadata: active.providerMetadata + }); + controller.enqueue({ + type: "tool-input-end", + id: active.toolCallId, + providerMetadata: active.providerMetadata + }); + controller.enqueue({ + type: "tool-call", + toolCallId: active.toolCallId, + toolName: active.toolName, + input: finalJSON, + providerMetadata: active.providerMetadata + }); + hasToolCalls = true; + } else if (isCompleteCall) { + const toolCallId = generateId3(); + const toolName = part.functionCall.name; + const args2 = "string" == typeof part.functionCall.args ? part.functionCall.args : JSON.stringify(null != (_i = part.functionCall.args) ? _i : {}); + controller.enqueue({ + type: "tool-input-start", + id: toolCallId, + toolName, + providerMetadata: providerMeta + }); + controller.enqueue({ + type: "tool-input-delta", + id: toolCallId, + delta: args2, + providerMetadata: providerMeta + }); + controller.enqueue({ + type: "tool-input-end", + id: toolCallId, + providerMetadata: providerMeta + }); + controller.enqueue({ + type: "tool-call", + toolCallId, + toolName, + input: args2, + providerMetadata: providerMeta + }); + hasToolCalls = true; + } + } + } + if (null != candidate.finishReason) { + finishReason = { + unified: mapGoogleGenerativeAIFinishReason({ + finishReason: candidate.finishReason, + hasToolCalls + }), + raw: candidate.finishReason + }; + providerMetadata = { + [providerOptionsName]: { + promptFeedback: null != (_j = value1.promptFeedback) ? _j : null, + groundingMetadata: lastGroundingMetadata, + urlContextMetadata: lastUrlContextMetadata, + safetyRatings: null != (_k = candidate.safetyRatings) ? _k : null, + usageMetadata: null != usageMetadata ? usageMetadata : null, + finishMessage: null != (_l = candidate.finishMessage) ? _l : null, + serviceTier + } + }; + } + }, + flush (controller) { + if (null !== currentTextBlockId) controller.enqueue({ + type: "text-end", + id: currentTextBlockId + }); + if (null !== currentReasoningBlockId) controller.enqueue({ + type: "reasoning-end", + id: currentReasoningBlockId + }); + controller.enqueue({ + type: "finish", + finishReason, + usage: convertGoogleGenerativeAIUsage(usage), + providerMetadata + }); + } + })), + response: { + headers: responseHeaders + }, + request: { + body: args + } + }; + } + }; + function extractSources({ groundingMetadata, generateId: generateId3 }) { + var _a, _b, _c, _d, _e, _f; + if (!(null == groundingMetadata ? void 0 : groundingMetadata.groundingChunks)) return; + const sources = []; + for (const chunk of groundingMetadata.groundingChunks)if (null != chunk.web) sources.push({ + type: "source", + sourceType: "url", + id: generateId3(), + url: chunk.web.uri, + title: null != (_a = chunk.web.title) ? _a : void 0 + }); + else if (null != chunk.image) sources.push({ + type: "source", + sourceType: "url", + id: generateId3(), + url: chunk.image.sourceUri, + title: null != (_b = chunk.image.title) ? _b : void 0 + }); + else if (null != chunk.retrievedContext) { + const uri = chunk.retrievedContext.uri; + const fileSearchStore = chunk.retrievedContext.fileSearchStore; + if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) sources.push({ + type: "source", + sourceType: "url", + id: generateId3(), + url: uri, + title: null != (_c = chunk.retrievedContext.title) ? _c : void 0 + }); + else if (uri) { + const title = null != (_d = chunk.retrievedContext.title) ? _d : "Unknown Document"; + let mediaType = "application/octet-stream"; + let filename; + if (uri.endsWith(".pdf")) { + mediaType = "application/pdf"; + filename = uri.split("/").pop(); + } else if (uri.endsWith(".txt")) { + mediaType = "text/plain"; + filename = uri.split("/").pop(); + } else if (uri.endsWith(".docx")) { + mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; + filename = uri.split("/").pop(); + } else if (uri.endsWith(".doc")) { + mediaType = "application/msword"; + filename = uri.split("/").pop(); + } else if (uri.match(/\.(md|markdown)$/)) { + mediaType = "text/markdown"; + filename = uri.split("/").pop(); + } else filename = uri.split("/").pop(); + sources.push({ + type: "source", + sourceType: "document", + id: generateId3(), + mediaType, + title, + filename + }); + } else if (fileSearchStore) { + const title = null != (_e = chunk.retrievedContext.title) ? _e : "Unknown Document"; + sources.push({ + type: "source", + sourceType: "document", + id: generateId3(), + mediaType: "application/octet-stream", + title, + filename: fileSearchStore.split("/").pop() + }); + } + } else if (null != chunk.maps) { + if (chunk.maps.uri) sources.push({ + type: "source", + sourceType: "url", + id: generateId3(), + url: chunk.maps.uri, + title: null != (_f = chunk.maps.title) ? _f : void 0 + }); + } + return sources.length > 0 ? sources : void 0; + } + var getGroundingMetadataSchema = ()=>schemas_object({ + webSearchQueries: schemas_array(schemas_string()).nullish(), + imageSearchQueries: schemas_array(schemas_string()).nullish(), + retrievalQueries: schemas_array(schemas_string()).nullish(), + searchEntryPoint: schemas_object({ + renderedContent: schemas_string() + }).nullish(), + groundingChunks: schemas_array(schemas_object({ + web: schemas_object({ + uri: schemas_string(), + title: schemas_string().nullish() + }).nullish(), + image: schemas_object({ + sourceUri: schemas_string(), + imageUri: schemas_string(), + title: schemas_string().nullish(), + domain: schemas_string().nullish() + }).nullish(), + retrievedContext: schemas_object({ + uri: schemas_string().nullish(), + title: schemas_string().nullish(), + text: schemas_string().nullish(), + fileSearchStore: schemas_string().nullish() + }).nullish(), + maps: schemas_object({ + uri: schemas_string().nullish(), + title: schemas_string().nullish(), + text: schemas_string().nullish(), + placeId: schemas_string().nullish() + }).nullish() + })).nullish(), + groundingSupports: schemas_array(schemas_object({ + segment: schemas_object({ + startIndex: schemas_number().nullish(), + endIndex: schemas_number().nullish(), + text: schemas_string().nullish() + }).nullish(), + segment_text: schemas_string().nullish(), + groundingChunkIndices: schemas_array(schemas_number()).nullish(), + supportChunkIndices: schemas_array(schemas_number()).nullish(), + confidenceScores: schemas_array(schemas_number()).nullish(), + confidenceScore: schemas_array(schemas_number()).nullish() + })).nullish(), + retrievalMetadata: union([ + schemas_object({ + webDynamicRetrievalScore: schemas_number() + }), + schemas_object({}) + ]).nullish() + }); + var partialArgSchema = schemas_object({ + jsonPath: schemas_string(), + stringValue: schemas_string().nullish(), + numberValue: schemas_number().nullish(), + boolValue: schemas_boolean().nullish(), + nullValue: unknown().nullish(), + willContinue: schemas_boolean().nullish() + }); + var getContentSchema = ()=>schemas_object({ + parts: schemas_array(union([ + schemas_object({ + functionCall: schemas_object({ + name: schemas_string().nullish(), + args: unknown().nullish(), + partialArgs: schemas_array(partialArgSchema).nullish(), + willContinue: schemas_boolean().nullish() + }), + thoughtSignature: schemas_string().nullish() + }), + schemas_object({ + inlineData: schemas_object({ + mimeType: schemas_string(), + data: schemas_string() + }), + thought: schemas_boolean().nullish(), + thoughtSignature: schemas_string().nullish() + }), + schemas_object({ + toolCall: schemas_object({ + toolType: schemas_string(), + args: unknown().nullish(), + id: schemas_string() + }), + thoughtSignature: schemas_string().nullish() + }), + schemas_object({ + toolResponse: schemas_object({ + toolType: schemas_string(), + response: unknown().nullish(), + id: schemas_string() + }), + thoughtSignature: schemas_string().nullish() + }), + schemas_object({ + executableCode: schemas_object({ + language: schemas_string(), + code: schemas_string() + }).nullish(), + codeExecutionResult: schemas_object({ + outcome: schemas_string(), + output: schemas_string().nullish() + }).nullish(), + text: schemas_string().nullish(), + thought: schemas_boolean().nullish(), + thoughtSignature: schemas_string().nullish() + }) + ])).nullish() + }); + var getSafetyRatingSchema = ()=>schemas_object({ + category: schemas_string().nullish(), + probability: schemas_string().nullish(), + probabilityScore: schemas_number().nullish(), + severity: schemas_string().nullish(), + severityScore: schemas_number().nullish(), + blocked: schemas_boolean().nullish() + }); + var tokenDetailsSchema = schemas_array(schemas_object({ + modality: schemas_string(), + tokenCount: schemas_number() + })).nullish(); + var usageSchema = schemas_object({ + cachedContentTokenCount: schemas_number().nullish(), + thoughtsTokenCount: schemas_number().nullish(), + promptTokenCount: schemas_number().nullish(), + candidatesTokenCount: schemas_number().nullish(), + totalTokenCount: schemas_number().nullish(), + trafficType: schemas_string().nullish(), + promptTokensDetails: tokenDetailsSchema, + candidatesTokensDetails: tokenDetailsSchema + }); + var getUrlContextMetadataSchema = ()=>schemas_object({ + urlMetadata: schemas_array(schemas_object({ + retrievedUrl: schemas_string(), + urlRetrievalStatus: schemas_string() + })).nullish() + }); + var dist_responseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + candidates: schemas_array(schemas_object({ + content: getContentSchema().nullish().or(schemas_object({}).strict()), + finishReason: schemas_string().nullish(), + finishMessage: schemas_string().nullish(), + safetyRatings: schemas_array(getSafetyRatingSchema()).nullish(), + groundingMetadata: getGroundingMetadataSchema().nullish(), + urlContextMetadata: getUrlContextMetadataSchema().nullish() + })), + usageMetadata: usageSchema.nullish(), + promptFeedback: schemas_object({ + blockReason: schemas_string().nullish(), + safetyRatings: schemas_array(getSafetyRatingSchema()).nullish() + }).nullish(), + serviceTier: schemas_string().nullish() + }))); + var dist_chunkSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + candidates: schemas_array(schemas_object({ + content: getContentSchema().nullish(), + finishReason: schemas_string().nullish(), + finishMessage: schemas_string().nullish(), + safetyRatings: schemas_array(getSafetyRatingSchema()).nullish(), + groundingMetadata: getGroundingMetadataSchema().nullish(), + urlContextMetadata: getUrlContextMetadataSchema().nullish() + })).nullish(), + usageMetadata: usageSchema.nullish(), + promptFeedback: schemas_object({ + blockReason: schemas_string().nullish(), + safetyRatings: schemas_array(getSafetyRatingSchema()).nullish() + }).nullish(), + serviceTier: schemas_string().nullish() + }))); + var codeExecution = createProviderToolFactoryWithOutputSchema({ + id: "google.code_execution", + inputSchema: schemas_object({ + language: schemas_string().describe("The programming language of the code."), + code: schemas_string().describe("The code to be executed.") + }), + outputSchema: schemas_object({ + outcome: schemas_string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'), + output: schemas_string().describe("The output from the code execution.") + }) + }); + var enterpriseWebSearch = createProviderToolFactory({ + id: "google.enterprise_web_search", + inputSchema: dist_lazySchema(()=>dist_zodSchema(schemas_object({}))) + }); + var fileSearchArgsBaseSchema = schemas_object({ + fileSearchStoreNames: schemas_array(schemas_string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"), + topK: schemas_number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(), + metadataFilter: schemas_string().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional() + }).passthrough(); + var fileSearchArgsSchema = dist_lazySchema(()=>dist_zodSchema(fileSearchArgsBaseSchema)); + var fileSearch = createProviderToolFactory({ + id: "google.file_search", + inputSchema: fileSearchArgsSchema + }); + var googleMaps = createProviderToolFactory({ + id: "google.google_maps", + inputSchema: dist_lazySchema(()=>dist_zodSchema(schemas_object({}))) + }); + var googleSearchToolArgsBaseSchema = schemas_object({ + searchTypes: schemas_object({ + webSearch: schemas_object({}).optional(), + imageSearch: schemas_object({}).optional() + }).optional(), + timeRangeFilter: schemas_object({ + startTime: schemas_string(), + endTime: schemas_string() + }).optional() + }).passthrough(); + var googleSearchToolArgsSchema = dist_lazySchema(()=>dist_zodSchema(googleSearchToolArgsBaseSchema)); + var googleSearch = createProviderToolFactory({ + id: "google.google_search", + inputSchema: googleSearchToolArgsSchema + }); + var urlContext = createProviderToolFactory({ + id: "google.url_context", + inputSchema: dist_lazySchema(()=>dist_zodSchema(schemas_object({}))) + }); + var vertexRagStore = createProviderToolFactory({ + id: "google.vertex_rag_store", + inputSchema: schemas_object({ + ragCorpus: schemas_string(), + topK: schemas_number().optional() + }) + }); + var googleTools = { + googleSearch, + enterpriseWebSearch, + googleMaps, + urlContext, + fileSearch, + codeExecution, + vertexRagStore + }; + var GoogleGenerativeAIImageModel = class { + constructor(modelId, settings, config){ + this.modelId = modelId; + this.settings = settings; + this.config = config; + this.specificationVersion = "v3"; + } + get maxImagesPerCall() { + if (null != this.settings.maxImagesPerCall) return this.settings.maxImagesPerCall; + if (isGeminiModel(this.modelId)) return 10; + return 4; + } + get provider() { + return this.config.provider; + } + async doGenerate(options1) { + if (isGeminiModel(this.modelId)) return this.doGenerateGemini(options1); + return this.doGenerateImagen(options1); + } + async doGenerateImagen(options1) { + var _a, _b, _c; + const { prompt, n = 1, size, aspectRatio = "1:1", seed, providerOptions, headers, abortSignal, files, mask } = options1; + const warnings = []; + if (null != files && files.length > 0) throw new Error("Google Generative AI does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities."); + if (null != mask) throw new Error("Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities."); + if (null != size) warnings.push({ + type: "unsupported", + feature: "size", + details: "This model does not support the `size` option. Use `aspectRatio` instead." + }); + if (null != seed) warnings.push({ + type: "unsupported", + feature: "seed", + details: "This model does not support the `seed` option through this provider." + }); + const googleOptions = await parseProviderOptions({ + provider: "google", + providerOptions, + schema: googleImageModelOptionsSchema + }); + const currentDate = null != (_c = null == (_b = null == (_a = this.config._internal) ? void 0 : _a.currentDate) ? void 0 : _b.call(_a)) ? _c : /* @__PURE__ */ new Date(); + const parameters = { + sampleCount: n + }; + if (null != aspectRatio) parameters.aspectRatio = aspectRatio; + if (googleOptions) Object.assign(parameters, googleOptions); + const body = { + instances: [ + { + prompt + } + ], + parameters + }; + const { responseHeaders, value: response } = await postJsonToApi({ + url: `${this.config.baseURL}/models/${this.modelId}:predict`, + headers: combineHeaders(await dist_resolve(this.config.headers), headers), + body, + failedResponseHandler: googleFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(googleImageResponseSchema), + abortSignal, + fetch: this.config.fetch + }); + return { + images: response.predictions.map((p)=>p.bytesBase64Encoded), + warnings, + providerMetadata: { + google: { + images: response.predictions.map(()=>({})) + } + }, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders + } + }; + } + async doGenerateGemini(options1) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i; + const { prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal, files, mask } = options1; + const warnings = []; + if (null != mask) throw new Error("Gemini image models do not support mask-based image editing."); + if (null != n && n > 1) throw new Error("Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter."); + if (null != size) warnings.push({ + type: "unsupported", + feature: "size", + details: "This model does not support the `size` option. Use `aspectRatio` instead." + }); + const userContent = []; + if (null != prompt) userContent.push({ + type: "text", + text: prompt + }); + if (null != files && files.length > 0) for (const file of files)if ("url" === file.type) userContent.push({ + type: "file", + data: new URL(file.url), + mediaType: "image/*" + }); + else userContent.push({ + type: "file", + data: "string" == typeof file.data ? file.data : new Uint8Array(file.data), + mediaType: file.mediaType + }); + const languageModelPrompt = [ + { + role: "user", + content: userContent + } + ]; + const languageModel = new GoogleGenerativeAILanguageModel(this.modelId, { + provider: this.config.provider, + baseURL: this.config.baseURL, + headers: null != (_a = this.config.headers) ? _a : {}, + fetch: this.config.fetch, + generateId: null != (_b = this.config.generateId) ? _b : generateId + }); + const result = await languageModel.doGenerate({ + prompt: languageModelPrompt, + seed, + providerOptions: { + google: { + responseModalities: [ + "IMAGE" + ], + imageConfig: aspectRatio ? { + aspectRatio + } : void 0, + ...null != (_c = null == providerOptions ? void 0 : providerOptions.google) ? _c : {} + } + }, + headers, + abortSignal + }); + const currentDate = null != (_f = null == (_e = null == (_d = this.config._internal) ? void 0 : _d.currentDate) ? void 0 : _e.call(_d)) ? _f : /* @__PURE__ */ new Date(); + const images = []; + for (const part of result.content)if ("file" === part.type && part.mediaType.startsWith("image/")) images.push(convertToBase64(part.data)); + return { + images, + warnings, + providerMetadata: { + google: { + images: images.map(()=>({})) + } + }, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: null == (_g = result.response) ? void 0 : _g.headers + }, + usage: result.usage ? { + inputTokens: result.usage.inputTokens.total, + outputTokens: result.usage.outputTokens.total, + totalTokens: (null != (_h = result.usage.inputTokens.total) ? _h : 0) + (null != (_i = result.usage.outputTokens.total) ? _i : 0) + } : void 0 + }; + } + }; + function isGeminiModel(modelId) { + return modelId.startsWith("gemini-"); + } + var googleImageResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + predictions: schemas_array(schemas_object({ + bytesBase64Encoded: schemas_string() + })).default([]) + }))); + var googleImageModelOptionsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + personGeneration: schemas_enum([ + "dont_allow", + "allow_adult", + "allow_all" + ]).nullish(), + aspectRatio: schemas_enum([ + "1:1", + "3:4", + "4:3", + "9:16", + "16:9" + ]).nullish() + }))); + var GoogleGenerativeAIVideoModel = class { + constructor(modelId, config){ + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v3"; + } + get provider() { + return this.config.provider; + } + get maxVideosPerCall() { + return 4; + } + async doGenerate(options1) { + var _a, _b, _c, _d, _e, _f, _g, _h; + const currentDate = null != (_c = null == (_b = null == (_a = this.config._internal) ? void 0 : _a.currentDate) ? void 0 : _b.call(_a)) ? _c : /* @__PURE__ */ new Date(); + const warnings = []; + const googleOptions = await parseProviderOptions({ + provider: "google", + providerOptions: options1.providerOptions, + schema: googleVideoModelOptionsSchema + }); + const instances = [ + {} + ]; + const instance = instances[0]; + if (null != options1.prompt) instance.prompt = options1.prompt; + if (null != options1.image) if ("url" === options1.image.type) warnings.push({ + type: "unsupported", + feature: "URL-based image input", + details: "Google Generative AI video models require base64-encoded images. URL will be ignored." + }); + else { + const base64Data = "string" == typeof options1.image.data ? options1.image.data : convertUint8ArrayToBase64(options1.image.data); + instance.image = { + inlineData: { + mimeType: options1.image.mediaType || "image/png", + data: base64Data + } + }; + } + if ((null == googleOptions ? void 0 : googleOptions.referenceImages) != null) instance.referenceImages = googleOptions.referenceImages.map((refImg)=>{ + if (refImg.bytesBase64Encoded) return { + inlineData: { + mimeType: "image/png", + data: refImg.bytesBase64Encoded + } + }; + if (refImg.gcsUri) return { + gcsUri: refImg.gcsUri + }; + return refImg; + }); + const parameters = { + sampleCount: options1.n + }; + if (options1.aspectRatio) parameters.aspectRatio = options1.aspectRatio; + if (options1.resolution) { + const resolutionMap = { + "1280x720": "720p", + "1920x1080": "1080p", + "3840x2160": "4k" + }; + parameters.resolution = resolutionMap[options1.resolution] || options1.resolution; + } + if (options1.duration) parameters.durationSeconds = options1.duration; + if (options1.seed) parameters.seed = options1.seed; + if (null != googleOptions) { + const opts = googleOptions; + if (void 0 !== opts.personGeneration && null !== opts.personGeneration) parameters.personGeneration = opts.personGeneration; + if (void 0 !== opts.negativePrompt && null !== opts.negativePrompt) parameters.negativePrompt = opts.negativePrompt; + for (const [key, value1] of Object.entries(opts))if (![ + "pollIntervalMs", + "pollTimeoutMs", + "personGeneration", + "negativePrompt", + "referenceImages" + ].includes(key)) parameters[key] = value1; + } + const { value: operation } = await postJsonToApi({ + url: `${this.config.baseURL}/models/${this.modelId}:predictLongRunning`, + headers: combineHeaders(await dist_resolve(this.config.headers), options1.headers), + body: { + instances, + parameters + }, + successfulResponseHandler: createJsonResponseHandler(googleOperationSchema), + failedResponseHandler: googleFailedResponseHandler, + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + const operationName = operation.name; + if (!operationName) throw new AISDKError({ + name: "GOOGLE_VIDEO_GENERATION_ERROR", + message: "No operation name returned from API" + }); + const pollIntervalMs = null != (_d = null == googleOptions ? void 0 : googleOptions.pollIntervalMs) ? _d : 1e4; + const pollTimeoutMs = null != (_e = null == googleOptions ? void 0 : googleOptions.pollTimeoutMs) ? _e : 6e5; + const startTime = Date.now(); + let finalOperation = operation; + let responseHeaders; + while(!finalOperation.done){ + if (Date.now() - startTime > pollTimeoutMs) throw new AISDKError({ + name: "GOOGLE_VIDEO_GENERATION_TIMEOUT", + message: `Video generation timed out after ${pollTimeoutMs}ms` + }); + await delay(pollIntervalMs); + if (null == (_f = options1.abortSignal) ? void 0 : _f.aborted) throw new AISDKError({ + name: "GOOGLE_VIDEO_GENERATION_ABORTED", + message: "Video generation request was aborted" + }); + const { value: statusOperation, responseHeaders: pollHeaders } = await getFromApi({ + url: `${this.config.baseURL}/${operationName}`, + headers: combineHeaders(await dist_resolve(this.config.headers), options1.headers), + successfulResponseHandler: createJsonResponseHandler(googleOperationSchema), + failedResponseHandler: googleFailedResponseHandler, + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + finalOperation = statusOperation; + responseHeaders = pollHeaders; + } + if (finalOperation.error) throw new AISDKError({ + name: "GOOGLE_VIDEO_GENERATION_FAILED", + message: `Video generation failed: ${finalOperation.error.message}` + }); + const response = finalOperation.response; + if (!(null == (_g = null == response ? void 0 : response.generateVideoResponse) ? void 0 : _g.generatedSamples) || 0 === response.generateVideoResponse.generatedSamples.length) throw new AISDKError({ + name: "GOOGLE_VIDEO_GENERATION_ERROR", + message: `No videos in response. Response: ${JSON.stringify(finalOperation)}` + }); + const videos = []; + const videoMetadata = []; + const resolvedHeaders = await dist_resolve(this.config.headers); + const apiKey = null == resolvedHeaders ? void 0 : resolvedHeaders["x-goog-api-key"]; + for (const generatedSample of response.generateVideoResponse.generatedSamples)if (null == (_h = generatedSample.video) ? void 0 : _h.uri) { + const urlWithAuth = apiKey ? `${generatedSample.video.uri}${generatedSample.video.uri.includes("?") ? "&" : "?"}key=${apiKey}` : generatedSample.video.uri; + videos.push({ + type: "url", + url: urlWithAuth, + mediaType: "video/mp4" + }); + videoMetadata.push({ + uri: generatedSample.video.uri + }); + } + if (0 === videos.length) throw new AISDKError({ + name: "GOOGLE_VIDEO_GENERATION_ERROR", + message: "No valid videos in response" + }); + return { + videos, + warnings, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders + }, + providerMetadata: { + google: { + videos: videoMetadata + } + } + }; + } + }; + var googleOperationSchema = schemas_object({ + name: schemas_string().nullish(), + done: schemas_boolean().nullish(), + error: schemas_object({ + code: schemas_number().nullish(), + message: schemas_string(), + status: schemas_string().nullish() + }).nullish(), + response: schemas_object({ + generateVideoResponse: schemas_object({ + generatedSamples: schemas_array(schemas_object({ + video: schemas_object({ + uri: schemas_string().nullish() + }).nullish() + })).nullish() + }).nullish() + }).nullish() + }); + var googleVideoModelOptionsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + pollIntervalMs: schemas_number().positive().nullish(), + pollTimeoutMs: schemas_number().positive().nullish(), + personGeneration: schemas_enum([ + "dont_allow", + "allow_adult", + "allow_all" + ]).nullish(), + negativePrompt: schemas_string().nullish(), + referenceImages: schemas_array(schemas_object({ + bytesBase64Encoded: schemas_string().nullish(), + gcsUri: schemas_string().nullish() + })).nullish() + }).passthrough())); + function createGoogleGenerativeAI(options1 = {}) { + var _a, _b; + const baseURL = null != (_a = withoutTrailingSlash(options1.baseURL)) ? _a : "https://generativelanguage.googleapis.com/v1beta"; + const providerName = null != (_b = options1.name) ? _b : "google.generative-ai"; + const getHeaders = ()=>withUserAgentSuffix({ + "x-goog-api-key": loadApiKey({ + apiKey: options1.apiKey, + environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY", + description: "Google Generative AI" + }), + ...options1.headers + }, `ai-sdk/google/${google_dist_VERSION}`); + const createChatModel = (modelId)=>{ + var _a2; + return new GoogleGenerativeAILanguageModel(modelId, { + provider: providerName, + baseURL, + headers: getHeaders, + generateId: null != (_a2 = options1.generateId) ? _a2 : generateId, + supportedUrls: ()=>({ + "*": [ + new RegExp(`^${baseURL}/files/.*$`), + new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"), + new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$") + ] + }), + fetch: options1.fetch + }); + }; + const createEmbeddingModel = (modelId)=>new GoogleGenerativeAIEmbeddingModel(modelId, { + provider: providerName, + baseURL, + headers: getHeaders, + fetch: options1.fetch + }); + const createImageModel = (modelId, settings = {})=>new GoogleGenerativeAIImageModel(modelId, settings, { + provider: providerName, + baseURL, + headers: getHeaders, + fetch: options1.fetch + }); + const createVideoModel = (modelId)=>{ + var _a2; + return new GoogleGenerativeAIVideoModel(modelId, { + provider: providerName, + baseURL, + headers: getHeaders, + fetch: options1.fetch, + generateId: null != (_a2 = options1.generateId) ? _a2 : generateId + }); + }; + const provider = function(modelId) { + if (new.target) throw new Error("The Google Generative AI model function cannot be called with the new keyword."); + return createChatModel(modelId); + }; + provider.specificationVersion = "v3"; + provider.languageModel = createChatModel; + provider.chat = createChatModel; + provider.generativeAI = createChatModel; + provider.embedding = createEmbeddingModel; + provider.embeddingModel = createEmbeddingModel; + provider.textEmbedding = createEmbeddingModel; + provider.textEmbeddingModel = createEmbeddingModel; + provider.image = createImageModel; + provider.imageModel = createImageModel; + provider.video = createVideoModel; + provider.videoModel = createVideoModel; + provider.tools = googleTools; + return provider; + } + createGoogleGenerativeAI(); + var openaiErrorDataSchema = schemas_object({ + error: schemas_object({ + message: schemas_string(), + type: schemas_string().nullish(), + param: any().nullish(), + code: union([ + schemas_string(), + schemas_number() + ]).nullish() + }) + }); + var openaiFailedResponseHandler = createJsonErrorResponseHandler({ + errorSchema: openaiErrorDataSchema, + errorToMessage: (data)=>data.error.message + }); + function getOpenAILanguageModelCapabilities(modelId) { + const supportsFlexProcessing = modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"); + const supportsPriorityProcessing = modelId.startsWith("gpt-4") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-nano") && !modelId.startsWith("gpt-5-chat") && !modelId.startsWith("gpt-5.4-nano") || modelId.startsWith("o3") || modelId.startsWith("o4-mini"); + const isReasoningModel = modelId.startsWith("o1") || modelId.startsWith("o3") || modelId.startsWith("o4-mini") || modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"); + const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2") || modelId.startsWith("gpt-5.3") || modelId.startsWith("gpt-5.4"); + const systemMessageMode = isReasoningModel ? "developer" : "system"; + return { + supportsFlexProcessing, + supportsPriorityProcessing, + isReasoningModel, + systemMessageMode, + supportsNonReasoningParameters + }; + } + function convertOpenAIChatUsage(usage) { + var _a, _b, _c, _d, _e, _f; + if (null == usage) return { + inputTokens: { + total: void 0, + noCache: void 0, + cacheRead: void 0, + cacheWrite: void 0 + }, + outputTokens: { + total: void 0, + text: void 0, + reasoning: void 0 + }, + raw: void 0 + }; + const promptTokens = null != (_a = usage.prompt_tokens) ? _a : 0; + const completionTokens = null != (_b = usage.completion_tokens) ? _b : 0; + const cachedTokens = null != (_d = null == (_c = usage.prompt_tokens_details) ? void 0 : _c.cached_tokens) ? _d : 0; + const reasoningTokens = null != (_f = null == (_e = usage.completion_tokens_details) ? void 0 : _e.reasoning_tokens) ? _f : 0; + return { + inputTokens: { + total: promptTokens, + noCache: promptTokens - cachedTokens, + cacheRead: cachedTokens, + cacheWrite: void 0 + }, + outputTokens: { + total: completionTokens, + text: completionTokens - reasoningTokens, + reasoning: reasoningTokens + }, + raw: usage + }; + } + function convertToOpenAIChatMessages({ prompt, systemMessageMode = "system" }) { + var _a; + const messages = []; + const warnings = []; + for (const { role, content } of prompt)switch(role){ + case "system": + switch(systemMessageMode){ + case "system": + messages.push({ + role: "system", + content + }); + break; + case "developer": + messages.push({ + role: "developer", + content + }); + break; + case "remove": + warnings.push({ + type: "other", + message: "system messages are removed for this model" + }); + break; + default: + { + const _exhaustiveCheck = systemMessageMode; + throw new Error(`Unsupported system message mode: ${_exhaustiveCheck}`); + } + } + break; + case "user": + if (1 === content.length && "text" === content[0].type) { + messages.push({ + role: "user", + content: content[0].text + }); + break; + } + messages.push({ + role: "user", + content: content.map((part, index)=>{ + var _a2, _b, _c; + switch(part.type){ + case "text": + return { + type: "text", + text: part.text + }; + case "file": + if (part.mediaType.startsWith("image/")) { + const mediaType = "image/*" === part.mediaType ? "image/jpeg" : part.mediaType; + return { + type: "image_url", + image_url: { + url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`, + detail: null == (_b = null == (_a2 = part.providerOptions) ? void 0 : _a2.openai) ? void 0 : _b.imageDetail + } + }; + } + if (part.mediaType.startsWith("audio/")) { + if (part.data instanceof URL) throw new UnsupportedFunctionalityError({ + functionality: "audio file parts with URLs" + }); + switch(part.mediaType){ + case "audio/wav": + return { + type: "input_audio", + input_audio: { + data: convertToBase64(part.data), + format: "wav" + } + }; + case "audio/mp3": + case "audio/mpeg": + return { + type: "input_audio", + input_audio: { + data: convertToBase64(part.data), + format: "mp3" + } + }; + default: + throw new UnsupportedFunctionalityError({ + functionality: `audio content parts with media type ${part.mediaType}` + }); + } + } + if ("application/pdf" === part.mediaType) { + if (part.data instanceof URL) throw new UnsupportedFunctionalityError({ + functionality: "PDF file parts with URLs" + }); + return { + type: "file", + file: "string" == typeof part.data && part.data.startsWith("file-") ? { + file_id: part.data + } : { + filename: null != (_c = part.filename) ? _c : `part-${index}.pdf`, + file_data: `data:application/pdf;base64,${convertToBase64(part.data)}` + } + }; + } else throw new UnsupportedFunctionalityError({ + functionality: `file part media type ${part.mediaType}` + }); + } + }) + }); + break; + case "assistant": + { + let text = ""; + const toolCalls = []; + for (const part of content)switch(part.type){ + case "text": + text += part.text; + break; + case "tool-call": + toolCalls.push({ + id: part.toolCallId, + type: "function", + function: { + name: part.toolName, + arguments: JSON.stringify(part.input) + } + }); + break; + } + messages.push({ + role: "assistant", + content: text, + tool_calls: toolCalls.length > 0 ? toolCalls : void 0 + }); + break; + } + case "tool": + for (const toolResponse of content){ + if ("tool-approval-response" === toolResponse.type) continue; + const output = toolResponse.output; + let contentValue; + switch(output.type){ + case "text": + case "error-text": + contentValue = output.value; + break; + case "execution-denied": + contentValue = null != (_a = output.reason) ? _a : "Tool execution denied."; + break; + case "content": + case "json": + case "error-json": + contentValue = JSON.stringify(output.value); + break; + } + messages.push({ + role: "tool", + tool_call_id: toolResponse.toolCallId, + content: contentValue + }); + } + break; + default: + { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + return { + messages, + warnings + }; + } + function dist_getResponseMetadata({ id, model, created }) { + return { + id: null != id ? id : void 0, + modelId: null != model ? model : void 0, + timestamp: created ? new Date(1e3 * created) : void 0 + }; + } + function mapOpenAIFinishReason(finishReason) { + switch(finishReason){ + case "stop": + return "stop"; + case "length": + return "length"; + case "content_filter": + return "content-filter"; + case "function_call": + case "tool_calls": + return "tool-calls"; + default: + return "other"; + } + } + var openaiChatResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + id: schemas_string().nullish(), + created: schemas_number().nullish(), + model: schemas_string().nullish(), + choices: schemas_array(schemas_object({ + message: schemas_object({ + role: schemas_literal("assistant").nullish(), + content: schemas_string().nullish(), + tool_calls: schemas_array(schemas_object({ + id: schemas_string().nullish(), + type: schemas_literal("function"), + function: schemas_object({ + name: schemas_string(), + arguments: schemas_string() + }) + })).nullish(), + annotations: schemas_array(schemas_object({ + type: schemas_literal("url_citation"), + url_citation: schemas_object({ + start_index: schemas_number(), + end_index: schemas_number(), + url: schemas_string(), + title: schemas_string() + }) + })).nullish() + }), + index: schemas_number(), + logprobs: schemas_object({ + content: schemas_array(schemas_object({ + token: schemas_string(), + logprob: schemas_number(), + top_logprobs: schemas_array(schemas_object({ + token: schemas_string(), + logprob: schemas_number() + })) + })).nullish() + }).nullish(), + finish_reason: schemas_string().nullish() + })), + usage: schemas_object({ + prompt_tokens: schemas_number().nullish(), + completion_tokens: schemas_number().nullish(), + total_tokens: schemas_number().nullish(), + prompt_tokens_details: schemas_object({ + cached_tokens: schemas_number().nullish() + }).nullish(), + completion_tokens_details: schemas_object({ + reasoning_tokens: schemas_number().nullish(), + accepted_prediction_tokens: schemas_number().nullish(), + rejected_prediction_tokens: schemas_number().nullish() + }).nullish() + }).nullish() + }))); + var openaiChatChunkSchema = dist_lazySchema(()=>dist_zodSchema(union([ + schemas_object({ + id: schemas_string().nullish(), + created: schemas_number().nullish(), + model: schemas_string().nullish(), + choices: schemas_array(schemas_object({ + delta: schemas_object({ + role: schemas_enum([ + "assistant" + ]).nullish(), + content: schemas_string().nullish(), + tool_calls: schemas_array(schemas_object({ + index: schemas_number(), + id: schemas_string().nullish(), + type: schemas_literal("function").nullish(), + function: schemas_object({ + name: schemas_string().nullish(), + arguments: schemas_string().nullish() + }) + })).nullish(), + annotations: schemas_array(schemas_object({ + type: schemas_literal("url_citation"), + url_citation: schemas_object({ + start_index: schemas_number(), + end_index: schemas_number(), + url: schemas_string(), + title: schemas_string() + }) + })).nullish() + }).nullish(), + logprobs: schemas_object({ + content: schemas_array(schemas_object({ + token: schemas_string(), + logprob: schemas_number(), + top_logprobs: schemas_array(schemas_object({ + token: schemas_string(), + logprob: schemas_number() + })) + })).nullish() + }).nullish(), + finish_reason: schemas_string().nullish(), + index: schemas_number() + })), + usage: schemas_object({ + prompt_tokens: schemas_number().nullish(), + completion_tokens: schemas_number().nullish(), + total_tokens: schemas_number().nullish(), + prompt_tokens_details: schemas_object({ + cached_tokens: schemas_number().nullish() + }).nullish(), + completion_tokens_details: schemas_object({ + reasoning_tokens: schemas_number().nullish(), + accepted_prediction_tokens: schemas_number().nullish(), + rejected_prediction_tokens: schemas_number().nullish() + }).nullish() + }).nullish() + }), + openaiErrorDataSchema + ]))); + var openaiLanguageModelChatOptions = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + logitBias: schemas_record(coerce_number(), schemas_number()).optional(), + logprobs: union([ + schemas_boolean(), + schemas_number() + ]).optional(), + parallelToolCalls: schemas_boolean().optional(), + user: schemas_string().optional(), + reasoningEffort: schemas_enum([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh" + ]).optional(), + maxCompletionTokens: schemas_number().optional(), + store: schemas_boolean().optional(), + metadata: schemas_record(schemas_string().max(64), schemas_string().max(512)).optional(), + prediction: schemas_record(schemas_string(), any()).optional(), + serviceTier: schemas_enum([ + "auto", + "flex", + "priority", + "default" + ]).optional(), + strictJsonSchema: schemas_boolean().optional(), + textVerbosity: schemas_enum([ + "low", + "medium", + "high" + ]).optional(), + promptCacheKey: schemas_string().optional(), + promptCacheRetention: schemas_enum([ + "in_memory", + "24h" + ]).optional(), + safetyIdentifier: schemas_string().optional(), + systemMessageMode: schemas_enum([ + "system", + "developer", + "remove" + ]).optional(), + forceReasoning: schemas_boolean().optional() + }))); + function prepareChatTools({ tools, toolChoice }) { + tools = (null == tools ? void 0 : tools.length) ? tools : void 0; + const toolWarnings = []; + if (null == tools) return { + tools: void 0, + toolChoice: void 0, + toolWarnings + }; + const openaiTools2 = []; + for (const tool of tools)switch(tool.type){ + case "function": + openaiTools2.push({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.inputSchema, + ...null != tool.strict ? { + strict: tool.strict + } : {} + } + }); + break; + default: + toolWarnings.push({ + type: "unsupported", + feature: `tool type: ${tool.type}` + }); + break; + } + if (null == toolChoice) return { + tools: openaiTools2, + toolChoice: void 0, + toolWarnings + }; + const type = toolChoice.type; + switch(type){ + case "auto": + case "none": + case "required": + return { + tools: openaiTools2, + toolChoice: type, + toolWarnings + }; + case "tool": + return { + tools: openaiTools2, + toolChoice: { + type: "function", + function: { + name: toolChoice.toolName + } + }, + toolWarnings + }; + default: + { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `tool choice type: ${_exhaustiveCheck}` + }); + } + } + } + var OpenAIChatLanguageModel = class { + constructor(modelId, config){ + this.specificationVersion = "v3"; + this.supportedUrls = { + "image/*": [ + /^https?:\/\/.*$/ + ] + }; + this.modelId = modelId; + this.config = config; + } + get provider() { + return this.config.provider; + } + async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions }) { + var _a, _b, _c, _d, _e; + const warnings = []; + const openaiOptions = null != (_a = await parseProviderOptions({ + provider: "openai", + providerOptions, + schema: openaiLanguageModelChatOptions + })) ? _a : {}; + const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId); + const isReasoningModel = null != (_b = openaiOptions.forceReasoning) ? _b : modelCapabilities.isReasoningModel; + if (null != topK) warnings.push({ + type: "unsupported", + feature: "topK" + }); + const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages({ + prompt, + systemMessageMode: null != (_c = openaiOptions.systemMessageMode) ? _c : isReasoningModel ? "developer" : modelCapabilities.systemMessageMode + }); + warnings.push(...messageWarnings); + const strictJsonSchema = null != (_d = openaiOptions.strictJsonSchema) ? _d : true; + const baseArgs = { + model: this.modelId, + logit_bias: openaiOptions.logitBias, + logprobs: true === openaiOptions.logprobs || "number" == typeof openaiOptions.logprobs ? true : void 0, + top_logprobs: "number" == typeof openaiOptions.logprobs ? openaiOptions.logprobs : "boolean" == typeof openaiOptions.logprobs ? openaiOptions.logprobs ? 0 : void 0 : void 0, + user: openaiOptions.user, + parallel_tool_calls: openaiOptions.parallelToolCalls, + max_tokens: maxOutputTokens, + temperature, + top_p: topP, + frequency_penalty: frequencyPenalty, + presence_penalty: presencePenalty, + response_format: (null == responseFormat ? void 0 : responseFormat.type) === "json" ? null != responseFormat.schema ? { + type: "json_schema", + json_schema: { + schema: responseFormat.schema, + strict: strictJsonSchema, + name: null != (_e = responseFormat.name) ? _e : "response", + description: responseFormat.description + } + } : { + type: "json_object" + } : void 0, + stop: stopSequences, + seed, + verbosity: openaiOptions.textVerbosity, + max_completion_tokens: openaiOptions.maxCompletionTokens, + store: openaiOptions.store, + metadata: openaiOptions.metadata, + prediction: openaiOptions.prediction, + reasoning_effort: openaiOptions.reasoningEffort, + service_tier: openaiOptions.serviceTier, + prompt_cache_key: openaiOptions.promptCacheKey, + prompt_cache_retention: openaiOptions.promptCacheRetention, + safety_identifier: openaiOptions.safetyIdentifier, + messages + }; + if (isReasoningModel) { + if ("none" !== openaiOptions.reasoningEffort || !modelCapabilities.supportsNonReasoningParameters) { + if (null != baseArgs.temperature) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported", + feature: "temperature", + details: "temperature is not supported for reasoning models" + }); + } + if (null != baseArgs.top_p) { + baseArgs.top_p = void 0; + warnings.push({ + type: "unsupported", + feature: "topP", + details: "topP is not supported for reasoning models" + }); + } + if (null != baseArgs.logprobs) { + baseArgs.logprobs = void 0; + warnings.push({ + type: "other", + message: "logprobs is not supported for reasoning models" + }); + } + } + if (null != baseArgs.frequency_penalty) { + baseArgs.frequency_penalty = void 0; + warnings.push({ + type: "unsupported", + feature: "frequencyPenalty", + details: "frequencyPenalty is not supported for reasoning models" + }); + } + if (null != baseArgs.presence_penalty) { + baseArgs.presence_penalty = void 0; + warnings.push({ + type: "unsupported", + feature: "presencePenalty", + details: "presencePenalty is not supported for reasoning models" + }); + } + if (null != baseArgs.logit_bias) { + baseArgs.logit_bias = void 0; + warnings.push({ + type: "other", + message: "logitBias is not supported for reasoning models" + }); + } + if (null != baseArgs.top_logprobs) { + baseArgs.top_logprobs = void 0; + warnings.push({ + type: "other", + message: "topLogprobs is not supported for reasoning models" + }); + } + if (null != baseArgs.max_tokens) { + if (null == baseArgs.max_completion_tokens) baseArgs.max_completion_tokens = baseArgs.max_tokens; + baseArgs.max_tokens = void 0; + } + } else if (this.modelId.startsWith("gpt-4o-search-preview") || this.modelId.startsWith("gpt-4o-mini-search-preview")) { + if (null != baseArgs.temperature) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported", + feature: "temperature", + details: "temperature is not supported for the search preview models and has been removed." + }); + } + } + if ("flex" === openaiOptions.serviceTier && !modelCapabilities.supportsFlexProcessing) { + warnings.push({ + type: "unsupported", + feature: "serviceTier", + details: "flex processing is only available for o3, o4-mini, and gpt-5 models" + }); + baseArgs.service_tier = void 0; + } + if ("priority" === openaiOptions.serviceTier && !modelCapabilities.supportsPriorityProcessing) { + warnings.push({ + type: "unsupported", + feature: "serviceTier", + details: "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported" + }); + baseArgs.service_tier = void 0; + } + const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = prepareChatTools({ + tools, + toolChoice + }); + return { + args: { + ...baseArgs, + tools: openaiTools2, + tool_choice: openaiToolChoice + }, + warnings: [ + ...warnings, + ...toolWarnings + ] + }; + } + async doGenerate(options1) { + var _a, _b, _c, _d, _e, _f, _g; + const { args: body, warnings } = await this.getArgs(options1); + const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options1.headers), + body, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(openaiChatResponseSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + const choice = response.choices[0]; + const content = []; + const text = choice.message.content; + if (null != text && text.length > 0) content.push({ + type: "text", + text + }); + for (const toolCall of null != (_a = choice.message.tool_calls) ? _a : [])content.push({ + type: "tool-call", + toolCallId: null != (_b = toolCall.id) ? _b : generateId(), + toolName: toolCall.function.name, + input: toolCall.function.arguments + }); + for (const annotation of null != (_c = choice.message.annotations) ? _c : [])content.push({ + type: "source", + sourceType: "url", + id: generateId(), + url: annotation.url_citation.url, + title: annotation.url_citation.title + }); + const completionTokenDetails = null == (_d = response.usage) ? void 0 : _d.completion_tokens_details; + null == (_e = response.usage) || _e.prompt_tokens_details; + const providerMetadata = { + openai: {} + }; + if ((null == completionTokenDetails ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) providerMetadata.openai.acceptedPredictionTokens = null == completionTokenDetails ? void 0 : completionTokenDetails.accepted_prediction_tokens; + if ((null == completionTokenDetails ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) providerMetadata.openai.rejectedPredictionTokens = null == completionTokenDetails ? void 0 : completionTokenDetails.rejected_prediction_tokens; + if ((null == (_f = choice.logprobs) ? void 0 : _f.content) != null) providerMetadata.openai.logprobs = choice.logprobs.content; + return { + content, + finishReason: { + unified: mapOpenAIFinishReason(choice.finish_reason), + raw: null != (_g = choice.finish_reason) ? _g : void 0 + }, + usage: convertOpenAIChatUsage(response.usage), + request: { + body + }, + response: { + ...dist_getResponseMetadata(response), + headers: responseHeaders, + body: rawResponse + }, + warnings, + providerMetadata + }; + } + async doStream(options1) { + const { args, warnings } = await this.getArgs(options1); + const body = { + ...args, + stream: true, + stream_options: { + include_usage: true + } + }; + const { responseHeaders, value: response } = await postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options1.headers), + body, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler(openaiChatChunkSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + const toolCalls = []; + let finishReason = { + unified: "other", + raw: void 0 + }; + let usage; + let metadataExtracted = false; + let isActiveText = false; + const providerMetadata = { + openai: {} + }; + return { + stream: response.pipeThrough(new TransformStream({ + start (controller) { + controller.enqueue({ + type: "stream-start", + warnings + }); + }, + transform (chunk, controller) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q; + if (options1.includeRawChunks) controller.enqueue({ + type: "raw", + rawValue: chunk.rawValue + }); + if (!chunk.success) { + finishReason = { + unified: "error", + raw: void 0 + }; + controller.enqueue({ + type: "error", + error: chunk.error + }); + return; + } + const value1 = chunk.value; + if ("error" in value1) { + finishReason = { + unified: "error", + raw: void 0 + }; + controller.enqueue({ + type: "error", + error: value1.error + }); + return; + } + if (!metadataExtracted) { + const metadata = dist_getResponseMetadata(value1); + if (Object.values(metadata).some(Boolean)) { + metadataExtracted = true; + controller.enqueue({ + type: "response-metadata", + ...dist_getResponseMetadata(value1) + }); + } + } + if (null != value1.usage) { + usage = value1.usage; + if ((null == (_a = value1.usage.completion_tokens_details) ? void 0 : _a.accepted_prediction_tokens) != null) providerMetadata.openai.acceptedPredictionTokens = null == (_b = value1.usage.completion_tokens_details) ? void 0 : _b.accepted_prediction_tokens; + if ((null == (_c = value1.usage.completion_tokens_details) ? void 0 : _c.rejected_prediction_tokens) != null) providerMetadata.openai.rejectedPredictionTokens = null == (_d = value1.usage.completion_tokens_details) ? void 0 : _d.rejected_prediction_tokens; + } + const choice = value1.choices[0]; + if ((null == choice ? void 0 : choice.finish_reason) != null) finishReason = { + unified: mapOpenAIFinishReason(choice.finish_reason), + raw: choice.finish_reason + }; + if ((null == (_e = null == choice ? void 0 : choice.logprobs) ? void 0 : _e.content) != null) providerMetadata.openai.logprobs = choice.logprobs.content; + if ((null == choice ? void 0 : choice.delta) == null) return; + const delta = choice.delta; + if (null != delta.content) { + if (!isActiveText) { + controller.enqueue({ + type: "text-start", + id: "0" + }); + isActiveText = true; + } + controller.enqueue({ + type: "text-delta", + id: "0", + delta: delta.content + }); + } + if (null != delta.tool_calls) for (const toolCallDelta of delta.tool_calls){ + const index = toolCallDelta.index; + if (null == toolCalls[index]) { + if (null != toolCallDelta.type && "function" !== toolCallDelta.type) throw new InvalidResponseDataError({ + data: toolCallDelta, + message: "Expected 'function' type." + }); + if (null == toolCallDelta.id) throw new InvalidResponseDataError({ + data: toolCallDelta, + message: "Expected 'id' to be a string." + }); + if ((null == (_f = toolCallDelta.function) ? void 0 : _f.name) == null) throw new InvalidResponseDataError({ + data: toolCallDelta, + message: "Expected 'function.name' to be a string." + }); + controller.enqueue({ + type: "tool-input-start", + id: toolCallDelta.id, + toolName: toolCallDelta.function.name + }); + toolCalls[index] = { + id: toolCallDelta.id, + type: "function", + function: { + name: toolCallDelta.function.name, + arguments: null != (_g = toolCallDelta.function.arguments) ? _g : "" + }, + hasFinished: false + }; + const toolCall2 = toolCalls[index]; + if ((null == (_h = toolCall2.function) ? void 0 : _h.name) != null && (null == (_i = toolCall2.function) ? void 0 : _i.arguments) != null) { + if (toolCall2.function.arguments.length > 0) controller.enqueue({ + type: "tool-input-delta", + id: toolCall2.id, + delta: toolCall2.function.arguments + }); + if (isParsableJson(toolCall2.function.arguments)) { + controller.enqueue({ + type: "tool-input-end", + id: toolCall2.id + }); + controller.enqueue({ + type: "tool-call", + toolCallId: null != (_j = toolCall2.id) ? _j : generateId(), + toolName: toolCall2.function.name, + input: toolCall2.function.arguments + }); + toolCall2.hasFinished = true; + } + } + continue; + } + const toolCall = toolCalls[index]; + if (!toolCall.hasFinished) { + if ((null == (_k = toolCallDelta.function) ? void 0 : _k.arguments) != null) toolCall.function.arguments += null != (_m = null == (_l = toolCallDelta.function) ? void 0 : _l.arguments) ? _m : ""; + controller.enqueue({ + type: "tool-input-delta", + id: toolCall.id, + delta: null != (_n = toolCallDelta.function.arguments) ? _n : "" + }); + if ((null == (_o = toolCall.function) ? void 0 : _o.name) != null && (null == (_p = toolCall.function) ? void 0 : _p.arguments) != null && isParsableJson(toolCall.function.arguments)) { + controller.enqueue({ + type: "tool-input-end", + id: toolCall.id + }); + controller.enqueue({ + type: "tool-call", + toolCallId: null != (_q = toolCall.id) ? _q : generateId(), + toolName: toolCall.function.name, + input: toolCall.function.arguments + }); + toolCall.hasFinished = true; + } + } + } + if (null != delta.annotations) for (const annotation of delta.annotations)controller.enqueue({ + type: "source", + sourceType: "url", + id: generateId(), + url: annotation.url_citation.url, + title: annotation.url_citation.title + }); + }, + flush (controller) { + if (isActiveText) controller.enqueue({ + type: "text-end", + id: "0" + }); + controller.enqueue({ + type: "finish", + finishReason, + usage: convertOpenAIChatUsage(usage), + ...null != providerMetadata ? { + providerMetadata + } : {} + }); + } + })), + request: { + body + }, + response: { + headers: responseHeaders + } + }; + } + }; + function convertOpenAICompletionUsage(usage) { + var _a, _b, _c, _d; + if (null == usage) return { + inputTokens: { + total: void 0, + noCache: void 0, + cacheRead: void 0, + cacheWrite: void 0 + }, + outputTokens: { + total: void 0, + text: void 0, + reasoning: void 0 + }, + raw: void 0 + }; + const promptTokens = null != (_a = usage.prompt_tokens) ? _a : 0; + const completionTokens = null != (_b = usage.completion_tokens) ? _b : 0; + return { + inputTokens: { + total: null != (_c = usage.prompt_tokens) ? _c : void 0, + noCache: promptTokens, + cacheRead: void 0, + cacheWrite: void 0 + }, + outputTokens: { + total: null != (_d = usage.completion_tokens) ? _d : void 0, + text: completionTokens, + reasoning: void 0 + }, + raw: usage + }; + } + function convertToOpenAICompletionPrompt({ prompt, user = "user", assistant = "assistant" }) { + let text = ""; + if ("system" === prompt[0].role) { + text += `${prompt[0].content} + +`; + prompt = prompt.slice(1); + } + for (const { role, content } of prompt)switch(role){ + case "system": + throw new InvalidPromptError({ + message: "Unexpected system message in prompt: ${content}", + prompt + }); + case "user": + { + const userMessage = content.map((part)=>{ + switch(part.type){ + case "text": + return part.text; + } + }).filter(Boolean).join(""); + text += `${user}: +${userMessage} + +`; + break; + } + case "assistant": + { + const assistantMessage = content.map((part)=>{ + switch(part.type){ + case "text": + return part.text; + case "tool-call": + throw new UnsupportedFunctionalityError({ + functionality: "tool-call messages" + }); + } + }).join(""); + text += `${assistant}: +${assistantMessage} + +`; + break; + } + case "tool": + throw new UnsupportedFunctionalityError({ + functionality: "tool messages" + }); + default: + { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + text += `${assistant}: +`; + return { + prompt: text, + stopSequences: [ + ` +${user}:` + ] + }; + } + function getResponseMetadata2({ id, model, created }) { + return { + id: null != id ? id : void 0, + modelId: null != model ? model : void 0, + timestamp: null != created ? new Date(1e3 * created) : void 0 + }; + } + function mapOpenAIFinishReason2(finishReason) { + switch(finishReason){ + case "stop": + return "stop"; + case "length": + return "length"; + case "content_filter": + return "content-filter"; + case "function_call": + case "tool_calls": + return "tool-calls"; + default: + return "other"; + } + } + var openaiCompletionResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + id: schemas_string().nullish(), + created: schemas_number().nullish(), + model: schemas_string().nullish(), + choices: schemas_array(schemas_object({ + text: schemas_string(), + finish_reason: schemas_string(), + logprobs: schemas_object({ + tokens: schemas_array(schemas_string()), + token_logprobs: schemas_array(schemas_number()), + top_logprobs: schemas_array(schemas_record(schemas_string(), schemas_number())).nullish() + }).nullish() + })), + usage: schemas_object({ + prompt_tokens: schemas_number(), + completion_tokens: schemas_number(), + total_tokens: schemas_number() + }).nullish() + }))); + var openaiCompletionChunkSchema = dist_lazySchema(()=>dist_zodSchema(union([ + schemas_object({ + id: schemas_string().nullish(), + created: schemas_number().nullish(), + model: schemas_string().nullish(), + choices: schemas_array(schemas_object({ + text: schemas_string(), + finish_reason: schemas_string().nullish(), + index: schemas_number(), + logprobs: schemas_object({ + tokens: schemas_array(schemas_string()), + token_logprobs: schemas_array(schemas_number()), + top_logprobs: schemas_array(schemas_record(schemas_string(), schemas_number())).nullish() + }).nullish() + })), + usage: schemas_object({ + prompt_tokens: schemas_number(), + completion_tokens: schemas_number(), + total_tokens: schemas_number() + }).nullish() + }), + openaiErrorDataSchema + ]))); + var openaiLanguageModelCompletionOptions = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + echo: schemas_boolean().optional(), + logitBias: schemas_record(schemas_string(), schemas_number()).optional(), + suffix: schemas_string().optional(), + user: schemas_string().optional(), + logprobs: union([ + schemas_boolean(), + schemas_number() + ]).optional() + }))); + var OpenAICompletionLanguageModel = class { + constructor(modelId, config){ + this.specificationVersion = "v3"; + this.supportedUrls = {}; + this.modelId = modelId; + this.config = config; + } + get providerOptionsName() { + return this.config.provider.split(".")[0].trim(); + } + get provider() { + return this.config.provider; + } + async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences: userStopSequences, responseFormat, tools, toolChoice, seed, providerOptions }) { + const warnings = []; + const openaiOptions = { + ...await parseProviderOptions({ + provider: "openai", + providerOptions, + schema: openaiLanguageModelCompletionOptions + }), + ...await parseProviderOptions({ + provider: this.providerOptionsName, + providerOptions, + schema: openaiLanguageModelCompletionOptions + }) + }; + if (null != topK) warnings.push({ + type: "unsupported", + feature: "topK" + }); + if (null == tools ? void 0 : tools.length) warnings.push({ + type: "unsupported", + feature: "tools" + }); + if (null != toolChoice) warnings.push({ + type: "unsupported", + feature: "toolChoice" + }); + if (null != responseFormat && "text" !== responseFormat.type) warnings.push({ + type: "unsupported", + feature: "responseFormat", + details: "JSON response format is not supported." + }); + const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ + prompt + }); + const stop = [ + ...null != stopSequences ? stopSequences : [], + ...null != userStopSequences ? userStopSequences : [] + ]; + return { + args: { + model: this.modelId, + echo: openaiOptions.echo, + logit_bias: openaiOptions.logitBias, + logprobs: (null == openaiOptions ? void 0 : openaiOptions.logprobs) === true ? 0 : (null == openaiOptions ? void 0 : openaiOptions.logprobs) === false ? void 0 : null == openaiOptions ? void 0 : openaiOptions.logprobs, + suffix: openaiOptions.suffix, + user: openaiOptions.user, + max_tokens: maxOutputTokens, + temperature, + top_p: topP, + frequency_penalty: frequencyPenalty, + presence_penalty: presencePenalty, + seed, + prompt: completionPrompt, + stop: stop.length > 0 ? stop : void 0 + }, + warnings + }; + } + async doGenerate(options1) { + var _a; + const { args, warnings } = await this.getArgs(options1); + const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({ + url: this.config.url({ + path: "/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options1.headers), + body: args, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(openaiCompletionResponseSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + const choice = response.choices[0]; + const providerMetadata = { + openai: {} + }; + if (null != choice.logprobs) providerMetadata.openai.logprobs = choice.logprobs; + return { + content: [ + { + type: "text", + text: choice.text + } + ], + usage: convertOpenAICompletionUsage(response.usage), + finishReason: { + unified: mapOpenAIFinishReason2(choice.finish_reason), + raw: null != (_a = choice.finish_reason) ? _a : void 0 + }, + request: { + body: args + }, + response: { + ...getResponseMetadata2(response), + headers: responseHeaders, + body: rawResponse + }, + providerMetadata, + warnings + }; + } + async doStream(options1) { + const { args, warnings } = await this.getArgs(options1); + const body = { + ...args, + stream: true, + stream_options: { + include_usage: true + } + }; + const { responseHeaders, value: response } = await postJsonToApi({ + url: this.config.url({ + path: "/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options1.headers), + body, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler(openaiCompletionChunkSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + let finishReason = { + unified: "other", + raw: void 0 + }; + const providerMetadata = { + openai: {} + }; + let usage; + let isFirstChunk = true; + return { + stream: response.pipeThrough(new TransformStream({ + start (controller) { + controller.enqueue({ + type: "stream-start", + warnings + }); + }, + transform (chunk, controller) { + if (options1.includeRawChunks) controller.enqueue({ + type: "raw", + rawValue: chunk.rawValue + }); + if (!chunk.success) { + finishReason = { + unified: "error", + raw: void 0 + }; + controller.enqueue({ + type: "error", + error: chunk.error + }); + return; + } + const value1 = chunk.value; + if ("error" in value1) { + finishReason = { + unified: "error", + raw: void 0 + }; + controller.enqueue({ + type: "error", + error: value1.error + }); + return; + } + if (isFirstChunk) { + isFirstChunk = false; + controller.enqueue({ + type: "response-metadata", + ...getResponseMetadata2(value1) + }); + controller.enqueue({ + type: "text-start", + id: "0" + }); + } + if (null != value1.usage) usage = value1.usage; + const choice = value1.choices[0]; + if ((null == choice ? void 0 : choice.finish_reason) != null) finishReason = { + unified: mapOpenAIFinishReason2(choice.finish_reason), + raw: choice.finish_reason + }; + if ((null == choice ? void 0 : choice.logprobs) != null) providerMetadata.openai.logprobs = choice.logprobs; + if ((null == choice ? void 0 : choice.text) != null && choice.text.length > 0) controller.enqueue({ + type: "text-delta", + id: "0", + delta: choice.text + }); + }, + flush (controller) { + if (!isFirstChunk) controller.enqueue({ + type: "text-end", + id: "0" + }); + controller.enqueue({ + type: "finish", + finishReason, + providerMetadata, + usage: convertOpenAICompletionUsage(usage) + }); + } + })), + request: { + body + }, + response: { + headers: responseHeaders + } + }; + } + }; + var openaiEmbeddingModelOptions = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + dimensions: schemas_number().optional(), + user: schemas_string().optional() + }))); + var openaiTextEmbeddingResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + data: schemas_array(schemas_object({ + embedding: schemas_array(schemas_number()) + })), + usage: schemas_object({ + prompt_tokens: schemas_number() + }).nullish() + }))); + var OpenAIEmbeddingModel = class { + constructor(modelId, config){ + this.specificationVersion = "v3"; + this.maxEmbeddingsPerCall = 2048; + this.supportsParallelCalls = true; + this.modelId = modelId; + this.config = config; + } + get provider() { + return this.config.provider; + } + async doEmbed({ values, headers, abortSignal, providerOptions }) { + var _a; + if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError({ + provider: this.provider, + modelId: this.modelId, + maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, + values + }); + const openaiOptions = null != (_a = await parseProviderOptions({ + provider: "openai", + providerOptions, + schema: openaiEmbeddingModelOptions + })) ? _a : {}; + const { responseHeaders, value: response, rawValue } = await postJsonToApi({ + url: this.config.url({ + path: "/embeddings", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), headers), + body: { + model: this.modelId, + input: values, + encoding_format: "float", + dimensions: openaiOptions.dimensions, + user: openaiOptions.user + }, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(openaiTextEmbeddingResponseSchema), + abortSignal, + fetch: this.config.fetch + }); + return { + warnings: [], + embeddings: response.data.map((item)=>item.embedding), + usage: response.usage ? { + tokens: response.usage.prompt_tokens + } : void 0, + response: { + headers: responseHeaders, + body: rawValue + } + }; + } + }; + var openaiImageResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + created: schemas_number().nullish(), + data: schemas_array(schemas_object({ + b64_json: schemas_string(), + revised_prompt: schemas_string().nullish() + })), + background: schemas_string().nullish(), + output_format: schemas_string().nullish(), + size: schemas_string().nullish(), + quality: schemas_string().nullish(), + usage: schemas_object({ + input_tokens: schemas_number().nullish(), + output_tokens: schemas_number().nullish(), + total_tokens: schemas_number().nullish(), + input_tokens_details: schemas_object({ + image_tokens: schemas_number().nullish(), + text_tokens: schemas_number().nullish() + }).nullish() + }).nullish() + }))); + var modelMaxImagesPerCall = { + "dall-e-3": 1, + "dall-e-2": 10, + "gpt-image-1": 10, + "gpt-image-1-mini": 10, + "gpt-image-1.5": 10, + "chatgpt-image-latest": 10 + }; + var defaultResponseFormatPrefixes = [ + "chatgpt-image-", + "gpt-image-1-mini", + "gpt-image-1.5", + "gpt-image-1" + ]; + function hasDefaultResponseFormat(modelId) { + return defaultResponseFormatPrefixes.some((prefix)=>modelId.startsWith(prefix)); + } + var OpenAIImageModel = class { + constructor(modelId, config){ + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v3"; + } + get maxImagesPerCall() { + var _a; + return null != (_a = modelMaxImagesPerCall[this.modelId]) ? _a : 1; + } + get provider() { + return this.config.provider; + } + async doGenerate({ prompt, files, mask, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; + const warnings = []; + if (null != aspectRatio) warnings.push({ + type: "unsupported", + feature: "aspectRatio", + details: "This model does not support aspect ratio. Use `size` instead." + }); + if (null != seed) warnings.push({ + type: "unsupported", + feature: "seed" + }); + const currentDate = null != (_c = null == (_b = null == (_a = this.config._internal) ? void 0 : _a.currentDate) ? void 0 : _b.call(_a)) ? _c : /* @__PURE__ */ new Date(); + if (null != files) { + const { value: response2, responseHeaders: responseHeaders2 } = await postFormDataToApi({ + url: this.config.url({ + path: "/images/edits", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), headers), + formData: convertToFormData({ + model: this.modelId, + prompt, + image: await Promise.all(files.map((file)=>"file" === file.type ? new Blob([ + file.data instanceof Uint8Array ? new Blob([ + file.data + ], { + type: file.mediaType + }) : new Blob([ + convertBase64ToUint8Array(file.data) + ], { + type: file.mediaType + }) + ], { + type: file.mediaType + }) : downloadBlob(file.url))), + mask: null != mask ? await fileToBlob(mask) : void 0, + n, + size, + ...null != (_d = providerOptions.openai) ? _d : {} + }), + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(openaiImageResponseSchema), + abortSignal, + fetch: this.config.fetch + }); + return { + images: response2.data.map((item)=>item.b64_json), + warnings, + usage: null != response2.usage ? { + inputTokens: null != (_e = response2.usage.input_tokens) ? _e : void 0, + outputTokens: null != (_f = response2.usage.output_tokens) ? _f : void 0, + totalTokens: null != (_g = response2.usage.total_tokens) ? _g : void 0 + } : void 0, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders2 + }, + providerMetadata: { + openai: { + images: response2.data.map((item, index)=>{ + var _a2, _b2, _c2, _d2, _e2, _f2; + return { + ...item.revised_prompt ? { + revisedPrompt: item.revised_prompt + } : {}, + created: null != (_a2 = response2.created) ? _a2 : void 0, + size: null != (_b2 = response2.size) ? _b2 : void 0, + quality: null != (_c2 = response2.quality) ? _c2 : void 0, + background: null != (_d2 = response2.background) ? _d2 : void 0, + outputFormat: null != (_e2 = response2.output_format) ? _e2 : void 0, + ...distributeTokenDetails(null == (_f2 = response2.usage) ? void 0 : _f2.input_tokens_details, index, response2.data.length) + }; + }) + } + } + }; + } + const { value: response, responseHeaders } = await postJsonToApi({ + url: this.config.url({ + path: "/images/generations", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), headers), + body: { + model: this.modelId, + prompt, + n, + size, + ...null != (_h = providerOptions.openai) ? _h : {}, + ...!hasDefaultResponseFormat(this.modelId) ? { + response_format: "b64_json" + } : {} + }, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(openaiImageResponseSchema), + abortSignal, + fetch: this.config.fetch + }); + return { + images: response.data.map((item)=>item.b64_json), + warnings, + usage: null != response.usage ? { + inputTokens: null != (_i = response.usage.input_tokens) ? _i : void 0, + outputTokens: null != (_j = response.usage.output_tokens) ? _j : void 0, + totalTokens: null != (_k = response.usage.total_tokens) ? _k : void 0 + } : void 0, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders + }, + providerMetadata: { + openai: { + images: response.data.map((item, index)=>{ + var _a2, _b2, _c2, _d2, _e2, _f2; + return { + ...item.revised_prompt ? { + revisedPrompt: item.revised_prompt + } : {}, + created: null != (_a2 = response.created) ? _a2 : void 0, + size: null != (_b2 = response.size) ? _b2 : void 0, + quality: null != (_c2 = response.quality) ? _c2 : void 0, + background: null != (_d2 = response.background) ? _d2 : void 0, + outputFormat: null != (_e2 = response.output_format) ? _e2 : void 0, + ...distributeTokenDetails(null == (_f2 = response.usage) ? void 0 : _f2.input_tokens_details, index, response.data.length) + }; + }) + } + } + }; + } + }; + function distributeTokenDetails(details, index, total) { + if (null == details) return {}; + const result = {}; + if (null != details.image_tokens) { + const base = Math.floor(details.image_tokens / total); + const remainder = details.image_tokens - base * (total - 1); + result.imageTokens = index === total - 1 ? remainder : base; + } + if (null != details.text_tokens) { + const base = Math.floor(details.text_tokens / total); + const remainder = details.text_tokens - base * (total - 1); + result.textTokens = index === total - 1 ? remainder : base; + } + return result; + } + async function fileToBlob(file) { + if (!file) return; + if ("url" === file.type) return downloadBlob(file.url); + const data = file.data instanceof Uint8Array ? file.data : convertBase64ToUint8Array(file.data); + return new Blob([ + data + ], { + type: file.mediaType + }); + } + var applyPatchInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + callId: schemas_string(), + operation: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("create_file"), + path: schemas_string(), + diff: schemas_string() + }), + schemas_object({ + type: schemas_literal("delete_file"), + path: schemas_string() + }), + schemas_object({ + type: schemas_literal("update_file"), + path: schemas_string(), + diff: schemas_string() + }) + ]) + }))); + var applyPatchOutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + status: schemas_enum([ + "completed", + "failed" + ]), + output: schemas_string().optional() + }))); + dist_lazySchema(()=>dist_zodSchema(schemas_object({}))); + var applyPatchToolFactory = createProviderToolFactoryWithOutputSchema({ + id: "openai.apply_patch", + inputSchema: applyPatchInputSchema, + outputSchema: applyPatchOutputSchema + }); + var applyPatch = applyPatchToolFactory; + var codeInterpreterInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + code: schemas_string().nullish(), + containerId: schemas_string() + }))); + var codeInterpreterOutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + outputs: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("logs"), + logs: schemas_string() + }), + schemas_object({ + type: schemas_literal("image"), + url: schemas_string() + }) + ])).nullish() + }))); + var codeInterpreterArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + container: union([ + schemas_string(), + schemas_object({ + fileIds: schemas_array(schemas_string()).optional() + }) + ]).optional() + }))); + var codeInterpreterToolFactory = createProviderToolFactoryWithOutputSchema({ + id: "openai.code_interpreter", + inputSchema: codeInterpreterInputSchema, + outputSchema: codeInterpreterOutputSchema + }); + var codeInterpreter = (args = {})=>codeInterpreterToolFactory(args); + var customArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + name: schemas_string(), + description: schemas_string().optional(), + format: union([ + schemas_object({ + type: schemas_literal("grammar"), + syntax: schemas_enum([ + "regex", + "lark" + ]), + definition: schemas_string() + }), + schemas_object({ + type: schemas_literal("text") + }) + ]).optional() + }))); + var customInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_string())); + var customToolFactory = createProviderToolFactory({ + id: "openai.custom", + inputSchema: customInputSchema + }); + var customTool = (args)=>customToolFactory(args); + var comparisonFilterSchema = schemas_object({ + key: schemas_string(), + type: schemas_enum([ + "eq", + "ne", + "gt", + "gte", + "lt", + "lte", + "in", + "nin" + ]), + value: union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ]) + }); + var compoundFilterSchema = schemas_object({ + type: schemas_enum([ + "and", + "or" + ]), + filters: schemas_array(union([ + comparisonFilterSchema, + lazy(()=>compoundFilterSchema) + ])) + }); + var dist_fileSearchArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + vectorStoreIds: schemas_array(schemas_string()), + maxNumResults: schemas_number().optional(), + ranking: schemas_object({ + ranker: schemas_string().optional(), + scoreThreshold: schemas_number().optional() + }).optional(), + filters: union([ + comparisonFilterSchema, + compoundFilterSchema + ]).optional() + }))); + var fileSearchOutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + queries: schemas_array(schemas_string()), + results: schemas_array(schemas_object({ + attributes: schemas_record(schemas_string(), unknown()), + fileId: schemas_string(), + filename: schemas_string(), + score: schemas_number(), + text: schemas_string() + })).nullable() + }))); + var dist_fileSearch = createProviderToolFactoryWithOutputSchema({ + id: "openai.file_search", + inputSchema: schemas_object({}), + outputSchema: fileSearchOutputSchema + }); + var imageGenerationArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + background: schemas_enum([ + "auto", + "opaque", + "transparent" + ]).optional(), + inputFidelity: schemas_enum([ + "low", + "high" + ]).optional(), + inputImageMask: schemas_object({ + fileId: schemas_string().optional(), + imageUrl: schemas_string().optional() + }).optional(), + model: schemas_string().optional(), + moderation: schemas_enum([ + "auto" + ]).optional(), + outputCompression: schemas_number().int().min(0).max(100).optional(), + outputFormat: schemas_enum([ + "png", + "jpeg", + "webp" + ]).optional(), + partialImages: schemas_number().int().min(0).max(3).optional(), + quality: schemas_enum([ + "auto", + "low", + "medium", + "high" + ]).optional(), + size: schemas_enum([ + "1024x1024", + "1024x1536", + "1536x1024", + "auto" + ]).optional() + }).strict())); + var imageGenerationInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({}))); + var imageGenerationOutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + result: schemas_string() + }))); + var imageGenerationToolFactory = createProviderToolFactoryWithOutputSchema({ + id: "openai.image_generation", + inputSchema: imageGenerationInputSchema, + outputSchema: imageGenerationOutputSchema + }); + var imageGeneration = (args = {})=>imageGenerationToolFactory(args); + var localShellInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + action: schemas_object({ + type: schemas_literal("exec"), + command: schemas_array(schemas_string()), + timeoutMs: schemas_number().optional(), + user: schemas_string().optional(), + workingDirectory: schemas_string().optional(), + env: schemas_record(schemas_string(), schemas_string()).optional() + }) + }))); + var localShellOutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + output: schemas_string() + }))); + var localShell = createProviderToolFactoryWithOutputSchema({ + id: "openai.local_shell", + inputSchema: localShellInputSchema, + outputSchema: localShellOutputSchema + }); + var shellInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + action: schemas_object({ + commands: schemas_array(schemas_string()), + timeoutMs: schemas_number().optional(), + maxOutputLength: schemas_number().optional() + }) + }))); + var shellOutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + output: schemas_array(schemas_object({ + stdout: schemas_string(), + stderr: schemas_string(), + outcome: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("timeout") + }), + schemas_object({ + type: schemas_literal("exit"), + exitCode: schemas_number() + }) + ]) + })) + }))); + var shellSkillsSchema = schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("skillReference"), + skillId: schemas_string(), + version: schemas_string().optional() + }), + schemas_object({ + type: schemas_literal("inline"), + name: schemas_string(), + description: schemas_string(), + source: schemas_object({ + type: schemas_literal("base64"), + mediaType: schemas_literal("application/zip"), + data: schemas_string() + }) + }) + ])).optional(); + var shellArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + environment: union([ + schemas_object({ + type: schemas_literal("containerAuto"), + fileIds: schemas_array(schemas_string()).optional(), + memoryLimit: schemas_enum([ + "1g", + "4g", + "16g", + "64g" + ]).optional(), + networkPolicy: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("disabled") + }), + schemas_object({ + type: schemas_literal("allowlist"), + allowedDomains: schemas_array(schemas_string()), + domainSecrets: schemas_array(schemas_object({ + domain: schemas_string(), + name: schemas_string(), + value: schemas_string() + })).optional() + }) + ]).optional(), + skills: shellSkillsSchema + }), + schemas_object({ + type: schemas_literal("containerReference"), + containerId: schemas_string() + }), + schemas_object({ + type: schemas_literal("local").optional(), + skills: schemas_array(schemas_object({ + name: schemas_string(), + description: schemas_string(), + path: schemas_string() + })).optional() + }) + ]).optional() + }))); + var shell = createProviderToolFactoryWithOutputSchema({ + id: "openai.shell", + inputSchema: shellInputSchema, + outputSchema: shellOutputSchema + }); + var toolSearchArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + execution: schemas_enum([ + "server", + "client" + ]).optional(), + description: schemas_string().optional(), + parameters: schemas_record(schemas_string(), unknown()).optional() + }))); + var toolSearchInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + arguments: unknown().optional(), + call_id: schemas_string().nullish() + }))); + var toolSearchOutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + tools: schemas_array(schemas_record(schemas_string(), unknown())) + }))); + var toolSearchToolFactory = createProviderToolFactoryWithOutputSchema({ + id: "openai.tool_search", + inputSchema: toolSearchInputSchema, + outputSchema: toolSearchOutputSchema + }); + var toolSearch = (args = {})=>toolSearchToolFactory(args); + var webSearchArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + externalWebAccess: schemas_boolean().optional(), + filters: schemas_object({ + allowedDomains: schemas_array(schemas_string()).optional() + }).optional(), + searchContextSize: schemas_enum([ + "low", + "medium", + "high" + ]).optional(), + userLocation: schemas_object({ + type: schemas_literal("approximate"), + country: schemas_string().optional(), + city: schemas_string().optional(), + region: schemas_string().optional(), + timezone: schemas_string().optional() + }).optional() + }))); + var webSearchInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({}))); + var webSearchOutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + action: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("search"), + query: schemas_string().optional() + }), + schemas_object({ + type: schemas_literal("openPage"), + url: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("findInPage"), + url: schemas_string().nullish(), + pattern: schemas_string().nullish() + }) + ]).optional(), + sources: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("url"), + url: schemas_string() + }), + schemas_object({ + type: schemas_literal("api"), + name: schemas_string() + }) + ])).optional() + }))); + var webSearchToolFactory = createProviderToolFactoryWithOutputSchema({ + id: "openai.web_search", + inputSchema: webSearchInputSchema, + outputSchema: webSearchOutputSchema + }); + var webSearch = (args = {})=>webSearchToolFactory(args); + var webSearchPreviewArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + searchContextSize: schemas_enum([ + "low", + "medium", + "high" + ]).optional(), + userLocation: schemas_object({ + type: schemas_literal("approximate"), + country: schemas_string().optional(), + city: schemas_string().optional(), + region: schemas_string().optional(), + timezone: schemas_string().optional() + }).optional() + }))); + var webSearchPreviewInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({}))); + var webSearchPreviewOutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + action: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("search"), + query: schemas_string().optional() + }), + schemas_object({ + type: schemas_literal("openPage"), + url: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("findInPage"), + url: schemas_string().nullish(), + pattern: schemas_string().nullish() + }) + ]).optional() + }))); + var webSearchPreview = createProviderToolFactoryWithOutputSchema({ + id: "openai.web_search_preview", + inputSchema: webSearchPreviewInputSchema, + outputSchema: webSearchPreviewOutputSchema + }); + var dist_jsonValueSchema = lazy(()=>union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_array(dist_jsonValueSchema), + schemas_record(schemas_string(), dist_jsonValueSchema) + ])); + var mcpArgsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + serverLabel: schemas_string(), + allowedTools: union([ + schemas_array(schemas_string()), + schemas_object({ + readOnly: schemas_boolean().optional(), + toolNames: schemas_array(schemas_string()).optional() + }) + ]).optional(), + authorization: schemas_string().optional(), + connectorId: schemas_string().optional(), + headers: schemas_record(schemas_string(), schemas_string()).optional(), + requireApproval: union([ + schemas_enum([ + "always", + "never" + ]), + schemas_object({ + never: schemas_object({ + toolNames: schemas_array(schemas_string()).optional() + }).optional() + }) + ]).optional(), + serverDescription: schemas_string().optional(), + serverUrl: schemas_string().optional() + }).refine((v)=>null != v.serverUrl || null != v.connectorId, "One of serverUrl or connectorId must be provided."))); + var mcpInputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({}))); + var mcpOutputSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + type: schemas_literal("call"), + serverLabel: schemas_string(), + name: schemas_string(), + arguments: schemas_string(), + output: schemas_string().nullish(), + error: union([ + schemas_string(), + dist_jsonValueSchema + ]).optional() + }))); + var mcpToolFactory = createProviderToolFactoryWithOutputSchema({ + id: "openai.mcp", + inputSchema: mcpInputSchema, + outputSchema: mcpOutputSchema + }); + var mcp = (args)=>mcpToolFactory(args); + var openaiTools = { + applyPatch, + customTool, + codeInterpreter, + fileSearch: dist_fileSearch, + imageGeneration, + localShell, + shell, + webSearchPreview, + webSearch, + mcp, + toolSearch + }; + function convertOpenAIResponsesUsage(usage) { + var _a, _b, _c, _d; + if (null == usage) return { + inputTokens: { + total: void 0, + noCache: void 0, + cacheRead: void 0, + cacheWrite: void 0 + }, + outputTokens: { + total: void 0, + text: void 0, + reasoning: void 0 + }, + raw: void 0 + }; + const inputTokens = usage.input_tokens; + const outputTokens = usage.output_tokens; + const cachedTokens = null != (_b = null == (_a = usage.input_tokens_details) ? void 0 : _a.cached_tokens) ? _b : 0; + const reasoningTokens = null != (_d = null == (_c = usage.output_tokens_details) ? void 0 : _c.reasoning_tokens) ? _d : 0; + return { + inputTokens: { + total: inputTokens, + noCache: inputTokens - cachedTokens, + cacheRead: cachedTokens, + cacheWrite: void 0 + }, + outputTokens: { + total: outputTokens, + text: outputTokens - reasoningTokens, + reasoning: reasoningTokens + }, + raw: usage + }; + } + function isFileId(data, prefixes) { + if (!prefixes) return false; + return prefixes.some((prefix)=>data.startsWith(prefix)); + } + async function convertToOpenAIResponsesInput({ prompt, toolNameMapping, systemMessageMode, providerOptionsName, fileIdPrefixes, store, hasConversation = false, hasLocalShellTool = false, hasShellTool = false, hasApplyPatchTool = false, customProviderToolNames }) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q; + let input = []; + const warnings = []; + const processedApprovalIds = /* @__PURE__ */ new Set(); + for (const { role, content } of prompt)switch(role){ + case "system": + switch(systemMessageMode){ + case "system": + input.push({ + role: "system", + content + }); + break; + case "developer": + input.push({ + role: "developer", + content + }); + break; + case "remove": + warnings.push({ + type: "other", + message: "system messages are removed for this model" + }); + break; + default: + { + const _exhaustiveCheck = systemMessageMode; + throw new Error(`Unsupported system message mode: ${_exhaustiveCheck}`); + } + } + break; + case "user": + input.push({ + role: "user", + content: content.map((part, index)=>{ + var _a2, _b2, _c2; + switch(part.type){ + case "text": + return { + type: "input_text", + text: part.text + }; + case "file": + if (part.mediaType.startsWith("image/")) { + const mediaType = "image/*" === part.mediaType ? "image/jpeg" : part.mediaType; + return { + type: "input_image", + ...part.data instanceof URL ? { + image_url: part.data.toString() + } : "string" == typeof part.data && isFileId(part.data, fileIdPrefixes) ? { + file_id: part.data + } : { + image_url: `data:${mediaType};base64,${convertToBase64(part.data)}` + }, + detail: null == (_b2 = null == (_a2 = part.providerOptions) ? void 0 : _a2[providerOptionsName]) ? void 0 : _b2.imageDetail + }; + } + if ("application/pdf" === part.mediaType) { + if (part.data instanceof URL) return { + type: "input_file", + file_url: part.data.toString() + }; + return { + type: "input_file", + ..."string" == typeof part.data && isFileId(part.data, fileIdPrefixes) ? { + file_id: part.data + } : { + filename: null != (_c2 = part.filename) ? _c2 : `part-${index}.pdf`, + file_data: `data:application/pdf;base64,${convertToBase64(part.data)}` + } + }; + } + throw new UnsupportedFunctionalityError({ + functionality: `file part media type ${part.mediaType}` + }); + } + }) + }); + break; + case "assistant": + { + const reasoningMessages = {}; + for (const part of content)switch(part.type){ + case "text": + { + const providerOpts = null == (_a = part.providerOptions) ? void 0 : _a[providerOptionsName]; + const id = null == providerOpts ? void 0 : providerOpts.itemId; + const phase = null == providerOpts ? void 0 : providerOpts.phase; + if (hasConversation && null != id) break; + if (store && null != id) { + input.push({ + type: "item_reference", + id + }); + break; + } + input.push({ + role: "assistant", + content: [ + { + type: "output_text", + text: part.text + } + ], + id, + ...null != phase && { + phase + } + }); + break; + } + case "tool-call": + { + const id = null != (_f = null == (_c = null == (_b = part.providerOptions) ? void 0 : _b[providerOptionsName]) ? void 0 : _c.itemId) ? _f : null == (_e = null == (_d = part.providerMetadata) ? void 0 : _d[providerOptionsName]) ? void 0 : _e.itemId; + if (hasConversation && null != id) break; + const resolvedToolName = toolNameMapping.toProviderToolName(part.toolName); + if ("tool_search" === resolvedToolName) { + if (store && null != id) { + input.push({ + type: "item_reference", + id + }); + break; + } + const parsedInput = "string" == typeof part.input ? await parseJSON({ + text: part.input, + schema: toolSearchInputSchema + }) : await dist_validateTypes({ + value: part.input, + schema: toolSearchInputSchema + }); + const execution = null != parsedInput.call_id ? "client" : "server"; + input.push({ + type: "tool_search_call", + id: null != id ? id : part.toolCallId, + execution, + call_id: null != (_g = parsedInput.call_id) ? _g : null, + status: "completed", + arguments: parsedInput.arguments + }); + break; + } + if (part.providerExecuted) { + if (store && null != id) input.push({ + type: "item_reference", + id + }); + break; + } + if (store && null != id) { + input.push({ + type: "item_reference", + id + }); + break; + } + if (hasLocalShellTool && "local_shell" === resolvedToolName) { + const parsedInput = await dist_validateTypes({ + value: part.input, + schema: localShellInputSchema + }); + input.push({ + type: "local_shell_call", + call_id: part.toolCallId, + id, + action: { + type: "exec", + command: parsedInput.action.command, + timeout_ms: parsedInput.action.timeoutMs, + user: parsedInput.action.user, + working_directory: parsedInput.action.workingDirectory, + env: parsedInput.action.env + } + }); + break; + } + if (hasShellTool && "shell" === resolvedToolName) { + const parsedInput = await dist_validateTypes({ + value: part.input, + schema: shellInputSchema + }); + input.push({ + type: "shell_call", + call_id: part.toolCallId, + id, + status: "completed", + action: { + commands: parsedInput.action.commands, + timeout_ms: parsedInput.action.timeoutMs, + max_output_length: parsedInput.action.maxOutputLength + } + }); + break; + } + if (hasApplyPatchTool && "apply_patch" === resolvedToolName) { + const parsedInput = await dist_validateTypes({ + value: part.input, + schema: applyPatchInputSchema + }); + input.push({ + type: "apply_patch_call", + call_id: parsedInput.callId, + id, + status: "completed", + operation: parsedInput.operation + }); + break; + } + if (null == customProviderToolNames ? void 0 : customProviderToolNames.has(resolvedToolName)) { + input.push({ + type: "custom_tool_call", + call_id: part.toolCallId, + name: resolvedToolName, + input: "string" == typeof part.input ? part.input : JSON.stringify(part.input), + id + }); + break; + } + input.push({ + type: "function_call", + call_id: part.toolCallId, + name: resolvedToolName, + arguments: JSON.stringify(part.input), + id + }); + break; + } + case "tool-result": + { + if ("execution-denied" === part.output.type || "json" === part.output.type && "object" == typeof part.output.value && null != part.output.value && "type" in part.output.value && "execution-denied" === part.output.value.type) break; + if (hasConversation) break; + const resolvedResultToolName = toolNameMapping.toProviderToolName(part.toolName); + if ("tool_search" === resolvedResultToolName) { + const itemId = null != (_j = null == (_i = null == (_h = part.providerOptions) ? void 0 : _h[providerOptionsName]) ? void 0 : _i.itemId) ? _j : part.toolCallId; + if (store) input.push({ + type: "item_reference", + id: itemId + }); + else if ("json" === part.output.type) { + const parsedOutput = await dist_validateTypes({ + value: part.output.value, + schema: toolSearchOutputSchema + }); + input.push({ + type: "tool_search_output", + id: itemId, + execution: "server", + call_id: null, + status: "completed", + tools: parsedOutput.tools + }); + } + break; + } + if (hasShellTool && "shell" === resolvedResultToolName) { + if ("json" === part.output.type) { + const parsedOutput = await dist_validateTypes({ + value: part.output.value, + schema: shellOutputSchema + }); + input.push({ + type: "shell_call_output", + call_id: part.toolCallId, + output: parsedOutput.output.map((item)=>({ + stdout: item.stdout, + stderr: item.stderr, + outcome: "timeout" === item.outcome.type ? { + type: "timeout" + } : { + type: "exit", + exit_code: item.outcome.exitCode + } + })) + }); + } + break; + } + if (store) { + const itemId = null != (_m = null == (_l = null == (_k = part.providerOptions) ? void 0 : _k[providerOptionsName]) ? void 0 : _l.itemId) ? _m : part.toolCallId; + input.push({ + type: "item_reference", + id: itemId + }); + } else warnings.push({ + type: "other", + message: `Results for OpenAI tool ${part.toolName} are not sent to the API when store is false` + }); + break; + } + case "reasoning": + { + const providerOptions = await parseProviderOptions({ + provider: providerOptionsName, + providerOptions: part.providerOptions, + schema: openaiResponsesReasoningProviderOptionsSchema + }); + const reasoningId = null == providerOptions ? void 0 : providerOptions.itemId; + if (hasConversation && null != reasoningId) break; + if (null != reasoningId) { + const reasoningMessage = reasoningMessages[reasoningId]; + if (store) { + if (void 0 === reasoningMessage) { + input.push({ + type: "item_reference", + id: reasoningId + }); + reasoningMessages[reasoningId] = { + type: "reasoning", + id: reasoningId, + summary: [] + }; + } + } else { + const summaryParts = []; + if (part.text.length > 0) summaryParts.push({ + type: "summary_text", + text: part.text + }); + else if (void 0 !== reasoningMessage) warnings.push({ + type: "other", + message: `Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(part)}.` + }); + if (void 0 === reasoningMessage) { + reasoningMessages[reasoningId] = { + type: "reasoning", + id: reasoningId, + encrypted_content: null == providerOptions ? void 0 : providerOptions.reasoningEncryptedContent, + summary: summaryParts + }; + input.push(reasoningMessages[reasoningId]); + } else { + reasoningMessage.summary.push(...summaryParts); + if ((null == providerOptions ? void 0 : providerOptions.reasoningEncryptedContent) != null) reasoningMessage.encrypted_content = providerOptions.reasoningEncryptedContent; + } + } + } else { + const encryptedContent = null == providerOptions ? void 0 : providerOptions.reasoningEncryptedContent; + if (null != encryptedContent) { + const summaryParts = []; + if (part.text.length > 0) summaryParts.push({ + type: "summary_text", + text: part.text + }); + input.push({ + type: "reasoning", + encrypted_content: encryptedContent, + summary: summaryParts + }); + } else warnings.push({ + type: "other", + message: `Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(part)}.` + }); + } + break; + } + } + break; + } + case "tool": + for (const part of content){ + if ("tool-approval-response" === part.type) { + const approvalResponse = part; + if (processedApprovalIds.has(approvalResponse.approvalId)) continue; + processedApprovalIds.add(approvalResponse.approvalId); + if (store) input.push({ + type: "item_reference", + id: approvalResponse.approvalId + }); + input.push({ + type: "mcp_approval_response", + approval_request_id: approvalResponse.approvalId, + approve: approvalResponse.approved + }); + continue; + } + const output = part.output; + if ("execution-denied" === output.type) { + const approvalId = null == (_o = null == (_n = output.providerOptions) ? void 0 : _n.openai) ? void 0 : _o.approvalId; + if (approvalId) continue; + } + const resolvedToolName = toolNameMapping.toProviderToolName(part.toolName); + if ("tool_search" === resolvedToolName && "json" === output.type) { + const parsedOutput = await dist_validateTypes({ + value: output.value, + schema: toolSearchOutputSchema + }); + input.push({ + type: "tool_search_output", + execution: "client", + call_id: part.toolCallId, + status: "completed", + tools: parsedOutput.tools + }); + continue; + } + if (hasLocalShellTool && "local_shell" === resolvedToolName && "json" === output.type) { + const parsedOutput = await dist_validateTypes({ + value: output.value, + schema: localShellOutputSchema + }); + input.push({ + type: "local_shell_call_output", + call_id: part.toolCallId, + output: parsedOutput.output + }); + continue; + } + if (hasShellTool && "shell" === resolvedToolName && "json" === output.type) { + const parsedOutput = await dist_validateTypes({ + value: output.value, + schema: shellOutputSchema + }); + input.push({ + type: "shell_call_output", + call_id: part.toolCallId, + output: parsedOutput.output.map((item)=>({ + stdout: item.stdout, + stderr: item.stderr, + outcome: "timeout" === item.outcome.type ? { + type: "timeout" + } : { + type: "exit", + exit_code: item.outcome.exitCode + } + })) + }); + continue; + } + if (hasApplyPatchTool && "apply_patch" === part.toolName && "json" === output.type) { + const parsedOutput = await dist_validateTypes({ + value: output.value, + schema: applyPatchOutputSchema + }); + input.push({ + type: "apply_patch_call_output", + call_id: part.toolCallId, + status: parsedOutput.status, + output: parsedOutput.output + }); + continue; + } + if (null == customProviderToolNames ? void 0 : customProviderToolNames.has(resolvedToolName)) { + let outputValue; + switch(output.type){ + case "text": + case "error-text": + outputValue = output.value; + break; + case "execution-denied": + outputValue = null != (_p = output.reason) ? _p : "Tool execution denied."; + break; + case "json": + case "error-json": + outputValue = JSON.stringify(output.value); + break; + case "content": + outputValue = output.value.map((item)=>{ + var _a2; + switch(item.type){ + case "text": + return { + type: "input_text", + text: item.text + }; + case "image-data": + return { + type: "input_image", + image_url: `data:${item.mediaType};base64,${item.data}` + }; + case "image-url": + return { + type: "input_image", + image_url: item.url + }; + case "file-data": + return { + type: "input_file", + filename: null != (_a2 = item.filename) ? _a2 : "data", + file_data: `data:${item.mediaType};base64,${item.data}` + }; + case "file-url": + return { + type: "input_file", + file_url: item.url + }; + default: + warnings.push({ + type: "other", + message: `unsupported custom tool content part type: ${item.type}` + }); + return; + } + }).filter(dist_isNonNullable); + break; + default: + outputValue = ""; + } + input.push({ + type: "custom_tool_call_output", + call_id: part.toolCallId, + output: outputValue + }); + continue; + } + let contentValue; + switch(output.type){ + case "text": + case "error-text": + contentValue = output.value; + break; + case "execution-denied": + contentValue = null != (_q = output.reason) ? _q : "Tool execution denied."; + break; + case "json": + case "error-json": + contentValue = JSON.stringify(output.value); + break; + case "content": + contentValue = output.value.map((item)=>{ + var _a2; + switch(item.type){ + case "text": + return { + type: "input_text", + text: item.text + }; + case "image-data": + return { + type: "input_image", + image_url: `data:${item.mediaType};base64,${item.data}` + }; + case "image-url": + return { + type: "input_image", + image_url: item.url + }; + case "file-data": + return { + type: "input_file", + filename: null != (_a2 = item.filename) ? _a2 : "data", + file_data: `data:${item.mediaType};base64,${item.data}` + }; + case "file-url": + return { + type: "input_file", + file_url: item.url + }; + default: + return void warnings.push({ + type: "other", + message: `unsupported tool content part type: ${item.type}` + }); + } + }).filter(dist_isNonNullable); + break; + } + input.push({ + type: "function_call_output", + call_id: part.toolCallId, + output: contentValue + }); + } + break; + default: + { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + if (!store && input.some((item)=>"type" in item && "reasoning" === item.type && null == item.encrypted_content)) { + warnings.push({ + type: "other", + message: "Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts." + }); + input = input.filter((item)=>!("type" in item) || "reasoning" !== item.type || null != item.encrypted_content); + } + return { + input, + warnings + }; + } + var openaiResponsesReasoningProviderOptionsSchema = schemas_object({ + itemId: schemas_string().nullish(), + reasoningEncryptedContent: schemas_string().nullish() + }); + function mapOpenAIResponseFinishReason({ finishReason, hasFunctionCall }) { + switch(finishReason){ + case void 0: + case null: + return hasFunctionCall ? "tool-calls" : "stop"; + case "max_output_tokens": + return "length"; + case "content_filter": + return "content-filter"; + default: + return hasFunctionCall ? "tool-calls" : "other"; + } + } + var jsonValueSchema2 = lazy(()=>union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_array(jsonValueSchema2), + schemas_record(schemas_string(), jsonValueSchema2.optional()) + ])); + var openaiResponsesChunkSchema = dist_lazySchema(()=>dist_zodSchema(union([ + schemas_object({ + type: schemas_literal("response.output_text.delta"), + item_id: schemas_string(), + delta: schemas_string(), + logprobs: schemas_array(schemas_object({ + token: schemas_string(), + logprob: schemas_number(), + top_logprobs: schemas_array(schemas_object({ + token: schemas_string(), + logprob: schemas_number() + })) + })).nullish() + }), + schemas_object({ + type: schemas_enum([ + "response.completed", + "response.incomplete" + ]), + response: schemas_object({ + incomplete_details: schemas_object({ + reason: schemas_string() + }).nullish(), + usage: schemas_object({ + input_tokens: schemas_number(), + input_tokens_details: schemas_object({ + cached_tokens: schemas_number().nullish() + }).nullish(), + output_tokens: schemas_number(), + output_tokens_details: schemas_object({ + reasoning_tokens: schemas_number().nullish() + }).nullish() + }), + service_tier: schemas_string().nullish() + }) + }), + schemas_object({ + type: schemas_literal("response.failed"), + response: schemas_object({ + error: schemas_object({ + code: schemas_string().nullish(), + message: schemas_string() + }).nullish(), + incomplete_details: schemas_object({ + reason: schemas_string() + }).nullish(), + usage: schemas_object({ + input_tokens: schemas_number(), + input_tokens_details: schemas_object({ + cached_tokens: schemas_number().nullish() + }).nullish(), + output_tokens: schemas_number(), + output_tokens_details: schemas_object({ + reasoning_tokens: schemas_number().nullish() + }).nullish() + }).nullish(), + service_tier: schemas_string().nullish() + }) + }), + schemas_object({ + type: schemas_literal("response.created"), + response: schemas_object({ + id: schemas_string(), + created_at: schemas_number(), + model: schemas_string(), + service_tier: schemas_string().nullish() + }) + }), + schemas_object({ + type: schemas_literal("response.output_item.added"), + output_index: schemas_number(), + item: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("message"), + id: schemas_string(), + phase: schemas_enum([ + "commentary", + "final_answer" + ]).nullish() + }), + schemas_object({ + type: schemas_literal("reasoning"), + id: schemas_string(), + encrypted_content: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("function_call"), + id: schemas_string(), + call_id: schemas_string(), + name: schemas_string(), + arguments: schemas_string() + }), + schemas_object({ + type: schemas_literal("web_search_call"), + id: schemas_string(), + status: schemas_string() + }), + schemas_object({ + type: schemas_literal("computer_call"), + id: schemas_string(), + status: schemas_string() + }), + schemas_object({ + type: schemas_literal("file_search_call"), + id: schemas_string() + }), + schemas_object({ + type: schemas_literal("image_generation_call"), + id: schemas_string() + }), + schemas_object({ + type: schemas_literal("code_interpreter_call"), + id: schemas_string(), + container_id: schemas_string(), + code: schemas_string().nullable(), + outputs: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("logs"), + logs: schemas_string() + }), + schemas_object({ + type: schemas_literal("image"), + url: schemas_string() + }) + ])).nullable(), + status: schemas_string() + }), + schemas_object({ + type: schemas_literal("mcp_call"), + id: schemas_string(), + status: schemas_string(), + approval_request_id: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("mcp_list_tools"), + id: schemas_string() + }), + schemas_object({ + type: schemas_literal("mcp_approval_request"), + id: schemas_string() + }), + schemas_object({ + type: schemas_literal("apply_patch_call"), + id: schemas_string(), + call_id: schemas_string(), + status: schemas_enum([ + "in_progress", + "completed" + ]), + operation: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("create_file"), + path: schemas_string(), + diff: schemas_string() + }), + schemas_object({ + type: schemas_literal("delete_file"), + path: schemas_string() + }), + schemas_object({ + type: schemas_literal("update_file"), + path: schemas_string(), + diff: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("custom_tool_call"), + id: schemas_string(), + call_id: schemas_string(), + name: schemas_string(), + input: schemas_string() + }), + schemas_object({ + type: schemas_literal("shell_call"), + id: schemas_string(), + call_id: schemas_string(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + action: schemas_object({ + commands: schemas_array(schemas_string()) + }) + }), + schemas_object({ + type: schemas_literal("shell_call_output"), + id: schemas_string(), + call_id: schemas_string(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + output: schemas_array(schemas_object({ + stdout: schemas_string(), + stderr: schemas_string(), + outcome: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("timeout") + }), + schemas_object({ + type: schemas_literal("exit"), + exit_code: schemas_number() + }) + ]) + })) + }), + schemas_object({ + type: schemas_literal("tool_search_call"), + id: schemas_string(), + execution: schemas_enum([ + "server", + "client" + ]), + call_id: schemas_string().nullable(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + arguments: unknown() + }), + schemas_object({ + type: schemas_literal("tool_search_output"), + id: schemas_string(), + execution: schemas_enum([ + "server", + "client" + ]), + call_id: schemas_string().nullable(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + tools: schemas_array(schemas_record(schemas_string(), jsonValueSchema2.optional())) + }) + ]) + }), + schemas_object({ + type: schemas_literal("response.output_item.done"), + output_index: schemas_number(), + item: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("message"), + id: schemas_string(), + phase: schemas_enum([ + "commentary", + "final_answer" + ]).nullish() + }), + schemas_object({ + type: schemas_literal("reasoning"), + id: schemas_string(), + encrypted_content: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("function_call"), + id: schemas_string(), + call_id: schemas_string(), + name: schemas_string(), + arguments: schemas_string(), + status: schemas_literal("completed") + }), + schemas_object({ + type: schemas_literal("custom_tool_call"), + id: schemas_string(), + call_id: schemas_string(), + name: schemas_string(), + input: schemas_string(), + status: schemas_literal("completed") + }), + schemas_object({ + type: schemas_literal("code_interpreter_call"), + id: schemas_string(), + code: schemas_string().nullable(), + container_id: schemas_string(), + outputs: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("logs"), + logs: schemas_string() + }), + schemas_object({ + type: schemas_literal("image"), + url: schemas_string() + }) + ])).nullable() + }), + schemas_object({ + type: schemas_literal("image_generation_call"), + id: schemas_string(), + result: schemas_string() + }), + schemas_object({ + type: schemas_literal("web_search_call"), + id: schemas_string(), + status: schemas_string(), + action: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("search"), + query: schemas_string().nullish(), + sources: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("url"), + url: schemas_string() + }), + schemas_object({ + type: schemas_literal("api"), + name: schemas_string() + }) + ])).nullish() + }), + schemas_object({ + type: schemas_literal("open_page"), + url: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("find_in_page"), + url: schemas_string().nullish(), + pattern: schemas_string().nullish() + }) + ]).nullish() + }), + schemas_object({ + type: schemas_literal("file_search_call"), + id: schemas_string(), + queries: schemas_array(schemas_string()), + results: schemas_array(schemas_object({ + attributes: schemas_record(schemas_string(), union([ + schemas_string(), + schemas_number(), + schemas_boolean() + ])), + file_id: schemas_string(), + filename: schemas_string(), + score: schemas_number(), + text: schemas_string() + })).nullish() + }), + schemas_object({ + type: schemas_literal("local_shell_call"), + id: schemas_string(), + call_id: schemas_string(), + action: schemas_object({ + type: schemas_literal("exec"), + command: schemas_array(schemas_string()), + timeout_ms: schemas_number().optional(), + user: schemas_string().optional(), + working_directory: schemas_string().optional(), + env: schemas_record(schemas_string(), schemas_string()).optional() + }) + }), + schemas_object({ + type: schemas_literal("computer_call"), + id: schemas_string(), + status: schemas_literal("completed") + }), + schemas_object({ + type: schemas_literal("mcp_call"), + id: schemas_string(), + status: schemas_string(), + arguments: schemas_string(), + name: schemas_string(), + server_label: schemas_string(), + output: schemas_string().nullish(), + error: union([ + schemas_string(), + schemas_object({ + type: schemas_string().optional(), + code: union([ + schemas_number(), + schemas_string() + ]).optional(), + message: schemas_string().optional() + }).loose() + ]).nullish(), + approval_request_id: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("mcp_list_tools"), + id: schemas_string(), + server_label: schemas_string(), + tools: schemas_array(schemas_object({ + name: schemas_string(), + description: schemas_string().optional(), + input_schema: any(), + annotations: schemas_record(schemas_string(), unknown()).optional() + })), + error: union([ + schemas_string(), + schemas_object({ + type: schemas_string().optional(), + code: union([ + schemas_number(), + schemas_string() + ]).optional(), + message: schemas_string().optional() + }).loose() + ]).optional() + }), + schemas_object({ + type: schemas_literal("mcp_approval_request"), + id: schemas_string(), + server_label: schemas_string(), + name: schemas_string(), + arguments: schemas_string(), + approval_request_id: schemas_string().optional() + }), + schemas_object({ + type: schemas_literal("apply_patch_call"), + id: schemas_string(), + call_id: schemas_string(), + status: schemas_enum([ + "in_progress", + "completed" + ]), + operation: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("create_file"), + path: schemas_string(), + diff: schemas_string() + }), + schemas_object({ + type: schemas_literal("delete_file"), + path: schemas_string() + }), + schemas_object({ + type: schemas_literal("update_file"), + path: schemas_string(), + diff: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("shell_call"), + id: schemas_string(), + call_id: schemas_string(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + action: schemas_object({ + commands: schemas_array(schemas_string()) + }) + }), + schemas_object({ + type: schemas_literal("shell_call_output"), + id: schemas_string(), + call_id: schemas_string(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + output: schemas_array(schemas_object({ + stdout: schemas_string(), + stderr: schemas_string(), + outcome: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("timeout") + }), + schemas_object({ + type: schemas_literal("exit"), + exit_code: schemas_number() + }) + ]) + })) + }), + schemas_object({ + type: schemas_literal("tool_search_call"), + id: schemas_string(), + execution: schemas_enum([ + "server", + "client" + ]), + call_id: schemas_string().nullable(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + arguments: unknown() + }), + schemas_object({ + type: schemas_literal("tool_search_output"), + id: schemas_string(), + execution: schemas_enum([ + "server", + "client" + ]), + call_id: schemas_string().nullable(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + tools: schemas_array(schemas_record(schemas_string(), jsonValueSchema2.optional())) + }) + ]) + }), + schemas_object({ + type: schemas_literal("response.function_call_arguments.delta"), + item_id: schemas_string(), + output_index: schemas_number(), + delta: schemas_string() + }), + schemas_object({ + type: schemas_literal("response.custom_tool_call_input.delta"), + item_id: schemas_string(), + output_index: schemas_number(), + delta: schemas_string() + }), + schemas_object({ + type: schemas_literal("response.image_generation_call.partial_image"), + item_id: schemas_string(), + output_index: schemas_number(), + partial_image_b64: schemas_string() + }), + schemas_object({ + type: schemas_literal("response.code_interpreter_call_code.delta"), + item_id: schemas_string(), + output_index: schemas_number(), + delta: schemas_string() + }), + schemas_object({ + type: schemas_literal("response.code_interpreter_call_code.done"), + item_id: schemas_string(), + output_index: schemas_number(), + code: schemas_string() + }), + schemas_object({ + type: schemas_literal("response.output_text.annotation.added"), + annotation: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("url_citation"), + start_index: schemas_number(), + end_index: schemas_number(), + url: schemas_string(), + title: schemas_string() + }), + schemas_object({ + type: schemas_literal("file_citation"), + file_id: schemas_string(), + filename: schemas_string(), + index: schemas_number() + }), + schemas_object({ + type: schemas_literal("container_file_citation"), + container_id: schemas_string(), + file_id: schemas_string(), + filename: schemas_string(), + start_index: schemas_number(), + end_index: schemas_number() + }), + schemas_object({ + type: schemas_literal("file_path"), + file_id: schemas_string(), + index: schemas_number() + }) + ]) + }), + schemas_object({ + type: schemas_literal("response.reasoning_summary_part.added"), + item_id: schemas_string(), + summary_index: schemas_number() + }), + schemas_object({ + type: schemas_literal("response.reasoning_summary_text.delta"), + item_id: schemas_string(), + summary_index: schemas_number(), + delta: schemas_string() + }), + schemas_object({ + type: schemas_literal("response.reasoning_summary_part.done"), + item_id: schemas_string(), + summary_index: schemas_number() + }), + schemas_object({ + type: schemas_literal("response.apply_patch_call_operation_diff.delta"), + item_id: schemas_string(), + output_index: schemas_number(), + delta: schemas_string(), + obfuscation: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("response.apply_patch_call_operation_diff.done"), + item_id: schemas_string(), + output_index: schemas_number(), + diff: schemas_string() + }), + schemas_object({ + type: schemas_literal("error"), + sequence_number: schemas_number(), + error: schemas_object({ + type: schemas_string(), + code: schemas_string(), + message: schemas_string(), + param: schemas_string().nullish() + }) + }), + schemas_object({ + type: schemas_string() + }).loose().transform((value1)=>({ + type: "unknown_chunk", + message: value1.type + })) + ]))); + var openaiResponsesResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + id: schemas_string().optional(), + created_at: schemas_number().optional(), + error: schemas_object({ + message: schemas_string(), + type: schemas_string(), + param: schemas_string().nullish(), + code: schemas_string() + }).nullish(), + model: schemas_string().optional(), + output: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("message"), + role: schemas_literal("assistant"), + id: schemas_string(), + phase: schemas_enum([ + "commentary", + "final_answer" + ]).nullish(), + content: schemas_array(schemas_object({ + type: schemas_literal("output_text"), + text: schemas_string(), + logprobs: schemas_array(schemas_object({ + token: schemas_string(), + logprob: schemas_number(), + top_logprobs: schemas_array(schemas_object({ + token: schemas_string(), + logprob: schemas_number() + })) + })).nullish(), + annotations: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("url_citation"), + start_index: schemas_number(), + end_index: schemas_number(), + url: schemas_string(), + title: schemas_string() + }), + schemas_object({ + type: schemas_literal("file_citation"), + file_id: schemas_string(), + filename: schemas_string(), + index: schemas_number() + }), + schemas_object({ + type: schemas_literal("container_file_citation"), + container_id: schemas_string(), + file_id: schemas_string(), + filename: schemas_string(), + start_index: schemas_number(), + end_index: schemas_number() + }), + schemas_object({ + type: schemas_literal("file_path"), + file_id: schemas_string(), + index: schemas_number() + }) + ])) + })) + }), + schemas_object({ + type: schemas_literal("web_search_call"), + id: schemas_string(), + status: schemas_string(), + action: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("search"), + query: schemas_string().nullish(), + sources: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("url"), + url: schemas_string() + }), + schemas_object({ + type: schemas_literal("api"), + name: schemas_string() + }) + ])).nullish() + }), + schemas_object({ + type: schemas_literal("open_page"), + url: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("find_in_page"), + url: schemas_string().nullish(), + pattern: schemas_string().nullish() + }) + ]).nullish() + }), + schemas_object({ + type: schemas_literal("file_search_call"), + id: schemas_string(), + queries: schemas_array(schemas_string()), + results: schemas_array(schemas_object({ + attributes: schemas_record(schemas_string(), union([ + schemas_string(), + schemas_number(), + schemas_boolean() + ])), + file_id: schemas_string(), + filename: schemas_string(), + score: schemas_number(), + text: schemas_string() + })).nullish() + }), + schemas_object({ + type: schemas_literal("code_interpreter_call"), + id: schemas_string(), + code: schemas_string().nullable(), + container_id: schemas_string(), + outputs: schemas_array(discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("logs"), + logs: schemas_string() + }), + schemas_object({ + type: schemas_literal("image"), + url: schemas_string() + }) + ])).nullable() + }), + schemas_object({ + type: schemas_literal("image_generation_call"), + id: schemas_string(), + result: schemas_string() + }), + schemas_object({ + type: schemas_literal("local_shell_call"), + id: schemas_string(), + call_id: schemas_string(), + action: schemas_object({ + type: schemas_literal("exec"), + command: schemas_array(schemas_string()), + timeout_ms: schemas_number().optional(), + user: schemas_string().optional(), + working_directory: schemas_string().optional(), + env: schemas_record(schemas_string(), schemas_string()).optional() + }) + }), + schemas_object({ + type: schemas_literal("function_call"), + call_id: schemas_string(), + name: schemas_string(), + arguments: schemas_string(), + id: schemas_string() + }), + schemas_object({ + type: schemas_literal("custom_tool_call"), + call_id: schemas_string(), + name: schemas_string(), + input: schemas_string(), + id: schemas_string() + }), + schemas_object({ + type: schemas_literal("computer_call"), + id: schemas_string(), + status: schemas_string().optional() + }), + schemas_object({ + type: schemas_literal("reasoning"), + id: schemas_string(), + encrypted_content: schemas_string().nullish(), + summary: schemas_array(schemas_object({ + type: schemas_literal("summary_text"), + text: schemas_string() + })) + }), + schemas_object({ + type: schemas_literal("mcp_call"), + id: schemas_string(), + status: schemas_string(), + arguments: schemas_string(), + name: schemas_string(), + server_label: schemas_string(), + output: schemas_string().nullish(), + error: union([ + schemas_string(), + schemas_object({ + type: schemas_string().optional(), + code: union([ + schemas_number(), + schemas_string() + ]).optional(), + message: schemas_string().optional() + }).loose() + ]).nullish(), + approval_request_id: schemas_string().nullish() + }), + schemas_object({ + type: schemas_literal("mcp_list_tools"), + id: schemas_string(), + server_label: schemas_string(), + tools: schemas_array(schemas_object({ + name: schemas_string(), + description: schemas_string().optional(), + input_schema: any(), + annotations: schemas_record(schemas_string(), unknown()).optional() + })), + error: union([ + schemas_string(), + schemas_object({ + type: schemas_string().optional(), + code: union([ + schemas_number(), + schemas_string() + ]).optional(), + message: schemas_string().optional() + }).loose() + ]).optional() + }), + schemas_object({ + type: schemas_literal("mcp_approval_request"), + id: schemas_string(), + server_label: schemas_string(), + name: schemas_string(), + arguments: schemas_string(), + approval_request_id: schemas_string().optional() + }), + schemas_object({ + type: schemas_literal("apply_patch_call"), + id: schemas_string(), + call_id: schemas_string(), + status: schemas_enum([ + "in_progress", + "completed" + ]), + operation: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("create_file"), + path: schemas_string(), + diff: schemas_string() + }), + schemas_object({ + type: schemas_literal("delete_file"), + path: schemas_string() + }), + schemas_object({ + type: schemas_literal("update_file"), + path: schemas_string(), + diff: schemas_string() + }) + ]) + }), + schemas_object({ + type: schemas_literal("shell_call"), + id: schemas_string(), + call_id: schemas_string(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + action: schemas_object({ + commands: schemas_array(schemas_string()) + }) + }), + schemas_object({ + type: schemas_literal("shell_call_output"), + id: schemas_string(), + call_id: schemas_string(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + output: schemas_array(schemas_object({ + stdout: schemas_string(), + stderr: schemas_string(), + outcome: discriminatedUnion("type", [ + schemas_object({ + type: schemas_literal("timeout") + }), + schemas_object({ + type: schemas_literal("exit"), + exit_code: schemas_number() + }) + ]) + })) + }), + schemas_object({ + type: schemas_literal("tool_search_call"), + id: schemas_string(), + execution: schemas_enum([ + "server", + "client" + ]), + call_id: schemas_string().nullable(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + arguments: unknown() + }), + schemas_object({ + type: schemas_literal("tool_search_output"), + id: schemas_string(), + execution: schemas_enum([ + "server", + "client" + ]), + call_id: schemas_string().nullable(), + status: schemas_enum([ + "in_progress", + "completed", + "incomplete" + ]), + tools: schemas_array(schemas_record(schemas_string(), jsonValueSchema2.optional())) + }) + ])).optional(), + service_tier: schemas_string().nullish(), + incomplete_details: schemas_object({ + reason: schemas_string() + }).nullish(), + usage: schemas_object({ + input_tokens: schemas_number(), + input_tokens_details: schemas_object({ + cached_tokens: schemas_number().nullish() + }).nullish(), + output_tokens: schemas_number(), + output_tokens_details: schemas_object({ + reasoning_tokens: schemas_number().nullish() + }).nullish() + }).optional() + }))); + var TOP_LOGPROBS_MAX = 20; + var openaiResponsesReasoningModelIds = [ + "o1", + "o1-2024-12-17", + "o3", + "o3-2025-04-16", + "o3-mini", + "o3-mini-2025-01-31", + "o4-mini", + "o4-mini-2025-04-16", + "gpt-5", + "gpt-5-2025-08-07", + "gpt-5-codex", + "gpt-5-mini", + "gpt-5-mini-2025-08-07", + "gpt-5-nano", + "gpt-5-nano-2025-08-07", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1", + "gpt-5.1-chat-latest", + "gpt-5.1-codex-mini", + "gpt-5.1-codex", + "gpt-5.1-codex-max", + "gpt-5.2", + "gpt-5.2-chat-latest", + "gpt-5.2-pro", + "gpt-5.2-codex", + "gpt-5.3-chat-latest", + "gpt-5.3-codex", + "gpt-5.4", + "gpt-5.4-2026-03-05", + "gpt-5.4-mini", + "gpt-5.4-mini-2026-03-17", + "gpt-5.4-nano", + "gpt-5.4-nano-2026-03-17", + "gpt-5.4-pro", + "gpt-5.4-pro-2026-03-05" + ]; + [ + ...openaiResponsesReasoningModelIds + ]; + var openaiLanguageModelResponsesOptionsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + conversation: schemas_string().nullish(), + include: schemas_array(schemas_enum([ + "reasoning.encrypted_content", + "file_search_call.results", + "message.output_text.logprobs" + ])).nullish(), + instructions: schemas_string().nullish(), + logprobs: union([ + schemas_boolean(), + schemas_number().min(1).max(TOP_LOGPROBS_MAX) + ]).optional(), + maxToolCalls: schemas_number().nullish(), + metadata: any().nullish(), + parallelToolCalls: schemas_boolean().nullish(), + previousResponseId: schemas_string().nullish(), + promptCacheKey: schemas_string().nullish(), + promptCacheRetention: schemas_enum([ + "in_memory", + "24h" + ]).nullish(), + reasoningEffort: schemas_string().nullish(), + reasoningSummary: schemas_string().nullish(), + safetyIdentifier: schemas_string().nullish(), + serviceTier: schemas_enum([ + "auto", + "flex", + "priority", + "default" + ]).nullish(), + store: schemas_boolean().nullish(), + strictJsonSchema: schemas_boolean().nullish(), + textVerbosity: schemas_enum([ + "low", + "medium", + "high" + ]).nullish(), + truncation: schemas_enum([ + "auto", + "disabled" + ]).nullish(), + user: schemas_string().nullish(), + systemMessageMode: schemas_enum([ + "system", + "developer", + "remove" + ]).optional(), + forceReasoning: schemas_boolean().optional() + }))); + async function prepareResponsesTools({ tools, toolChoice, toolNameMapping, customProviderToolNames }) { + var _a, _b; + tools = (null == tools ? void 0 : tools.length) ? tools : void 0; + const toolWarnings = []; + if (null == tools) return { + tools: void 0, + toolChoice: void 0, + toolWarnings + }; + const openaiTools2 = []; + const resolvedCustomProviderToolNames = null != customProviderToolNames ? customProviderToolNames : /* @__PURE__ */ new Set(); + for (const tool of tools)switch(tool.type){ + case "function": + { + const openaiOptions = null == (_a = tool.providerOptions) ? void 0 : _a.openai; + const deferLoading = null == openaiOptions ? void 0 : openaiOptions.deferLoading; + openaiTools2.push({ + type: "function", + name: tool.name, + description: tool.description, + parameters: tool.inputSchema, + ...null != tool.strict ? { + strict: tool.strict + } : {}, + ...null != deferLoading ? { + defer_loading: deferLoading + } : {} + }); + break; + } + case "provider": + switch(tool.id){ + case "openai.file_search": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: dist_fileSearchArgsSchema + }); + openaiTools2.push({ + type: "file_search", + vector_store_ids: args.vectorStoreIds, + max_num_results: args.maxNumResults, + ranking_options: args.ranking ? { + ranker: args.ranking.ranker, + score_threshold: args.ranking.scoreThreshold + } : void 0, + filters: args.filters + }); + break; + } + case "openai.local_shell": + openaiTools2.push({ + type: "local_shell" + }); + break; + case "openai.shell": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: shellArgsSchema + }); + openaiTools2.push({ + type: "shell", + ...args.environment && { + environment: mapShellEnvironment(args.environment) + } + }); + break; + } + case "openai.apply_patch": + openaiTools2.push({ + type: "apply_patch" + }); + break; + case "openai.web_search_preview": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: webSearchPreviewArgsSchema + }); + openaiTools2.push({ + type: "web_search_preview", + search_context_size: args.searchContextSize, + user_location: args.userLocation + }); + break; + } + case "openai.web_search": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: webSearchArgsSchema + }); + openaiTools2.push({ + type: "web_search", + filters: null != args.filters ? { + allowed_domains: args.filters.allowedDomains + } : void 0, + external_web_access: args.externalWebAccess, + search_context_size: args.searchContextSize, + user_location: args.userLocation + }); + break; + } + case "openai.code_interpreter": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: codeInterpreterArgsSchema + }); + openaiTools2.push({ + type: "code_interpreter", + container: null == args.container ? { + type: "auto", + file_ids: void 0 + } : "string" == typeof args.container ? args.container : { + type: "auto", + file_ids: args.container.fileIds + } + }); + break; + } + case "openai.image_generation": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: imageGenerationArgsSchema + }); + openaiTools2.push({ + type: "image_generation", + background: args.background, + input_fidelity: args.inputFidelity, + input_image_mask: args.inputImageMask ? { + file_id: args.inputImageMask.fileId, + image_url: args.inputImageMask.imageUrl + } : void 0, + model: args.model, + moderation: args.moderation, + partial_images: args.partialImages, + quality: args.quality, + output_compression: args.outputCompression, + output_format: args.outputFormat, + size: args.size + }); + break; + } + case "openai.mcp": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: mcpArgsSchema + }); + const mapApprovalFilter = (filter)=>({ + tool_names: filter.toolNames + }); + const requireApproval = args.requireApproval; + const requireApprovalParam = null == requireApproval ? void 0 : "string" == typeof requireApproval ? requireApproval : null != requireApproval.never ? { + never: mapApprovalFilter(requireApproval.never) + } : void 0; + openaiTools2.push({ + type: "mcp", + server_label: args.serverLabel, + allowed_tools: Array.isArray(args.allowedTools) ? args.allowedTools : args.allowedTools ? { + read_only: args.allowedTools.readOnly, + tool_names: args.allowedTools.toolNames + } : void 0, + authorization: args.authorization, + connector_id: args.connectorId, + headers: args.headers, + require_approval: null != requireApprovalParam ? requireApprovalParam : "never", + server_description: args.serverDescription, + server_url: args.serverUrl + }); + break; + } + case "openai.custom": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: customArgsSchema + }); + openaiTools2.push({ + type: "custom", + name: args.name, + description: args.description, + format: args.format + }); + resolvedCustomProviderToolNames.add(args.name); + break; + } + case "openai.tool_search": + { + const args = await dist_validateTypes({ + value: tool.args, + schema: toolSearchArgsSchema + }); + openaiTools2.push({ + type: "tool_search", + ...null != args.execution ? { + execution: args.execution + } : {}, + ...null != args.description ? { + description: args.description + } : {}, + ...null != args.parameters ? { + parameters: args.parameters + } : {} + }); + break; + } + } + break; + default: + toolWarnings.push({ + type: "unsupported", + feature: `function tool ${tool}` + }); + break; + } + if (null == toolChoice) return { + tools: openaiTools2, + toolChoice: void 0, + toolWarnings + }; + const type = toolChoice.type; + switch(type){ + case "auto": + case "none": + case "required": + return { + tools: openaiTools2, + toolChoice: type, + toolWarnings + }; + case "tool": + { + const resolvedToolName = null != (_b = null == toolNameMapping ? void 0 : toolNameMapping.toProviderToolName(toolChoice.toolName)) ? _b : toolChoice.toolName; + return { + tools: openaiTools2, + toolChoice: "code_interpreter" === resolvedToolName || "file_search" === resolvedToolName || "image_generation" === resolvedToolName || "web_search_preview" === resolvedToolName || "web_search" === resolvedToolName || "mcp" === resolvedToolName || "apply_patch" === resolvedToolName ? { + type: resolvedToolName + } : resolvedCustomProviderToolNames.has(resolvedToolName) ? { + type: "custom", + name: resolvedToolName + } : { + type: "function", + name: resolvedToolName + }, + toolWarnings + }; + } + default: + { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `tool choice type: ${_exhaustiveCheck}` + }); + } + } + } + function mapShellEnvironment(environment) { + if ("containerReference" === environment.type) { + const env2 = environment; + return { + type: "container_reference", + container_id: env2.containerId + }; + } + if ("containerAuto" === environment.type) { + const env2 = environment; + return { + type: "container_auto", + file_ids: env2.fileIds, + memory_limit: env2.memoryLimit, + network_policy: null == env2.networkPolicy ? void 0 : "disabled" === env2.networkPolicy.type ? { + type: "disabled" + } : { + type: "allowlist", + allowed_domains: env2.networkPolicy.allowedDomains, + domain_secrets: env2.networkPolicy.domainSecrets + }, + skills: mapShellSkills(env2.skills) + }; + } + const env = environment; + return { + type: "local", + skills: env.skills + }; + } + function mapShellSkills(skills) { + return null == skills ? void 0 : skills.map((skill)=>"skillReference" === skill.type ? { + type: "skill_reference", + skill_id: skill.skillId, + version: skill.version + } : { + type: "inline", + name: skill.name, + description: skill.description, + source: { + type: "base64", + media_type: skill.source.mediaType, + data: skill.source.data + } + }); + } + function extractApprovalRequestIdToToolCallIdMapping(prompt) { + var _a, _b; + const mapping = {}; + for (const message of prompt)if ("assistant" === message.role) for (const part of message.content){ + if ("tool-call" !== part.type) continue; + const approvalRequestId = null == (_b = null == (_a = part.providerOptions) ? void 0 : _a.openai) ? void 0 : _b.approvalRequestId; + if (null != approvalRequestId) mapping[approvalRequestId] = part.toolCallId; + } + return mapping; + } + var OpenAIResponsesLanguageModel = class { + constructor(modelId, config){ + this.specificationVersion = "v3"; + this.supportedUrls = { + "image/*": [ + /^https?:\/\/.*$/ + ], + "application/pdf": [ + /^https?:\/\/.*$/ + ] + }; + this.modelId = modelId; + this.config = config; + } + get provider() { + return this.config.provider; + } + async getArgs({ maxOutputTokens, temperature, stopSequences, topP, topK, presencePenalty, frequencyPenalty, seed, prompt, providerOptions, tools, toolChoice, responseFormat }) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i; + const warnings = []; + const modelCapabilities = getOpenAILanguageModelCapabilities(this.modelId); + if (null != topK) warnings.push({ + type: "unsupported", + feature: "topK" + }); + if (null != seed) warnings.push({ + type: "unsupported", + feature: "seed" + }); + if (null != presencePenalty) warnings.push({ + type: "unsupported", + feature: "presencePenalty" + }); + if (null != frequencyPenalty) warnings.push({ + type: "unsupported", + feature: "frequencyPenalty" + }); + if (null != stopSequences) warnings.push({ + type: "unsupported", + feature: "stopSequences" + }); + const providerOptionsName = this.config.provider.includes("azure") ? "azure" : "openai"; + let openaiOptions = await parseProviderOptions({ + provider: providerOptionsName, + providerOptions, + schema: openaiLanguageModelResponsesOptionsSchema + }); + if (null == openaiOptions && "openai" !== providerOptionsName) openaiOptions = await parseProviderOptions({ + provider: "openai", + providerOptions, + schema: openaiLanguageModelResponsesOptionsSchema + }); + const isReasoningModel = null != (_a = null == openaiOptions ? void 0 : openaiOptions.forceReasoning) ? _a : modelCapabilities.isReasoningModel; + if ((null == openaiOptions ? void 0 : openaiOptions.conversation) && (null == openaiOptions ? void 0 : openaiOptions.previousResponseId)) warnings.push({ + type: "unsupported", + feature: "conversation", + details: "conversation and previousResponseId cannot be used together" + }); + const toolNameMapping = createToolNameMapping({ + tools, + providerToolNames: { + "openai.code_interpreter": "code_interpreter", + "openai.file_search": "file_search", + "openai.image_generation": "image_generation", + "openai.local_shell": "local_shell", + "openai.shell": "shell", + "openai.web_search": "web_search", + "openai.web_search_preview": "web_search_preview", + "openai.mcp": "mcp", + "openai.apply_patch": "apply_patch", + "openai.tool_search": "tool_search" + }, + resolveProviderToolName: (tool)=>"openai.custom" === tool.id ? tool.args.name : void 0 + }); + const customProviderToolNames = /* @__PURE__ */ new Set(); + const { tools: openaiTools2, toolChoice: openaiToolChoice, toolWarnings } = await prepareResponsesTools({ + tools, + toolChoice, + toolNameMapping, + customProviderToolNames + }); + const { input, warnings: inputWarnings } = await convertToOpenAIResponsesInput({ + prompt, + toolNameMapping, + systemMessageMode: null != (_b = null == openaiOptions ? void 0 : openaiOptions.systemMessageMode) ? _b : isReasoningModel ? "developer" : modelCapabilities.systemMessageMode, + providerOptionsName, + fileIdPrefixes: this.config.fileIdPrefixes, + store: null != (_c = null == openaiOptions ? void 0 : openaiOptions.store) ? _c : true, + hasConversation: (null == openaiOptions ? void 0 : openaiOptions.conversation) != null, + hasLocalShellTool: hasOpenAITool("openai.local_shell"), + hasShellTool: hasOpenAITool("openai.shell"), + hasApplyPatchTool: hasOpenAITool("openai.apply_patch"), + customProviderToolNames: customProviderToolNames.size > 0 ? customProviderToolNames : void 0 + }); + warnings.push(...inputWarnings); + const strictJsonSchema = null != (_d = null == openaiOptions ? void 0 : openaiOptions.strictJsonSchema) ? _d : true; + let include = null == openaiOptions ? void 0 : openaiOptions.include; + function addInclude(key) { + if (null == include) include = [ + key + ]; + else if (!include.includes(key)) include = [ + ...include, + key + ]; + } + function hasOpenAITool(id) { + return (null == tools ? void 0 : tools.find((tool)=>"provider" === tool.type && tool.id === id)) != null; + } + const topLogprobs = "number" == typeof (null == openaiOptions ? void 0 : openaiOptions.logprobs) ? null == openaiOptions ? void 0 : openaiOptions.logprobs : (null == openaiOptions ? void 0 : openaiOptions.logprobs) === true ? TOP_LOGPROBS_MAX : void 0; + if (topLogprobs) addInclude("message.output_text.logprobs"); + const webSearchToolName = null == (_e = null == tools ? void 0 : tools.find((tool)=>"provider" === tool.type && ("openai.web_search" === tool.id || "openai.web_search_preview" === tool.id))) ? void 0 : _e.name; + if (webSearchToolName) addInclude("web_search_call.action.sources"); + if (hasOpenAITool("openai.code_interpreter")) addInclude("code_interpreter_call.outputs"); + const store = null == openaiOptions ? void 0 : openaiOptions.store; + if (false === store && isReasoningModel) addInclude("reasoning.encrypted_content"); + const baseArgs = { + model: this.modelId, + input, + temperature, + top_p: topP, + max_output_tokens: maxOutputTokens, + ...((null == responseFormat ? void 0 : responseFormat.type) === "json" || (null == openaiOptions ? void 0 : openaiOptions.textVerbosity)) && { + text: { + ...(null == responseFormat ? void 0 : responseFormat.type) === "json" && { + format: null != responseFormat.schema ? { + type: "json_schema", + strict: strictJsonSchema, + name: null != (_f = responseFormat.name) ? _f : "response", + description: responseFormat.description, + schema: responseFormat.schema + } : { + type: "json_object" + } + }, + ...(null == openaiOptions ? void 0 : openaiOptions.textVerbosity) && { + verbosity: openaiOptions.textVerbosity + } + } + }, + conversation: null == openaiOptions ? void 0 : openaiOptions.conversation, + max_tool_calls: null == openaiOptions ? void 0 : openaiOptions.maxToolCalls, + metadata: null == openaiOptions ? void 0 : openaiOptions.metadata, + parallel_tool_calls: null == openaiOptions ? void 0 : openaiOptions.parallelToolCalls, + previous_response_id: null == openaiOptions ? void 0 : openaiOptions.previousResponseId, + store, + user: null == openaiOptions ? void 0 : openaiOptions.user, + instructions: null == openaiOptions ? void 0 : openaiOptions.instructions, + service_tier: null == openaiOptions ? void 0 : openaiOptions.serviceTier, + include, + prompt_cache_key: null == openaiOptions ? void 0 : openaiOptions.promptCacheKey, + prompt_cache_retention: null == openaiOptions ? void 0 : openaiOptions.promptCacheRetention, + safety_identifier: null == openaiOptions ? void 0 : openaiOptions.safetyIdentifier, + top_logprobs: topLogprobs, + truncation: null == openaiOptions ? void 0 : openaiOptions.truncation, + ...isReasoningModel && ((null == openaiOptions ? void 0 : openaiOptions.reasoningEffort) != null || (null == openaiOptions ? void 0 : openaiOptions.reasoningSummary) != null) && { + reasoning: { + ...(null == openaiOptions ? void 0 : openaiOptions.reasoningEffort) != null && { + effort: openaiOptions.reasoningEffort + }, + ...(null == openaiOptions ? void 0 : openaiOptions.reasoningSummary) != null && { + summary: openaiOptions.reasoningSummary + } + } + } + }; + if (isReasoningModel) { + if (!((null == openaiOptions ? void 0 : openaiOptions.reasoningEffort) === "none" && modelCapabilities.supportsNonReasoningParameters)) { + if (null != baseArgs.temperature) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported", + feature: "temperature", + details: "temperature is not supported for reasoning models" + }); + } + if (null != baseArgs.top_p) { + baseArgs.top_p = void 0; + warnings.push({ + type: "unsupported", + feature: "topP", + details: "topP is not supported for reasoning models" + }); + } + } + } else { + if ((null == openaiOptions ? void 0 : openaiOptions.reasoningEffort) != null) warnings.push({ + type: "unsupported", + feature: "reasoningEffort", + details: "reasoningEffort is not supported for non-reasoning models" + }); + if ((null == openaiOptions ? void 0 : openaiOptions.reasoningSummary) != null) warnings.push({ + type: "unsupported", + feature: "reasoningSummary", + details: "reasoningSummary is not supported for non-reasoning models" + }); + } + if ((null == openaiOptions ? void 0 : openaiOptions.serviceTier) === "flex" && !modelCapabilities.supportsFlexProcessing) { + warnings.push({ + type: "unsupported", + feature: "serviceTier", + details: "flex processing is only available for o3, o4-mini, and gpt-5 models" + }); + delete baseArgs.service_tier; + } + if ((null == openaiOptions ? void 0 : openaiOptions.serviceTier) === "priority" && !modelCapabilities.supportsPriorityProcessing) { + warnings.push({ + type: "unsupported", + feature: "serviceTier", + details: "priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported" + }); + delete baseArgs.service_tier; + } + const shellToolEnvType = null == (_i = null == (_h = null == (_g = null == tools ? void 0 : tools.find((tool)=>"provider" === tool.type && "openai.shell" === tool.id)) ? void 0 : _g.args) ? void 0 : _h.environment) ? void 0 : _i.type; + const isShellProviderExecuted = "containerAuto" === shellToolEnvType || "containerReference" === shellToolEnvType; + return { + webSearchToolName, + args: { + ...baseArgs, + tools: openaiTools2, + tool_choice: openaiToolChoice + }, + warnings: [ + ...warnings, + ...toolWarnings + ], + store, + toolNameMapping, + providerOptionsName, + isShellProviderExecuted + }; + } + async doGenerate(options1) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B; + const { args: body, warnings, webSearchToolName, toolNameMapping, providerOptionsName, isShellProviderExecuted } = await this.getArgs(options1); + const url = this.config.url({ + path: "/responses", + modelId: this.modelId + }); + const approvalRequestIdToDummyToolCallIdFromPrompt = extractApprovalRequestIdToToolCallIdMapping(options1.prompt); + const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({ + url, + headers: combineHeaders(this.config.headers(), options1.headers), + body, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(openaiResponsesResponseSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + if (response.error) throw new APICallError({ + message: response.error.message, + url, + requestBodyValues: body, + statusCode: 400, + responseHeaders, + responseBody: rawResponse, + isRetryable: false + }); + const content = []; + const logprobs = []; + let hasFunctionCall = false; + const hostedToolSearchCallIds = []; + for (const part of response.output)switch(part.type){ + case "reasoning": + if (0 === part.summary.length) part.summary.push({ + type: "summary_text", + text: "" + }); + for (const summary of part.summary)content.push({ + type: "reasoning", + text: summary.text, + providerMetadata: { + [providerOptionsName]: { + itemId: part.id, + reasoningEncryptedContent: null != (_a = part.encrypted_content) ? _a : null + } + } + }); + break; + case "image_generation_call": + content.push({ + type: "tool-call", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName("image_generation"), + input: "{}", + providerExecuted: true + }); + content.push({ + type: "tool-result", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName("image_generation"), + result: { + result: part.result + } + }); + break; + case "tool_search_call": + { + const toolCallId = null != (_b = part.call_id) ? _b : part.id; + const isHosted = "server" === part.execution; + if (isHosted) hostedToolSearchCallIds.push(toolCallId); + content.push({ + type: "tool-call", + toolCallId, + toolName: toolNameMapping.toCustomToolName("tool_search"), + input: JSON.stringify({ + arguments: part.arguments, + call_id: part.call_id + }), + ...isHosted ? { + providerExecuted: true + } : {}, + providerMetadata: { + [providerOptionsName]: { + itemId: part.id + } + } + }); + break; + } + case "tool_search_output": + { + const toolCallId = null != (_d = null != (_c = part.call_id) ? _c : hostedToolSearchCallIds.shift()) ? _d : part.id; + content.push({ + type: "tool-result", + toolCallId, + toolName: toolNameMapping.toCustomToolName("tool_search"), + result: { + tools: part.tools + }, + providerMetadata: { + [providerOptionsName]: { + itemId: part.id + } + } + }); + break; + } + case "local_shell_call": + content.push({ + type: "tool-call", + toolCallId: part.call_id, + toolName: toolNameMapping.toCustomToolName("local_shell"), + input: JSON.stringify({ + action: part.action + }), + providerMetadata: { + [providerOptionsName]: { + itemId: part.id + } + } + }); + break; + case "shell_call": + content.push({ + type: "tool-call", + toolCallId: part.call_id, + toolName: toolNameMapping.toCustomToolName("shell"), + input: JSON.stringify({ + action: { + commands: part.action.commands + } + }), + ...isShellProviderExecuted && { + providerExecuted: true + }, + providerMetadata: { + [providerOptionsName]: { + itemId: part.id + } + } + }); + break; + case "shell_call_output": + content.push({ + type: "tool-result", + toolCallId: part.call_id, + toolName: toolNameMapping.toCustomToolName("shell"), + result: { + output: part.output.map((item)=>({ + stdout: item.stdout, + stderr: item.stderr, + outcome: "exit" === item.outcome.type ? { + type: "exit", + exitCode: item.outcome.exit_code + } : { + type: "timeout" + } + })) + } + }); + break; + case "message": + for (const contentPart of part.content){ + if ((null == (_f = null == (_e = options1.providerOptions) ? void 0 : _e[providerOptionsName]) ? void 0 : _f.logprobs) && contentPart.logprobs) logprobs.push(contentPart.logprobs); + const providerMetadata2 = { + itemId: part.id, + ...null != part.phase && { + phase: part.phase + }, + ...contentPart.annotations.length > 0 && { + annotations: contentPart.annotations + } + }; + content.push({ + type: "text", + text: contentPart.text, + providerMetadata: { + [providerOptionsName]: providerMetadata2 + } + }); + for (const annotation of contentPart.annotations)if ("url_citation" === annotation.type) content.push({ + type: "source", + sourceType: "url", + id: null != (_i = null == (_h = (_g = this.config).generateId) ? void 0 : _h.call(_g)) ? _i : generateId(), + url: annotation.url, + title: annotation.title + }); + else if ("file_citation" === annotation.type) content.push({ + type: "source", + sourceType: "document", + id: null != (_l = null == (_k = (_j = this.config).generateId) ? void 0 : _k.call(_j)) ? _l : generateId(), + mediaType: "text/plain", + title: annotation.filename, + filename: annotation.filename, + providerMetadata: { + [providerOptionsName]: { + type: annotation.type, + fileId: annotation.file_id, + index: annotation.index + } + } + }); + else if ("container_file_citation" === annotation.type) content.push({ + type: "source", + sourceType: "document", + id: null != (_o = null == (_n = (_m = this.config).generateId) ? void 0 : _n.call(_m)) ? _o : generateId(), + mediaType: "text/plain", + title: annotation.filename, + filename: annotation.filename, + providerMetadata: { + [providerOptionsName]: { + type: annotation.type, + fileId: annotation.file_id, + containerId: annotation.container_id + } + } + }); + else if ("file_path" === annotation.type) content.push({ + type: "source", + sourceType: "document", + id: null != (_r = null == (_q = (_p = this.config).generateId) ? void 0 : _q.call(_p)) ? _r : generateId(), + mediaType: "application/octet-stream", + title: annotation.file_id, + filename: annotation.file_id, + providerMetadata: { + [providerOptionsName]: { + type: annotation.type, + fileId: annotation.file_id, + index: annotation.index + } + } + }); + } + break; + case "function_call": + hasFunctionCall = true; + content.push({ + type: "tool-call", + toolCallId: part.call_id, + toolName: part.name, + input: part.arguments, + providerMetadata: { + [providerOptionsName]: { + itemId: part.id + } + } + }); + break; + case "custom_tool_call": + { + hasFunctionCall = true; + const toolName = toolNameMapping.toCustomToolName(part.name); + content.push({ + type: "tool-call", + toolCallId: part.call_id, + toolName, + input: JSON.stringify(part.input), + providerMetadata: { + [providerOptionsName]: { + itemId: part.id + } + } + }); + break; + } + case "web_search_call": + content.push({ + type: "tool-call", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName(null != webSearchToolName ? webSearchToolName : "web_search"), + input: JSON.stringify({}), + providerExecuted: true + }); + content.push({ + type: "tool-result", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName(null != webSearchToolName ? webSearchToolName : "web_search"), + result: mapWebSearchOutput(part.action) + }); + break; + case "mcp_call": + { + const toolCallId = null != part.approval_request_id ? null != (_s = approvalRequestIdToDummyToolCallIdFromPrompt[part.approval_request_id]) ? _s : part.id : part.id; + const toolName = `mcp.${part.name}`; + content.push({ + type: "tool-call", + toolCallId, + toolName, + input: part.arguments, + providerExecuted: true, + dynamic: true + }); + content.push({ + type: "tool-result", + toolCallId, + toolName, + result: { + type: "call", + serverLabel: part.server_label, + name: part.name, + arguments: part.arguments, + ...null != part.output ? { + output: part.output + } : {}, + ...null != part.error ? { + error: part.error + } : {} + }, + providerMetadata: { + [providerOptionsName]: { + itemId: part.id + } + } + }); + break; + } + case "mcp_list_tools": + break; + case "mcp_approval_request": + { + const approvalRequestId = null != (_t = part.approval_request_id) ? _t : part.id; + const dummyToolCallId = null != (_w = null == (_v = (_u = this.config).generateId) ? void 0 : _v.call(_u)) ? _w : generateId(); + const toolName = `mcp.${part.name}`; + content.push({ + type: "tool-call", + toolCallId: dummyToolCallId, + toolName, + input: part.arguments, + providerExecuted: true, + dynamic: true + }); + content.push({ + type: "tool-approval-request", + approvalId: approvalRequestId, + toolCallId: dummyToolCallId + }); + break; + } + case "computer_call": + content.push({ + type: "tool-call", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName("computer_use"), + input: "", + providerExecuted: true + }); + content.push({ + type: "tool-result", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName("computer_use"), + result: { + type: "computer_use_tool_result", + status: part.status || "completed" + } + }); + break; + case "file_search_call": + content.push({ + type: "tool-call", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName("file_search"), + input: "{}", + providerExecuted: true + }); + content.push({ + type: "tool-result", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName("file_search"), + result: { + queries: part.queries, + results: null != (_y = null == (_x = part.results) ? void 0 : _x.map((result)=>({ + attributes: result.attributes, + fileId: result.file_id, + filename: result.filename, + score: result.score, + text: result.text + }))) ? _y : null + } + }); + break; + case "code_interpreter_call": + content.push({ + type: "tool-call", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName("code_interpreter"), + input: JSON.stringify({ + code: part.code, + containerId: part.container_id + }), + providerExecuted: true + }); + content.push({ + type: "tool-result", + toolCallId: part.id, + toolName: toolNameMapping.toCustomToolName("code_interpreter"), + result: { + outputs: part.outputs + } + }); + break; + case "apply_patch_call": + content.push({ + type: "tool-call", + toolCallId: part.call_id, + toolName: toolNameMapping.toCustomToolName("apply_patch"), + input: JSON.stringify({ + callId: part.call_id, + operation: part.operation + }), + providerMetadata: { + [providerOptionsName]: { + itemId: part.id + } + } + }); + break; + } + const providerMetadata = { + [providerOptionsName]: { + responseId: response.id, + ...logprobs.length > 0 ? { + logprobs + } : {}, + ..."string" == typeof response.service_tier ? { + serviceTier: response.service_tier + } : {} + } + }; + const usage = response.usage; + return { + content, + finishReason: { + unified: mapOpenAIResponseFinishReason({ + finishReason: null == (_z = response.incomplete_details) ? void 0 : _z.reason, + hasFunctionCall + }), + raw: null != (_B = null == (_A = response.incomplete_details) ? void 0 : _A.reason) ? _B : void 0 + }, + usage: convertOpenAIResponsesUsage(usage), + request: { + body + }, + response: { + id: response.id, + timestamp: new Date(1e3 * response.created_at), + modelId: response.model, + headers: responseHeaders, + body: rawResponse + }, + providerMetadata, + warnings + }; + } + async doStream(options1) { + const { args: body, warnings, webSearchToolName, toolNameMapping, store, providerOptionsName, isShellProviderExecuted } = await this.getArgs(options1); + const { responseHeaders, value: response } = await postJsonToApi({ + url: this.config.url({ + path: "/responses", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options1.headers), + body: { + ...body, + stream: true + }, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler(openaiResponsesChunkSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + const self1 = this; + const approvalRequestIdToDummyToolCallIdFromPrompt = extractApprovalRequestIdToToolCallIdMapping(options1.prompt); + const approvalRequestIdToDummyToolCallIdFromStream = /* @__PURE__ */ new Map(); + let finishReason = { + unified: "other", + raw: void 0 + }; + let usage; + const logprobs = []; + let responseId = null; + const ongoingToolCalls = {}; + const ongoingAnnotations = []; + let activeMessagePhase; + let hasFunctionCall = false; + const activeReasoning = {}; + let serviceTier; + const hostedToolSearchCallIds = []; + return { + stream: response.pipeThrough(new TransformStream({ + start (controller) { + controller.enqueue({ + type: "stream-start", + warnings + }); + }, + transform (chunk, controller) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L; + if (options1.includeRawChunks) controller.enqueue({ + type: "raw", + rawValue: chunk.rawValue + }); + if (!chunk.success) { + finishReason = { + unified: "error", + raw: void 0 + }; + controller.enqueue({ + type: "error", + error: chunk.error + }); + return; + } + const value1 = chunk.value; + if (isResponseOutputItemAddedChunk(value1)) { + if ("function_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = { + toolName: value1.item.name, + toolCallId: value1.item.call_id + }; + controller.enqueue({ + type: "tool-input-start", + id: value1.item.call_id, + toolName: value1.item.name + }); + } else if ("custom_tool_call" === value1.item.type) { + const toolName = toolNameMapping.toCustomToolName(value1.item.name); + ongoingToolCalls[value1.output_index] = { + toolName, + toolCallId: value1.item.call_id + }; + controller.enqueue({ + type: "tool-input-start", + id: value1.item.call_id, + toolName + }); + } else if ("web_search_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = { + toolName: toolNameMapping.toCustomToolName(null != webSearchToolName ? webSearchToolName : "web_search"), + toolCallId: value1.item.id + }; + controller.enqueue({ + type: "tool-input-start", + id: value1.item.id, + toolName: toolNameMapping.toCustomToolName(null != webSearchToolName ? webSearchToolName : "web_search"), + providerExecuted: true + }); + controller.enqueue({ + type: "tool-input-end", + id: value1.item.id + }); + controller.enqueue({ + type: "tool-call", + toolCallId: value1.item.id, + toolName: toolNameMapping.toCustomToolName(null != webSearchToolName ? webSearchToolName : "web_search"), + input: JSON.stringify({}), + providerExecuted: true + }); + } else if ("computer_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = { + toolName: toolNameMapping.toCustomToolName("computer_use"), + toolCallId: value1.item.id + }; + controller.enqueue({ + type: "tool-input-start", + id: value1.item.id, + toolName: toolNameMapping.toCustomToolName("computer_use"), + providerExecuted: true + }); + } else if ("code_interpreter_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = { + toolName: toolNameMapping.toCustomToolName("code_interpreter"), + toolCallId: value1.item.id, + codeInterpreter: { + containerId: value1.item.container_id + } + }; + controller.enqueue({ + type: "tool-input-start", + id: value1.item.id, + toolName: toolNameMapping.toCustomToolName("code_interpreter"), + providerExecuted: true + }); + controller.enqueue({ + type: "tool-input-delta", + id: value1.item.id, + delta: `{"containerId":"${value1.item.container_id}","code":"` + }); + } else if ("file_search_call" === value1.item.type) controller.enqueue({ + type: "tool-call", + toolCallId: value1.item.id, + toolName: toolNameMapping.toCustomToolName("file_search"), + input: "{}", + providerExecuted: true + }); + else if ("image_generation_call" === value1.item.type) controller.enqueue({ + type: "tool-call", + toolCallId: value1.item.id, + toolName: toolNameMapping.toCustomToolName("image_generation"), + input: "{}", + providerExecuted: true + }); + else if ("tool_search_call" === value1.item.type) { + const toolCallId = value1.item.id; + const toolName = toolNameMapping.toCustomToolName("tool_search"); + const isHosted = "server" === value1.item.execution; + ongoingToolCalls[value1.output_index] = { + toolName, + toolCallId, + toolSearchExecution: null != (_a = value1.item.execution) ? _a : "server" + }; + if (isHosted) controller.enqueue({ + type: "tool-input-start", + id: toolCallId, + toolName, + providerExecuted: true + }); + } else if ("tool_search_output" === value1.item.type) ; + else if ("mcp_call" === value1.item.type || "mcp_list_tools" === value1.item.type || "mcp_approval_request" === value1.item.type) ; + else if ("apply_patch_call" === value1.item.type) { + const { call_id: callId, operation } = value1.item; + ongoingToolCalls[value1.output_index] = { + toolName: toolNameMapping.toCustomToolName("apply_patch"), + toolCallId: callId, + applyPatch: { + hasDiff: "delete_file" === operation.type, + endEmitted: "delete_file" === operation.type + } + }; + controller.enqueue({ + type: "tool-input-start", + id: callId, + toolName: toolNameMapping.toCustomToolName("apply_patch") + }); + if ("delete_file" === operation.type) { + const inputString = JSON.stringify({ + callId, + operation + }); + controller.enqueue({ + type: "tool-input-delta", + id: callId, + delta: inputString + }); + controller.enqueue({ + type: "tool-input-end", + id: callId + }); + } else controller.enqueue({ + type: "tool-input-delta", + id: callId, + delta: `{"callId":"${escapeJSONDelta(callId)}","operation":{"type":"${escapeJSONDelta(operation.type)}","path":"${escapeJSONDelta(operation.path)}","diff":"` + }); + } else if ("shell_call" === value1.item.type) ongoingToolCalls[value1.output_index] = { + toolName: toolNameMapping.toCustomToolName("shell"), + toolCallId: value1.item.call_id + }; + else if ("shell_call_output" === value1.item.type) ; + else if ("message" === value1.item.type) { + ongoingAnnotations.splice(0, ongoingAnnotations.length); + activeMessagePhase = null != (_b = value1.item.phase) ? _b : void 0; + controller.enqueue({ + type: "text-start", + id: value1.item.id, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id, + ...null != value1.item.phase && { + phase: value1.item.phase + } + } + } + }); + } else if (isResponseOutputItemAddedChunk(value1) && "reasoning" === value1.item.type) { + activeReasoning[value1.item.id] = { + encryptedContent: value1.item.encrypted_content, + summaryParts: { + 0: "active" + } + }; + controller.enqueue({ + type: "reasoning-start", + id: `${value1.item.id}:0`, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id, + reasoningEncryptedContent: null != (_c = value1.item.encrypted_content) ? _c : null + } + } + }); + } + } else if (isResponseOutputItemDoneChunk(value1)) { + if ("message" === value1.item.type) { + const phase = null != (_d = value1.item.phase) ? _d : activeMessagePhase; + activeMessagePhase = void 0; + controller.enqueue({ + type: "text-end", + id: value1.item.id, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id, + ...null != phase && { + phase + }, + ...ongoingAnnotations.length > 0 && { + annotations: ongoingAnnotations + } + } + } + }); + } else if ("function_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = void 0; + hasFunctionCall = true; + controller.enqueue({ + type: "tool-input-end", + id: value1.item.call_id + }); + controller.enqueue({ + type: "tool-call", + toolCallId: value1.item.call_id, + toolName: value1.item.name, + input: value1.item.arguments, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id + } + } + }); + } else if ("custom_tool_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = void 0; + hasFunctionCall = true; + const toolName = toolNameMapping.toCustomToolName(value1.item.name); + controller.enqueue({ + type: "tool-input-end", + id: value1.item.call_id + }); + controller.enqueue({ + type: "tool-call", + toolCallId: value1.item.call_id, + toolName, + input: JSON.stringify(value1.item.input), + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id + } + } + }); + } else if ("web_search_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = void 0; + controller.enqueue({ + type: "tool-result", + toolCallId: value1.item.id, + toolName: toolNameMapping.toCustomToolName(null != webSearchToolName ? webSearchToolName : "web_search"), + result: mapWebSearchOutput(value1.item.action) + }); + } else if ("computer_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = void 0; + controller.enqueue({ + type: "tool-input-end", + id: value1.item.id + }); + controller.enqueue({ + type: "tool-call", + toolCallId: value1.item.id, + toolName: toolNameMapping.toCustomToolName("computer_use"), + input: "", + providerExecuted: true + }); + controller.enqueue({ + type: "tool-result", + toolCallId: value1.item.id, + toolName: toolNameMapping.toCustomToolName("computer_use"), + result: { + type: "computer_use_tool_result", + status: value1.item.status || "completed" + } + }); + } else if ("file_search_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = void 0; + controller.enqueue({ + type: "tool-result", + toolCallId: value1.item.id, + toolName: toolNameMapping.toCustomToolName("file_search"), + result: { + queries: value1.item.queries, + results: null != (_f = null == (_e = value1.item.results) ? void 0 : _e.map((result)=>({ + attributes: result.attributes, + fileId: result.file_id, + filename: result.filename, + score: result.score, + text: result.text + }))) ? _f : null + } + }); + } else if ("code_interpreter_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = void 0; + controller.enqueue({ + type: "tool-result", + toolCallId: value1.item.id, + toolName: toolNameMapping.toCustomToolName("code_interpreter"), + result: { + outputs: value1.item.outputs + } + }); + } else if ("image_generation_call" === value1.item.type) controller.enqueue({ + type: "tool-result", + toolCallId: value1.item.id, + toolName: toolNameMapping.toCustomToolName("image_generation"), + result: { + result: value1.item.result + } + }); + else if ("tool_search_call" === value1.item.type) { + const toolCall = ongoingToolCalls[value1.output_index]; + const isHosted = "server" === value1.item.execution; + if (null != toolCall) { + const toolCallId = isHosted ? toolCall.toolCallId : null != (_g = value1.item.call_id) ? _g : value1.item.id; + if (isHosted) hostedToolSearchCallIds.push(toolCallId); + else controller.enqueue({ + type: "tool-input-start", + id: toolCallId, + toolName: toolCall.toolName + }); + controller.enqueue({ + type: "tool-input-end", + id: toolCallId + }); + controller.enqueue({ + type: "tool-call", + toolCallId, + toolName: toolCall.toolName, + input: JSON.stringify({ + arguments: value1.item.arguments, + call_id: isHosted ? null : toolCallId + }), + ...isHosted ? { + providerExecuted: true + } : {}, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id + } + } + }); + } + ongoingToolCalls[value1.output_index] = void 0; + } else if ("tool_search_output" === value1.item.type) { + const toolCallId = null != (_i = null != (_h = value1.item.call_id) ? _h : hostedToolSearchCallIds.shift()) ? _i : value1.item.id; + controller.enqueue({ + type: "tool-result", + toolCallId, + toolName: toolNameMapping.toCustomToolName("tool_search"), + result: { + tools: value1.item.tools + }, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id + } + } + }); + } else if ("mcp_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = void 0; + const approvalRequestId = null != (_j = value1.item.approval_request_id) ? _j : void 0; + const aliasedToolCallId = null != approvalRequestId ? null != (_l = null != (_k = approvalRequestIdToDummyToolCallIdFromStream.get(approvalRequestId)) ? _k : approvalRequestIdToDummyToolCallIdFromPrompt[approvalRequestId]) ? _l : value1.item.id : value1.item.id; + const toolName = `mcp.${value1.item.name}`; + controller.enqueue({ + type: "tool-call", + toolCallId: aliasedToolCallId, + toolName, + input: value1.item.arguments, + providerExecuted: true, + dynamic: true + }); + controller.enqueue({ + type: "tool-result", + toolCallId: aliasedToolCallId, + toolName, + result: { + type: "call", + serverLabel: value1.item.server_label, + name: value1.item.name, + arguments: value1.item.arguments, + ...null != value1.item.output ? { + output: value1.item.output + } : {}, + ...null != value1.item.error ? { + error: value1.item.error + } : {} + }, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id + } + } + }); + } else if ("mcp_list_tools" === value1.item.type) ongoingToolCalls[value1.output_index] = void 0; + else if ("apply_patch_call" === value1.item.type) { + const toolCall = ongoingToolCalls[value1.output_index]; + if ((null == toolCall ? void 0 : toolCall.applyPatch) && !toolCall.applyPatch.endEmitted && "delete_file" !== value1.item.operation.type) { + if (!toolCall.applyPatch.hasDiff) controller.enqueue({ + type: "tool-input-delta", + id: toolCall.toolCallId, + delta: escapeJSONDelta(value1.item.operation.diff) + }); + controller.enqueue({ + type: "tool-input-delta", + id: toolCall.toolCallId, + delta: '"}}' + }); + controller.enqueue({ + type: "tool-input-end", + id: toolCall.toolCallId + }); + toolCall.applyPatch.endEmitted = true; + } + if (toolCall && "completed" === value1.item.status) controller.enqueue({ + type: "tool-call", + toolCallId: toolCall.toolCallId, + toolName: toolNameMapping.toCustomToolName("apply_patch"), + input: JSON.stringify({ + callId: value1.item.call_id, + operation: value1.item.operation + }), + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id + } + } + }); + ongoingToolCalls[value1.output_index] = void 0; + } else if ("mcp_approval_request" === value1.item.type) { + ongoingToolCalls[value1.output_index] = void 0; + const dummyToolCallId = null != (_o = null == (_n = (_m = self1.config).generateId) ? void 0 : _n.call(_m)) ? _o : generateId(); + const approvalRequestId = null != (_p = value1.item.approval_request_id) ? _p : value1.item.id; + approvalRequestIdToDummyToolCallIdFromStream.set(approvalRequestId, dummyToolCallId); + const toolName = `mcp.${value1.item.name}`; + controller.enqueue({ + type: "tool-call", + toolCallId: dummyToolCallId, + toolName, + input: value1.item.arguments, + providerExecuted: true, + dynamic: true + }); + controller.enqueue({ + type: "tool-approval-request", + approvalId: approvalRequestId, + toolCallId: dummyToolCallId + }); + } else if ("local_shell_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = void 0; + controller.enqueue({ + type: "tool-call", + toolCallId: value1.item.call_id, + toolName: toolNameMapping.toCustomToolName("local_shell"), + input: JSON.stringify({ + action: { + type: "exec", + command: value1.item.action.command, + timeoutMs: value1.item.action.timeout_ms, + user: value1.item.action.user, + workingDirectory: value1.item.action.working_directory, + env: value1.item.action.env + } + }), + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id + } + } + }); + } else if ("shell_call" === value1.item.type) { + ongoingToolCalls[value1.output_index] = void 0; + controller.enqueue({ + type: "tool-call", + toolCallId: value1.item.call_id, + toolName: toolNameMapping.toCustomToolName("shell"), + input: JSON.stringify({ + action: { + commands: value1.item.action.commands + } + }), + ...isShellProviderExecuted && { + providerExecuted: true + }, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id + } + } + }); + } else if ("shell_call_output" === value1.item.type) controller.enqueue({ + type: "tool-result", + toolCallId: value1.item.call_id, + toolName: toolNameMapping.toCustomToolName("shell"), + result: { + output: value1.item.output.map((item)=>({ + stdout: item.stdout, + stderr: item.stderr, + outcome: "exit" === item.outcome.type ? { + type: "exit", + exitCode: item.outcome.exit_code + } : { + type: "timeout" + } + })) + } + }); + else if ("reasoning" === value1.item.type) { + const activeReasoningPart = activeReasoning[value1.item.id]; + const summaryPartIndices = Object.entries(activeReasoningPart.summaryParts).filter(([_1, status])=>"active" === status || "can-conclude" === status).map(([summaryIndex])=>summaryIndex); + for (const summaryIndex of summaryPartIndices)controller.enqueue({ + type: "reasoning-end", + id: `${value1.item.id}:${summaryIndex}`, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item.id, + reasoningEncryptedContent: null != (_q = value1.item.encrypted_content) ? _q : null + } + } + }); + delete activeReasoning[value1.item.id]; + } + } else if (isResponseFunctionCallArgumentsDeltaChunk(value1)) { + const toolCall = ongoingToolCalls[value1.output_index]; + if (null != toolCall) controller.enqueue({ + type: "tool-input-delta", + id: toolCall.toolCallId, + delta: value1.delta + }); + } else if (isResponseCustomToolCallInputDeltaChunk(value1)) { + const toolCall = ongoingToolCalls[value1.output_index]; + if (null != toolCall) controller.enqueue({ + type: "tool-input-delta", + id: toolCall.toolCallId, + delta: value1.delta + }); + } else if (isResponseApplyPatchCallOperationDiffDeltaChunk(value1)) { + const toolCall = ongoingToolCalls[value1.output_index]; + if (null == toolCall ? void 0 : toolCall.applyPatch) { + controller.enqueue({ + type: "tool-input-delta", + id: toolCall.toolCallId, + delta: escapeJSONDelta(value1.delta) + }); + toolCall.applyPatch.hasDiff = true; + } + } else if (isResponseApplyPatchCallOperationDiffDoneChunk(value1)) { + const toolCall = ongoingToolCalls[value1.output_index]; + if ((null == toolCall ? void 0 : toolCall.applyPatch) && !toolCall.applyPatch.endEmitted) { + if (!toolCall.applyPatch.hasDiff) { + controller.enqueue({ + type: "tool-input-delta", + id: toolCall.toolCallId, + delta: escapeJSONDelta(value1.diff) + }); + toolCall.applyPatch.hasDiff = true; + } + controller.enqueue({ + type: "tool-input-delta", + id: toolCall.toolCallId, + delta: '"}}' + }); + controller.enqueue({ + type: "tool-input-end", + id: toolCall.toolCallId + }); + toolCall.applyPatch.endEmitted = true; + } + } else if (isResponseImageGenerationCallPartialImageChunk(value1)) controller.enqueue({ + type: "tool-result", + toolCallId: value1.item_id, + toolName: toolNameMapping.toCustomToolName("image_generation"), + result: { + result: value1.partial_image_b64 + }, + preliminary: true + }); + else if (isResponseCodeInterpreterCallCodeDeltaChunk(value1)) { + const toolCall = ongoingToolCalls[value1.output_index]; + if (null != toolCall) controller.enqueue({ + type: "tool-input-delta", + id: toolCall.toolCallId, + delta: escapeJSONDelta(value1.delta) + }); + } else if (isResponseCodeInterpreterCallCodeDoneChunk(value1)) { + const toolCall = ongoingToolCalls[value1.output_index]; + if (null != toolCall) { + controller.enqueue({ + type: "tool-input-delta", + id: toolCall.toolCallId, + delta: '"}' + }); + controller.enqueue({ + type: "tool-input-end", + id: toolCall.toolCallId + }); + controller.enqueue({ + type: "tool-call", + toolCallId: toolCall.toolCallId, + toolName: toolNameMapping.toCustomToolName("code_interpreter"), + input: JSON.stringify({ + code: value1.code, + containerId: toolCall.codeInterpreter.containerId + }), + providerExecuted: true + }); + } + } else if (isResponseCreatedChunk(value1)) { + responseId = value1.response.id; + controller.enqueue({ + type: "response-metadata", + id: value1.response.id, + timestamp: new Date(1e3 * value1.response.created_at), + modelId: value1.response.model + }); + } else if (isTextDeltaChunk(value1)) { + controller.enqueue({ + type: "text-delta", + id: value1.item_id, + delta: value1.delta + }); + if ((null == (_s = null == (_r = options1.providerOptions) ? void 0 : _r[providerOptionsName]) ? void 0 : _s.logprobs) && value1.logprobs) logprobs.push(value1.logprobs); + } else if ("response.reasoning_summary_part.added" === value1.type) { + if (value1.summary_index > 0) { + const activeReasoningPart = activeReasoning[value1.item_id]; + activeReasoningPart.summaryParts[value1.summary_index] = "active"; + for (const summaryIndex of Object.keys(activeReasoningPart.summaryParts))if ("can-conclude" === activeReasoningPart.summaryParts[summaryIndex]) { + controller.enqueue({ + type: "reasoning-end", + id: `${value1.item_id}:${summaryIndex}`, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item_id + } + } + }); + activeReasoningPart.summaryParts[summaryIndex] = "concluded"; + } + controller.enqueue({ + type: "reasoning-start", + id: `${value1.item_id}:${value1.summary_index}`, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item_id, + reasoningEncryptedContent: null != (_u = null == (_t = activeReasoning[value1.item_id]) ? void 0 : _t.encryptedContent) ? _u : null + } + } + }); + } + } else if ("response.reasoning_summary_text.delta" === value1.type) controller.enqueue({ + type: "reasoning-delta", + id: `${value1.item_id}:${value1.summary_index}`, + delta: value1.delta, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item_id + } + } + }); + else if ("response.reasoning_summary_part.done" === value1.type) if (store) { + controller.enqueue({ + type: "reasoning-end", + id: `${value1.item_id}:${value1.summary_index}`, + providerMetadata: { + [providerOptionsName]: { + itemId: value1.item_id + } + } + }); + activeReasoning[value1.item_id].summaryParts[value1.summary_index] = "concluded"; + } else activeReasoning[value1.item_id].summaryParts[value1.summary_index] = "can-conclude"; + else if (isResponseFinishedChunk(value1)) { + finishReason = { + unified: mapOpenAIResponseFinishReason({ + finishReason: null == (_v = value1.response.incomplete_details) ? void 0 : _v.reason, + hasFunctionCall + }), + raw: null != (_x = null == (_w = value1.response.incomplete_details) ? void 0 : _w.reason) ? _x : void 0 + }; + usage = value1.response.usage; + if ("string" == typeof value1.response.service_tier) serviceTier = value1.response.service_tier; + } else if (isResponseFailedChunk(value1)) { + const incompleteReason = null == (_y = value1.response.incomplete_details) ? void 0 : _y.reason; + finishReason = { + unified: incompleteReason ? mapOpenAIResponseFinishReason({ + finishReason: incompleteReason, + hasFunctionCall + }) : "error", + raw: null != incompleteReason ? incompleteReason : "error" + }; + usage = null != (_z = value1.response.usage) ? _z : void 0; + } else if (isResponseAnnotationAddedChunk(value1)) { + ongoingAnnotations.push(value1.annotation); + if ("url_citation" === value1.annotation.type) controller.enqueue({ + type: "source", + sourceType: "url", + id: null != (_C = null == (_B = (_A = self1.config).generateId) ? void 0 : _B.call(_A)) ? _C : generateId(), + url: value1.annotation.url, + title: value1.annotation.title + }); + else if ("file_citation" === value1.annotation.type) controller.enqueue({ + type: "source", + sourceType: "document", + id: null != (_F = null == (_E = (_D = self1.config).generateId) ? void 0 : _E.call(_D)) ? _F : generateId(), + mediaType: "text/plain", + title: value1.annotation.filename, + filename: value1.annotation.filename, + providerMetadata: { + [providerOptionsName]: { + type: value1.annotation.type, + fileId: value1.annotation.file_id, + index: value1.annotation.index + } + } + }); + else if ("container_file_citation" === value1.annotation.type) controller.enqueue({ + type: "source", + sourceType: "document", + id: null != (_I = null == (_H = (_G = self1.config).generateId) ? void 0 : _H.call(_G)) ? _I : generateId(), + mediaType: "text/plain", + title: value1.annotation.filename, + filename: value1.annotation.filename, + providerMetadata: { + [providerOptionsName]: { + type: value1.annotation.type, + fileId: value1.annotation.file_id, + containerId: value1.annotation.container_id + } + } + }); + else if ("file_path" === value1.annotation.type) controller.enqueue({ + type: "source", + sourceType: "document", + id: null != (_L = null == (_K = (_J = self1.config).generateId) ? void 0 : _K.call(_J)) ? _L : generateId(), + mediaType: "application/octet-stream", + title: value1.annotation.file_id, + filename: value1.annotation.file_id, + providerMetadata: { + [providerOptionsName]: { + type: value1.annotation.type, + fileId: value1.annotation.file_id, + index: value1.annotation.index + } + } + }); + } else if (isErrorChunk(value1)) controller.enqueue({ + type: "error", + error: value1 + }); + }, + flush (controller) { + const providerMetadata = { + [providerOptionsName]: { + responseId, + ...logprobs.length > 0 ? { + logprobs + } : {}, + ...void 0 !== serviceTier ? { + serviceTier + } : {} + } + }; + controller.enqueue({ + type: "finish", + finishReason, + usage: convertOpenAIResponsesUsage(usage), + providerMetadata + }); + } + })), + request: { + body + }, + response: { + headers: responseHeaders + } + }; + } + }; + function isTextDeltaChunk(chunk) { + return "response.output_text.delta" === chunk.type; + } + function isResponseOutputItemDoneChunk(chunk) { + return "response.output_item.done" === chunk.type; + } + function isResponseFinishedChunk(chunk) { + return "response.completed" === chunk.type || "response.incomplete" === chunk.type; + } + function isResponseFailedChunk(chunk) { + return "response.failed" === chunk.type; + } + function isResponseCreatedChunk(chunk) { + return "response.created" === chunk.type; + } + function isResponseFunctionCallArgumentsDeltaChunk(chunk) { + return "response.function_call_arguments.delta" === chunk.type; + } + function isResponseCustomToolCallInputDeltaChunk(chunk) { + return "response.custom_tool_call_input.delta" === chunk.type; + } + function isResponseImageGenerationCallPartialImageChunk(chunk) { + return "response.image_generation_call.partial_image" === chunk.type; + } + function isResponseCodeInterpreterCallCodeDeltaChunk(chunk) { + return "response.code_interpreter_call_code.delta" === chunk.type; + } + function isResponseCodeInterpreterCallCodeDoneChunk(chunk) { + return "response.code_interpreter_call_code.done" === chunk.type; + } + function isResponseApplyPatchCallOperationDiffDeltaChunk(chunk) { + return "response.apply_patch_call_operation_diff.delta" === chunk.type; + } + function isResponseApplyPatchCallOperationDiffDoneChunk(chunk) { + return "response.apply_patch_call_operation_diff.done" === chunk.type; + } + function isResponseOutputItemAddedChunk(chunk) { + return "response.output_item.added" === chunk.type; + } + function isResponseAnnotationAddedChunk(chunk) { + return "response.output_text.annotation.added" === chunk.type; + } + function isErrorChunk(chunk) { + return "error" === chunk.type; + } + function mapWebSearchOutput(action) { + var _a; + if (null == action) return {}; + switch(action.type){ + case "search": + return { + action: { + type: "search", + query: null != (_a = action.query) ? _a : void 0 + }, + ...null != action.sources && { + sources: action.sources + } + }; + case "open_page": + return { + action: { + type: "openPage", + url: action.url + } + }; + case "find_in_page": + return { + action: { + type: "findInPage", + url: action.url, + pattern: action.pattern + } + }; + } + } + function escapeJSONDelta(delta) { + return JSON.stringify(delta).slice(1, -1); + } + var openaiSpeechModelOptionsSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + instructions: schemas_string().nullish(), + speed: schemas_number().min(0.25).max(4).default(1).nullish() + }))); + var OpenAISpeechModel = class { + constructor(modelId, config){ + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v3"; + } + get provider() { + return this.config.provider; + } + async getArgs({ text, voice = "alloy", outputFormat = "mp3", speed, instructions, language, providerOptions }) { + const warnings = []; + const openAIOptions = await parseProviderOptions({ + provider: "openai", + providerOptions, + schema: openaiSpeechModelOptionsSchema + }); + const requestBody = { + model: this.modelId, + input: text, + voice, + response_format: "mp3", + speed, + instructions + }; + if (outputFormat) if ([ + "mp3", + "opus", + "aac", + "flac", + "wav", + "pcm" + ].includes(outputFormat)) requestBody.response_format = outputFormat; + else warnings.push({ + type: "unsupported", + feature: "outputFormat", + details: `Unsupported output format: ${outputFormat}. Using mp3 instead.` + }); + if (openAIOptions) { + const speechModelOptions = {}; + for(const key in speechModelOptions){ + const value1 = speechModelOptions[key]; + if (void 0 !== value1) requestBody[key] = value1; + } + } + if (language) warnings.push({ + type: "unsupported", + feature: "language", + details: `OpenAI speech models do not support language selection. Language parameter "${language}" was ignored.` + }); + return { + requestBody, + warnings + }; + } + async doGenerate(options1) { + var _a, _b, _c; + const currentDate = null != (_c = null == (_b = null == (_a = this.config._internal) ? void 0 : _a.currentDate) ? void 0 : _b.call(_a)) ? _c : /* @__PURE__ */ new Date(); + const { requestBody, warnings } = await this.getArgs(options1); + const { value: audio, responseHeaders, rawValue: rawResponse } = await postJsonToApi({ + url: this.config.url({ + path: "/audio/speech", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options1.headers), + body: requestBody, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createBinaryResponseHandler(), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + return { + audio, + warnings, + request: { + body: JSON.stringify(requestBody) + }, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders, + body: rawResponse + } + }; + } + }; + var openaiTranscriptionResponseSchema = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + text: schemas_string(), + language: schemas_string().nullish(), + duration: schemas_number().nullish(), + words: schemas_array(schemas_object({ + word: schemas_string(), + start: schemas_number(), + end: schemas_number() + })).nullish(), + segments: schemas_array(schemas_object({ + id: schemas_number(), + seek: schemas_number(), + start: schemas_number(), + end: schemas_number(), + text: schemas_string(), + tokens: schemas_array(schemas_number()), + temperature: schemas_number(), + avg_logprob: schemas_number(), + compression_ratio: schemas_number(), + no_speech_prob: schemas_number() + })).nullish() + }))); + var openAITranscriptionModelOptions = dist_lazySchema(()=>dist_zodSchema(schemas_object({ + include: schemas_array(schemas_string()).optional(), + language: schemas_string().optional(), + prompt: schemas_string().optional(), + temperature: schemas_number().min(0).max(1).default(0).optional(), + timestampGranularities: schemas_array(schemas_enum([ + "word", + "segment" + ])).default([ + "segment" + ]).optional() + }))); + var languageMap = { + afrikaans: "af", + arabic: "ar", + armenian: "hy", + azerbaijani: "az", + belarusian: "be", + bosnian: "bs", + bulgarian: "bg", + catalan: "ca", + chinese: "zh", + croatian: "hr", + czech: "cs", + danish: "da", + dutch: "nl", + english: "en", + estonian: "et", + finnish: "fi", + french: "fr", + galician: "gl", + german: "de", + greek: "el", + hebrew: "he", + hindi: "hi", + hungarian: "hu", + icelandic: "is", + indonesian: "id", + italian: "it", + japanese: "ja", + kannada: "kn", + kazakh: "kk", + korean: "ko", + latvian: "lv", + lithuanian: "lt", + macedonian: "mk", + malay: "ms", + marathi: "mr", + maori: "mi", + nepali: "ne", + norwegian: "no", + persian: "fa", + polish: "pl", + portuguese: "pt", + romanian: "ro", + russian: "ru", + serbian: "sr", + slovak: "sk", + slovenian: "sl", + spanish: "es", + swahili: "sw", + swedish: "sv", + tagalog: "tl", + tamil: "ta", + thai: "th", + turkish: "tr", + ukrainian: "uk", + urdu: "ur", + vietnamese: "vi", + welsh: "cy" + }; + var OpenAITranscriptionModel = class { + constructor(modelId, config){ + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v3"; + } + get provider() { + return this.config.provider; + } + async getArgs({ audio, mediaType, providerOptions }) { + const warnings = []; + const openAIOptions = await parseProviderOptions({ + provider: "openai", + providerOptions, + schema: openAITranscriptionModelOptions + }); + const formData = new FormData(); + const blob = audio instanceof Uint8Array ? new Blob([ + audio + ]) : new Blob([ + convertBase64ToUint8Array(audio) + ]); + formData.append("model", this.modelId); + const fileExtension = mediaTypeToExtension(mediaType); + formData.append("file", new File([ + blob + ], "audio", { + type: mediaType + }), `audio.${fileExtension}`); + if (openAIOptions) { + const transcriptionModelOptions = { + include: openAIOptions.include, + language: openAIOptions.language, + prompt: openAIOptions.prompt, + response_format: [ + "gpt-4o-transcribe", + "gpt-4o-mini-transcribe" + ].includes(this.modelId) ? "json" : "verbose_json", + temperature: openAIOptions.temperature, + timestamp_granularities: openAIOptions.timestampGranularities + }; + for (const [key, value1] of Object.entries(transcriptionModelOptions))if (null != value1) if (Array.isArray(value1)) for (const item of value1)formData.append(`${key}[]`, String(item)); + else formData.append(key, String(value1)); + } + return { + formData, + warnings + }; + } + async doGenerate(options1) { + var _a, _b, _c, _d, _e, _f, _g, _h; + const currentDate = null != (_c = null == (_b = null == (_a = this.config._internal) ? void 0 : _a.currentDate) ? void 0 : _b.call(_a)) ? _c : /* @__PURE__ */ new Date(); + const { formData, warnings } = await this.getArgs(options1); + const { value: response, responseHeaders, rawValue: rawResponse } = await postFormDataToApi({ + url: this.config.url({ + path: "/audio/transcriptions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options1.headers), + formData, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(openaiTranscriptionResponseSchema), + abortSignal: options1.abortSignal, + fetch: this.config.fetch + }); + const language = null != response.language && response.language in languageMap ? languageMap[response.language] : void 0; + return { + text: response.text, + segments: null != (_g = null != (_f = null == (_d = response.segments) ? void 0 : _d.map((segment)=>({ + text: segment.text, + startSecond: segment.start, + endSecond: segment.end + }))) ? _f : null == (_e = response.words) ? void 0 : _e.map((word)=>({ + text: word.word, + startSecond: word.start, + endSecond: word.end + }))) ? _g : [], + language, + durationInSeconds: null != (_h = response.duration) ? _h : void 0, + warnings, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders, + body: rawResponse + } + }; + } + }; + var openai_dist_VERSION = "3.0.52"; + function createOpenAI(options1 = {}) { + var _a, _b; + const baseURL = null != (_a = withoutTrailingSlash(loadOptionalSetting({ + settingValue: options1.baseURL, + environmentVariableName: "OPENAI_BASE_URL" + }))) ? _a : "https://api.openai.com/v1"; + const providerName = null != (_b = options1.name) ? _b : "openai"; + const getHeaders = ()=>withUserAgentSuffix({ + Authorization: `Bearer ${loadApiKey({ + apiKey: options1.apiKey, + environmentVariableName: "OPENAI_API_KEY", + description: "OpenAI" + })}`, + "OpenAI-Organization": options1.organization, + "OpenAI-Project": options1.project, + ...options1.headers + }, `ai-sdk/openai/${openai_dist_VERSION}`); + const createChatModel = (modelId)=>new OpenAIChatLanguageModel(modelId, { + provider: `${providerName}.chat`, + url: ({ path })=>`${baseURL}${path}`, + headers: getHeaders, + fetch: options1.fetch + }); + const createCompletionModel = (modelId)=>new OpenAICompletionLanguageModel(modelId, { + provider: `${providerName}.completion`, + url: ({ path })=>`${baseURL}${path}`, + headers: getHeaders, + fetch: options1.fetch + }); + const createEmbeddingModel = (modelId)=>new OpenAIEmbeddingModel(modelId, { + provider: `${providerName}.embedding`, + url: ({ path })=>`${baseURL}${path}`, + headers: getHeaders, + fetch: options1.fetch + }); + const createImageModel = (modelId)=>new OpenAIImageModel(modelId, { + provider: `${providerName}.image`, + url: ({ path })=>`${baseURL}${path}`, + headers: getHeaders, + fetch: options1.fetch + }); + const createTranscriptionModel = (modelId)=>new OpenAITranscriptionModel(modelId, { + provider: `${providerName}.transcription`, + url: ({ path })=>`${baseURL}${path}`, + headers: getHeaders, + fetch: options1.fetch + }); + const createSpeechModel = (modelId)=>new OpenAISpeechModel(modelId, { + provider: `${providerName}.speech`, + url: ({ path })=>`${baseURL}${path}`, + headers: getHeaders, + fetch: options1.fetch + }); + const createLanguageModel = (modelId)=>{ + if (new.target) throw new Error("The OpenAI model function cannot be called with the new keyword."); + return createResponsesModel(modelId); + }; + const createResponsesModel = (modelId)=>new OpenAIResponsesLanguageModel(modelId, { + provider: `${providerName}.responses`, + url: ({ path })=>`${baseURL}${path}`, + headers: getHeaders, + fetch: options1.fetch, + fileIdPrefixes: [ + "file-" + ] + }); + const provider = function(modelId) { + return createLanguageModel(modelId); + }; + provider.specificationVersion = "v3"; + provider.languageModel = createLanguageModel; + provider.chat = createChatModel; + provider.completion = createCompletionModel; + provider.responses = createResponsesModel; + provider.embedding = createEmbeddingModel; + provider.embeddingModel = createEmbeddingModel; + provider.textEmbedding = createEmbeddingModel; + provider.textEmbeddingModel = createEmbeddingModel; + provider.image = createImageModel; + provider.imageModel = createImageModel; + provider.transcription = createTranscriptionModel; + provider.transcriptionModel = createTranscriptionModel; + provider.speech = createSpeechModel; + provider.speechModel = createSpeechModel; + provider.tools = openaiTools; + return provider; + } + createOpenAI(); + const MAX_CHARS = 50000; + function buildPrompt(diffData) { + let diffStr = JSON.stringify(diffData, null, 2); + if (diffStr.length > MAX_CHARS) diffStr = diffStr.substring(0, MAX_CHARS) + '\n... (truncated due to size)'; + return `You are a senior frontend performance engineer. Analyze the Rsdoctor bundle-diff JSON below (baseline → current) and produce a concise GitHub PR comment in Markdown. + +## Output format + +### šŸ“Š Size Changes + +| Asset / Chunk | Baseline | Current | Ī” Size | Ī” % | Initial? | +|---|---|---|---|---|---| + +(Only list entries with **>5 % or >10 KB** increase. If none, write "No significant regressions detected šŸŽ‰".) + +### šŸ” Root Cause Analysis +- Bullet points: which modules / dependencies drove each regression. + +### āš ļø Risk Assessment +Overall severity: **Low / Medium / High** +- One-sentence justification focusing on initial-chunk impact and total size delta. + +### šŸ’” Optimization Suggestions +- Numbered, actionable steps (e.g. code-split, tree-shake, replace heavy deps). + +## Priority rules +1. Initial / entry chunks > async chunks > static assets. +2. Newly added large modules or duplicate dependencies deserve explicit callout. +3. If total bundle size *decreased*, highlight the wins instead. + +## Constraints +- Be concise — aim for <400 words. +- Use exact numbers from the data; do not fabricate figures. +- If the diff data is empty or shows no meaningful change, state that clearly and skip the table. + +Bundle diff data: +\`\`\`json +${diffStr} +\`\`\``; + } + function detectProvider(model) { + const m = model.toLowerCase(); + if (m.startsWith('claude')) return 'anthropic'; + if (m.startsWith('gemini')) return 'google'; + if (m.startsWith('deepseek')) return 'deepseek'; + if (m.startsWith('qwen')) return 'qwen'; + return 'openai'; + } + function createModel(provider, model, token) { + switch(provider){ + case 'anthropic': + { + const anthropic = createAnthropic({ + apiKey: token + }); + return anthropic(model); + } + case 'google': + { + const google = createGoogleGenerativeAI({ + apiKey: token + }); + return google(model); + } + case 'deepseek': + { + const deepseek = createDeepSeek({ + apiKey: token + }); + return deepseek(model); + } + case 'qwen': + { + const qwen = createOpenAI({ + apiKey: token, + baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1' + }); + return qwen(model); + } + default: + { + const openai = createOpenAI({ + apiKey: token + }); + return openai(model); + } + } + } + async function analyzeWithAI(diffJsonPath, token, model = 'claude-3-5-haiku-latest') { + if (!token) { + console.log('ā„¹ļø No AI token provided, skipping AI analysis'); + return null; + } + if (!external_fs_.existsSync(diffJsonPath)) { + console.log(`āš ļø Bundle diff JSON not found at ${diffJsonPath}, skipping AI analysis`); + return null; + } + try { + const diffData = JSON.parse(external_fs_.readFileSync(diffJsonPath, 'utf8')); + const prompt = buildPrompt(diffData); + const provider = detectProvider(model); + console.log(`šŸ¤– Running AI analysis with ${provider} (${model})...`); + const llm = createModel(provider, model, token); + const { text: analysis } = await generateText({ + model: llm, + maxOutputTokens: 2048, + prompt + }); + console.log('āœ… AI analysis completed'); + return { + analysis, + provider, + model + }; + } catch (error) { + console.warn(`āš ļø AI analysis failed: ${error}`); + return null; + } + } + var external_util_ = __webpack_require__("util"); + var fast_glob_out = __webpack_require__("./node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/index.js"); + var out_default = /*#__PURE__*/ __webpack_require__.n(fast_glob_out); + const execFileAsync = (0, external_util_.promisify)(external_child_process_.execFile); + function isPullRequestEvent() { + const { context } = __webpack_require__("./node_modules/.pnpm/@actions+github@4.0.0/node_modules/@actions/github/lib/github.js"); + const isPR = 'pull_request' === context.eventName; + if (isPR) { + const prAction = context.payload.action; + const prMerged = context.payload.pull_request?.merged; + const prNumber = context.payload.pull_request?.number; + const baseRef = context.payload.pull_request?.base?.ref; + const headRef = context.payload.pull_request?.head?.ref; + if ('closed' === prAction) { + if (true === prMerged) console.log(`ā„¹ļø PR is closed and merged - upload will happen on push event`); + else console.log(`ā„¹ļø PR is closed but not merged - skipping processing`); + return false; + } + console.log(`šŸ“„ Detected pull request event`); + console.log(` Action: ${prAction}`); + console.log(` PR #${prNumber}: ${headRef} -> ${baseRef}`); + console.log(` Merged: ${prMerged}`); + console.log(" This is a PR review/update event - comparing with baseline (no upload)"); + } + return isPR; + } + function isPushEvent() { + const { context } = __webpack_require__("./node_modules/.pnpm/@actions+github@4.0.0/node_modules/@actions/github/lib/github.js"); + const isPush = 'push' === context.eventName; + if (isPush) { + const ref = context.ref; + const targetBranch = (0, core.getInput)('target_branch') || 'main'; + const targetBranchRef = `refs/heads/${targetBranch}`; + if (ref === targetBranchRef) { + console.log(`šŸ”„ Detected push event to ${targetBranch} branch`); + console.log(" This may be a merge commit - will upload artifacts"); + return true; + } + console.log(`ā„¹ļø Push event detected but not to target branch (${targetBranch})`); + console.log(` Current ref: ${ref}`); + } + return false; + } + function isWorkflowDispatchEvent() { + const { context } = __webpack_require__("./node_modules/.pnpm/@actions+github@4.0.0/node_modules/@actions/github/lib/github.js"); + const isDispatch = 'workflow_dispatch' === context.eventName; + if (isDispatch) { + console.log(`šŸ”§ Detected workflow_dispatch event`); + console.log(" This is a manually triggered workflow"); + return true; + } + return false; + } + function runRsdoctorViaNode(requirePath, args = []) { + const nodeExec = process.execPath; + console.log('process.execPath =', nodeExec); + console.log('Running:', nodeExec, requirePath, args.join(' ')); + const r = (0, external_child_process_.spawnSync)(nodeExec, [ + requirePath, + ...args + ], { + stdio: 'inherit' + }); + if (r.error) throw r.error; + if (0 !== r.status) throw new Error(`rsdoctor exited with code ${r.status}`); + } + function extractProjectName(filePath) { + const relativePath = external_path_default().relative(process.cwd(), filePath); + const pathParts = relativePath.split(external_path_default().sep); + const buildOutputDirs = [ + 'dist', + '.rsdoctor', + 'output', + '.next', + 'public' + ]; + const monorepoPatterns = [ + 'packages', + 'apps', + 'projects', + 'libs', + 'modules', + 'examples' + ]; + const patternIndex = pathParts.findIndex((part)=>monorepoPatterns.includes(part)); + if (patternIndex >= 0 && patternIndex + 1 < pathParts.length) { + let packageName = null; + let packageNameIndex = -1; + for(let i = patternIndex + 1; i < pathParts.length; i++)if (!buildOutputDirs.includes(pathParts[i])) { + packageName = pathParts[i]; + packageNameIndex = i; + break; + } + if (packageName) { + for(let i = pathParts.length - 2; i > packageNameIndex; i--){ + const part = pathParts[i]; + if (!buildOutputDirs.includes(part)) return `${packageName}/${part}`; + } + return packageName; + } + } + for(let i = pathParts.length - 2; i >= 0; i--){ + const part = pathParts[i]; + if (!buildOutputDirs.includes(part)) return part; + } + return pathParts[0] || 'root'; + } + async function processSingleFile(fullPath, currentCommitHash, targetCommitHash, baselineUsedFallback, baselineLatestCommitHash, aiToken, aiModel) { + const fileName = external_path_default().basename(fullPath); + const relativePath = external_path_default().relative(process.cwd(), fullPath); + const pathParts = relativePath.split(external_path_default().sep); + const fileNameWithoutExt = external_path_default().parse(fileName).name; + const fileExt = external_path_default().parse(fileName).ext; + const projectName = extractProjectName(fullPath); + console.log(`\nšŸ“¦ Processing project: ${projectName}`); + console.log(` File: ${relativePath}`); + const report = { + projectName, + filePath: relativePath, + current: null, + baseline: null + }; + const currentBundleAnalysis = parseRsdoctorData(fullPath); + if (!currentBundleAnalysis) { + console.warn(`āš ļø Failed to parse rsdoctor data from ${fullPath}, skipping...`); + return report; + } + report.current = currentBundleAnalysis; + let baselineJsonPath = null; + let baselinePRs = []; + if (targetCommitHash) try { + console.log(`šŸ“„ Attempting to download baseline for ${projectName}...`); + const downloadResult = await downloadArtifactByCommitHash(targetCommitHash, fileName, fullPath); + baselineJsonPath = external_path_default().join(downloadResult.downloadPath, fileName); + console.log(`šŸ“ Downloaded baseline file path: ${baselineJsonPath}`); + const baselineBundleAnalysis = parseRsdoctorData(baselineJsonPath); + if (baselineBundleAnalysis) { + report.baseline = baselineBundleAnalysis; + report.baselineCommitHash = targetCommitHash; + report.baselineUsedFallback = baselineUsedFallback; + report.baselineLatestCommitHash = baselineLatestCommitHash; + try { + const githubService = new GitHubService(); + baselinePRs = await githubService.findPRsByCommit(targetCommitHash); + if (baselinePRs.length > 0) { + report.baselinePRs = baselinePRs; + console.log(`šŸ“Ž Found ${baselinePRs.length} PR(s) associated with baseline commit ${targetCommitHash}`); + } + } catch (prError) { + console.log(`ā„¹ļø Could not find PRs for baseline commit: ${prError}`); + } + console.log(`āœ… Successfully downloaded and parsed baseline for ${projectName}`); + } + } catch (downloadError) { + console.log(`āŒ Failed to download baseline for ${projectName}: ${downloadError}`); + console.log(`ā„¹ļø No baseline data found for ${projectName} - skipping bundle diff for this project`); + baselineJsonPath = null; + } + if (report.baseline && baselineJsonPath) try { + const tempOutDir = process.cwd(); + pathParts.join('-'); + console.log(`šŸ” Looking for target artifact: ${pathParts.join('-')}-${fileNameWithoutExt}-${targetCommitHash}${fileExt}`); + try { + const cliEntry = require.resolve('@rsdoctor/cli', { + paths: [ + process.cwd() + ] + }); + const binCliEntry = external_path_default().join(external_path_default().dirname(external_path_default().dirname(cliEntry)), 'bin', 'rsdoctor'); + console.log(`šŸ” Found rsdoctor CLI at: ${binCliEntry}`); + runRsdoctorViaNode(binCliEntry, [ + 'bundle-diff', + '--html', + `--baseline=${baselineJsonPath}`, + `--current=${fullPath}` + ]); + } catch (e) { + console.log(`āš ļø rsdoctor CLI not found in node_modules: ${e}`); + try { + const shellCmd = `npx @rsdoctor/cli bundle-diff --html --baseline="${baselineJsonPath}" --current="${fullPath}"`; + console.log(`šŸ› ļø Running rsdoctor via npx: ${shellCmd}`); + await execFileAsync('sh', [ + '-c', + shellCmd + ], { + cwd: tempOutDir + }); + } catch (npxError) { + console.log(`āš ļø npx approach also failed: ${npxError}`); + } + } + const safeProjectName = projectName.replace(/\//g, '-'); + const diffHtmlPath = external_path_default().join(tempOutDir, `rsdoctor-diff-${safeProjectName}.html`); + const defaultDiffPath = external_path_default().join(tempOutDir, 'rsdoctor-diff.html'); + if (external_fs_.existsSync(defaultDiffPath)) try { + await external_fs_.promises.rename(defaultDiffPath, diffHtmlPath); + } catch (e) { + report.diffHtmlPath = defaultDiffPath; + } + if (!report.diffHtmlPath) report.diffHtmlPath = external_fs_.existsSync(diffHtmlPath) ? diffHtmlPath : defaultDiffPath; + if (external_fs_.existsSync(report.diffHtmlPath)) try { + const uploadRes = await uploadArtifact(report.diffHtmlPath, currentCommitHash); + if ('number' == typeof uploadRes.id) { + report.diffHtmlArtifactId = uploadRes.id; + console.log(`āœ… Uploaded bundle diff HTML for ${projectName}, artifact id: ${uploadRes.id}`); + } + } catch (e) { + console.warn(`āš ļø Failed to upload diff html for ${projectName}: ${e}`); + } + if (aiToken) try { + const diffJsonPath = external_path_default().join(tempOutDir, `rsdoctor-diff-${projectName}.json`); + const defaultDiffJsonPath = external_path_default().join(tempOutDir, 'rsdoctor-diff.json'); + try { + const cliEntry = require.resolve('@rsdoctor/cli', { + paths: [ + process.cwd() + ] + }); + const binCliEntry = external_path_default().join(external_path_default().dirname(external_path_default().dirname(cliEntry)), 'bin', 'rsdoctor'); + runRsdoctorViaNode(binCliEntry, [ + 'bundle-diff', + '--json', + `--baseline=${baselineJsonPath}`, + `--current=${fullPath}` + ]); + } catch (e) { + console.log(`āš ļø rsdoctor CLI (json) not found in node_modules: ${e}`); + try { + const shellCmd = `npx @rsdoctor/cli bundle-diff --json --baseline="${baselineJsonPath}" --current="${fullPath}"`; + console.log(`šŸ› ļø Running rsdoctor --json via npx: ${shellCmd}`); + await execFileAsync('sh', [ + '-c', + shellCmd + ], { + cwd: tempOutDir + }); + } catch (npxError) { + console.log(`āš ļø npx approach (json) also failed: ${npxError}`); + } + } + if (external_fs_.existsSync(defaultDiffJsonPath) && !external_fs_.existsSync(diffJsonPath)) await external_fs_.promises.rename(defaultDiffJsonPath, diffJsonPath); + const resolvedJsonPath = external_fs_.existsSync(diffJsonPath) ? diffJsonPath : defaultDiffJsonPath; + report.aiAnalysis = await analyzeWithAI(resolvedJsonPath, aiToken, aiModel); + } catch (e) { + console.warn(`āš ļø Failed to generate JSON diff for AI analysis: ${e}`); + } + } catch (e) { + console.warn(`āš ļø rsdoctor bundle-diff failed for ${projectName}: ${e}`); + } + return report; + } + (async ()=>{ + try { + const githubService = new GitHubService(); + const filePathPattern = (0, core.getInput)('file_path'); + if (!filePathPattern) throw new Error('file_path is required'); + const matchedFiles = await out_default()(filePathPattern, { + cwd: process.cwd(), + absolute: true, + onlyFiles: true + }); + if (0 === matchedFiles.length) throw new Error(`No files found matching pattern: ${filePathPattern}`); + console.log(`šŸ“ Found ${matchedFiles.length} file(s) matching pattern: ${filePathPattern}`); + matchedFiles.forEach((file, index)=>{ + console.log(` ${index + 1}. ${file}`); + }); + const currentCommitHash = githubService.getCurrentCommitHash(); + console.log(`Current commit hash: ${currentCommitHash}`); + const aiToken = process.env.AI_TOKEN || ''; + const aiModel = (0, core.getInput)('ai_model') || 'claude-3-5-haiku-latest'; + if (aiToken) console.log(`šŸ¤– AI analysis enabled (model: ${aiModel})`); + let targetCommitHash = null; + let baselineUsedFallback = false; + let baselineLatestCommitHash; + const isPush = isPushEvent(); + const isPR = isPullRequestEvent(); + const isDispatch = isWorkflowDispatchEvent(); + if (isPR || isDispatch) try { + console.log('šŸ” Getting target branch commit hash...'); + const commitInfo = await githubService.getTargetBranchLatestCommit(); + targetCommitHash = commitInfo.commitHash; + baselineUsedFallback = commitInfo.usedFallbackCommit; + baselineLatestCommitHash = commitInfo.latestCommitHash; + console.log(`āœ… Target branch commit hash: ${targetCommitHash}`); + if (baselineUsedFallback && baselineLatestCommitHash) console.log(`āš ļø Using fallback commit: ${targetCommitHash} (latest: ${baselineLatestCommitHash})`); + } catch (error) { + console.error(`āŒ Failed to get target branch commit: ${error}`); + console.log('šŸ“ No baseline data available for comparison'); + } + const projectReports = []; + if (isPush) { + console.log('šŸ”„ Detected push event to target branch - uploading artifacts'); + for (const fullPath of matchedFiles){ + const uploadResponse = await uploadArtifact(fullPath, currentCommitHash); + if ('number' != typeof uploadResponse.id) console.warn(`āš ļø Artifact upload failed for ${fullPath}`); + else console.log(`āœ… Successfully uploaded artifact with ID: ${uploadResponse.id}`); + const currentBundleAnalysis = parseRsdoctorData(fullPath); + if (currentBundleAnalysis) { + const projectName = extractProjectName(fullPath); + const relativePath = external_path_default().relative(process.cwd(), fullPath); + projectReports.push({ + projectName, + filePath: relativePath, + current: currentBundleAnalysis, + baseline: null + }); + } else { + const currentSizeData = loadSizeData(fullPath); + if (currentSizeData) await generateSizeReport(currentSizeData); + } + } + if (projectReports.length > 0) if (1 === projectReports.length) { + const report = projectReports[0]; + if (report.current) await generateBundleAnalysisReport(report.current, void 0, true, null, void 0); + } else { + await core.summary.addHeading('šŸ“¦ Monorepo Bundle Analysis', 2); + for (const report of projectReports)if (report.current) { + await core.summary.addHeading(`šŸ“ ${report.projectName}`, 3); + await core.summary.addRaw(`**Path:** \`${report.filePath}\``); + await generateBundleAnalysisReport(report.current, void 0, false, null, void 0); + } + await core.summary.write(); + } + } else if (isDispatch || isPR) { + if (isDispatch) console.log('šŸ”§ Processing workflow_dispatch event - uploading artifacts and comparing with baseline'); + else console.log('šŸ“„ Detected pull request event - processing files'); + for (const fullPath of matchedFiles){ + const report = await processSingleFile(fullPath, currentCommitHash, targetCommitHash, baselineUsedFallback, baselineLatestCommitHash, aiToken, aiModel); + projectReports.push(report); + if (isDispatch) { + const uploadResponse = await uploadArtifact(fullPath, currentCommitHash); + if ('number' != typeof uploadResponse.id) console.warn(`āš ļø Artifact upload failed for ${fullPath}`); + else console.log(`āœ… Successfully uploaded artifact with ID: ${uploadResponse.id}`); + } + } + if (projectReports.length > 0) if (1 === projectReports.length) { + const report = projectReports[0]; + if (report.current) { + if (report.baselineUsedFallback && report.baselineLatestCommitHash) await core.summary.addRaw(`> āš ļø **Note:** The latest commit (\`${report.baselineLatestCommitHash}\`) does not have baseline artifacts. Using commit \`${report.baselineCommitHash}\` for baseline comparison instead. If this seems incorrect, please wait a few minutes and try rerunning the workflow.\n\n`); await generateBundleAnalysisReport(report.current, report.baseline || void 0, true, report.baselineCommitHash, report.baselinePRs); } } else { @@ -96951,6 +129095,16 @@ var __webpack_exports__ = {}; } if (reportsWithChanges.length > 1) commentBody += '\n\n'; } + const reportsWithAI = projectReports.filter((r)=>r.aiAnalysis); + if (reportsWithAI.length > 0) { + commentBody += '
\nšŸ¤– AI Degradation Analysis (Click to expand)\n\n'; + for (const report of reportsWithAI)if (report.aiAnalysis) { + if (reportsWithAI.length > 1) commentBody += `#### šŸ“ ${report.projectName}\n\n`; + commentBody += report.aiAnalysis.analysis + '\n\n'; + commentBody += `Analysis by ${report.aiAnalysis.model}\n\n`; + } + commentBody += '
\n\n'; + } commentBody += '*Generated by [Rsdoctor GitHub Action](https://rsdoctor.rs/guide/start/action)*'; try { await githubService.updateOrCreateComment(context.payload.pull_request.number, commentBody); diff --git a/package.json b/package.json index 30a46d5..c62e040 100644 --- a/package.json +++ b/package.json @@ -36,12 +36,17 @@ "access": "public" }, "devDependencies": { + "@ai-sdk/anthropic": "^3.0.69", + "@ai-sdk/deepseek": "^2.0.29", + "@ai-sdk/google": "^3.0.63", + "@ai-sdk/openai": "^3.0.52", + "ai": "^6.0.159", "@actions/artifact": "^2.3.2", "@actions/core": "^1.2.6", "@actions/github": "^4.0.0", "@playwright/test": "^1.42.1", - "@rsdoctor/cli": "1.3.3-beta.2", - "@rsdoctor/client": "1.3.3-beta.2", + "@rsdoctor/cli": "1.5.8", + "@rsdoctor/client": "1.5.8", "@rslib/core": "^0.16.0", "@rstest/core": "^0.5.4", "@types/node": "^24.5.2", @@ -53,6 +58,7 @@ "yauzl": "^3.2.0" }, "overrides": { - "@rsdoctor/client": "1.3.3-beta.2" - } + "@rsdoctor/client": "1.5.8" + }, + "packageManager": "pnpm@9.15.9+sha512.68046141893c66fad01c079231128e9afb89ef87e2691d69e4d40eee228988295fd4682181bae55b58418c3a253bde65a505ec7c5f9403ece5cc3cd37dcf2531" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 932cd5a..d2231ab 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,15 +17,27 @@ importers: '@actions/github': specifier: ^4.0.0 version: 4.0.0 + '@ai-sdk/anthropic': + specifier: ^3.0.69 + version: 3.0.69(zod@4.3.6) + '@ai-sdk/deepseek': + specifier: ^2.0.29 + version: 2.0.29(zod@4.3.6) + '@ai-sdk/google': + specifier: ^3.0.63 + version: 3.0.63(zod@4.3.6) + '@ai-sdk/openai': + specifier: ^3.0.52 + version: 3.0.52(zod@4.3.6) '@playwright/test': specifier: ^1.42.1 version: 1.56.1 '@rsdoctor/cli': - specifier: 1.3.3-beta.2 - version: 1.3.3-beta.2(@rsbuild/core@1.6.0-beta.0)(@rsdoctor/client@1.3.3-beta.2)(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + specifier: 1.5.8 + version: 1.5.8(@rsdoctor/client@1.5.8)(@rspack/core@1.5.8(@swc/helpers@0.5.17)) '@rsdoctor/client': - specifier: 1.3.3-beta.2 - version: 1.3.3-beta.2 + specifier: 1.5.8 + version: 1.5.8 '@rslib/core': specifier: ^0.16.0 version: 0.16.0(typescript@5.4.5) @@ -41,6 +53,9 @@ importers: '@types/yauzl': specifier: ^2.10.3 version: 2.10.3 + ai: + specifier: ^6.0.159 + version: 6.0.159(zod@4.3.6) fast-glob: specifier: ^3.3.3 version: 3.3.3 @@ -136,6 +151,46 @@ packages: '@actions/io@1.1.3': resolution: {integrity: sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q==} + '@ai-sdk/anthropic@3.0.69': + resolution: {integrity: sha512-LshR7X3pFugY0o41G2VKTmg1XoGpSl7uoYWfzk6zjVZLhCfeFiwgpOga+eTV4XY1VVpZwKVqRnkDbIL7K2eH5g==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + + '@ai-sdk/deepseek@2.0.29': + resolution: {integrity: sha512-cn4+xV0menm/4JKEDElnVGiUilHvi6AD4ZK/sY7DXP/Wb7Yb3Vr86NyYM6mGBE/Shk3mWHoHbzggVnF5x0uMEA==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + + '@ai-sdk/gateway@3.0.96': + resolution: {integrity: sha512-BDiVEMUVHGpngReeigzLyJobG0TvzYbNGzdHI8JYBZHrjOX4aL6qwIls7z3p7V4TuXVWUCbG8TSWEe7ksX4Vhw==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + + '@ai-sdk/google@3.0.63': + resolution: {integrity: sha512-RfOZWVMYSPu2sPRfGajrauWAZ9BSaRopSn+AszkKWQ1MFj8nhaXvCqRHB5pBQUaHTfZKagvOmMpNfa/s3gPLgQ==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + + '@ai-sdk/openai@3.0.52': + resolution: {integrity: sha512-4Rr8NCGmfWTz6DCUvixn9UmyZcMatiHn0zWoMzI3JCUe9R1P/vsPOpCBALKoSzVYOjyJnhtnVIbfUKujcS39uw==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + + '@ai-sdk/provider-utils@4.0.23': + resolution: {integrity: sha512-z8GlDaCmRSDlqkMF2f4/RFgWxdarvIbyuk+m6WXT1LYgsnGiXRJGTD2Z1+SDl3LqtFuRtGX1aghYvQLoHL/9pg==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + + '@ai-sdk/provider@3.0.8': + resolution: {integrity: sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==} + engines: {node: '>=18'} + '@ast-grep/napi-darwin-arm64@0.37.0': resolution: {integrity: sha512-QAiIiaAbLvMEg/yBbyKn+p1gX2/FuaC0SMf7D7capm/oG4xGMzdeaQIcSosF4TCxxV+hIH4Bz9e4/u7w6Bnk3Q==} engines: {node: '>= 10'} @@ -385,6 +440,10 @@ packages: '@octokit/types@6.41.0': resolution: {integrity: sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==} + '@opentelemetry/api@1.9.0': + resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==} + engines: {node: '>=8.0.0'} + '@pkgjs/parseargs@0.11.0': resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} @@ -423,45 +482,31 @@ packages: engines: {node: '>=18.12.0'} hasBin: true - '@rsbuild/plugin-check-syntax@1.4.0': - resolution: {integrity: sha512-Lq3Dg4fcONeSHeCOUNeNr2cRUoZMHG49NHpHWCFc8eB7rELICUA4k/CQtVBVoU8Ahz/4HjmD8C25ilE2PmfXBQ==} - peerDependencies: - '@rsbuild/core': 1.x - peerDependenciesMeta: - '@rsbuild/core': - optional: true - '@rsbuild/plugin-react@1.4.1': resolution: {integrity: sha512-kahvnfRPQTsG0tReR6h0KuVfyjKJfpv/PoU5qW5SDkON7vmbGn8Jx7l3fI+yU3lR/7qDiAO19QnNjkqxPsFT3Q==} peerDependencies: '@rsbuild/core': 1.x - '@rsdoctor/cli@1.3.3-beta.2': - resolution: {integrity: sha512-fR6ZScM1Y4zxztjz6Mavh1oygfXaEqCa4ADPKZeN41uHuQKBNgx+QVhY0RHkbdldzGtpSbrodLKHu/NXs9XWjA==} + '@rsdoctor/cli@1.5.8': + resolution: {integrity: sha512-etTQWo5CIj4zqKEmqscekIE0BcydY8/JQf9MO7yW9HSaDVSA9IyUvfEAlkmW7vNLLpB3w4hHlDBOPurxcGBttA==} hasBin: true peerDependencies: - '@rsdoctor/client': 1.3.3 + '@rsdoctor/client': 1.5.8 '@rsdoctor/client@1.3.1': resolution: {integrity: sha512-BuAowgeQGQ9yRrFmmbnlZ5OM1IS+Qqkmgg2J3YFoQGWmHpoVxzFmKHuxbse0KPIMfoLO6qoexxgEwPQCvV3qiA==} - '@rsdoctor/client@1.3.3': - resolution: {integrity: sha512-ffN3SB97XOy0qngzFuyqdnWvs4wMNLuZR33hedrTfzX0zn0lucF7+zNmUSCW5qK/lpSWi9aSrvD2Zxnep2VffQ==} - - '@rsdoctor/client@1.3.3-beta.2': - resolution: {integrity: sha512-TIahDiTFajjesouAP4D5e8y4uFkjDVJxm2tou+ITotactmbxgt3vtt3UyMrWW9j5ydjE7TzWb6UpwT5DuDXQIA==} + '@rsdoctor/client@1.5.8': + resolution: {integrity: sha512-YOy3BUydv3Lxd0e/QgUVgrF0pTxh30dXaK825NCCSoQFlUv8kHyYvDmsSLWnAoWTbGFAStt3X4NHQzVZR8MIzg==} '@rsdoctor/core@1.3.1': resolution: {integrity: sha512-v7Lc21JMHCNlmXPE2Db7JXDebD8juojW53O/X0xo86/xreDJIj6X2EToswE18g9LDRQ0jHt/JZJB/F7fBxMgaQ==} - '@rsdoctor/core@1.3.3': - resolution: {integrity: sha512-sxyLmPIuYIaZUL/n1INEc5UcktTkPUkkLn96wa2MMgcMjUNES47vW6r9p4xzy2u/UAgVfgzSfdVK39Y92ch+Wg==} - '@rsdoctor/graph@1.3.1': resolution: {integrity: sha512-bV2fhplmC+xkC+BltHHpnCehHyiEvjCvDSffEAszXlIl/gKEuPTbhKwDPTpGp8QIxUbfGbMEpWBRikbQeOEuJg==} - '@rsdoctor/graph@1.3.3': - resolution: {integrity: sha512-KkygJjhi4ysRxNI1zQFLELQWTxgfB3/gwgb7kCF820AFTQd2RvurC5Bd+dHqfoy+qebgUmmPnqTH5Kq0TlVLFw==} + '@rsdoctor/graph@1.5.8': + resolution: {integrity: sha512-B8c/aAIOyuxRO87PuNEx7+d/RrYDDTfZBBLwgtra3PrUpGJHG8n/otRAE8e9Kww4igFdvIga5aqLaVSvp3NkSA==} '@rsdoctor/rspack-plugin@1.3.1': resolution: {integrity: sha512-lePN6mE2YphJhQMsyYQpy7Rcm8SNf14FVuzEWtKOPHerXfSA3OIcBPnN0w8Ycd4eHmjBkd/gbX4OT7+QY+Z8vQ==} @@ -474,8 +519,8 @@ packages: '@rsdoctor/sdk@1.3.1': resolution: {integrity: sha512-L3VjbJjmtb7WnV22bDFU60nS/c9ilGCiMRe6hgItauLwdrRm9sXljBrn4QhKG31LGo/JSCW5JJPRjUF3lyqcsg==} - '@rsdoctor/sdk@1.3.3': - resolution: {integrity: sha512-jknXjrTdiwbBz+qUvokC9kxkz+Ys/OiXZMd2vN1uPOy5x/bh05/Knjpr3oO5uc6ifaQ3T0D7MBqCotuxKg69Zw==} + '@rsdoctor/sdk@1.5.8': + resolution: {integrity: sha512-WJcdMq4u9RfHlykHMpxEzQDRYHXhe3DCwRiRcROFoq+jA9pxutBs2cogSzap2PzyvFa1Yc9/HfSWzPOqW/s6Zw==} '@rsdoctor/types@1.3.1': resolution: {integrity: sha512-q2hEu2eXPl9NzgFinODrJZrfBRIrMRcC2efIDPcIMWEgIQHHGCIPxw9WfDG/uAV+tRSc1KbOsPSmamMFJDV8rw==} @@ -488,8 +533,8 @@ packages: webpack: optional: true - '@rsdoctor/types@1.3.3': - resolution: {integrity: sha512-OYOAw3WRnQoqzoGsvJz4mTQKtuEyyaDGSkEs3mSocU007vojt7bWcm/pUoiBur5qnwzOCKZHO8y23i2pRBQ+uw==} + '@rsdoctor/types@1.5.8': + resolution: {integrity: sha512-JwY1zwVqpz1fCwcwy75nfM7yZ5mJwyFQJsf8GzS002rAFWCdLkVJF8NqXpZVP8Xg/YJxyFkWhvxPl8KozVpWFA==} peerDependencies: '@rspack/core': '*' webpack: 5.x @@ -502,8 +547,8 @@ packages: '@rsdoctor/utils@1.3.1': resolution: {integrity: sha512-o8QowrljKlS+qya/zRfoyiTnZJUvmZ4gUQKWR0rP9eqrZHtohl05vzFpnM4GH3JZQhTV8bMsvKIrD7kOvmbASQ==} - '@rsdoctor/utils@1.3.3': - resolution: {integrity: sha512-bls5Eehr7n5rbNoXNxyvUxgHcLqvTGxdH20+foOU6dQt0U0cAlc4AwltbdpqEDwTxQPkBvVIXSM51HsnS2ojhA==} + '@rsdoctor/utils@1.5.8': + resolution: {integrity: sha512-jQ3W5GEHuWUlkpnilTUUr76ut0eEltvmef531KQOvDToPMPk29ZI8Fa6b4gLwbSURKzsTTJsyDmOjCl1FkH51w==} '@rslib/core@0.16.0': resolution: {integrity: sha512-eN0rRd/KF/IMBA3S93R9UVZijTGO87x+pndf1vOet4vsq9dqzc7Jcue5xcuobtRSnnIHcB8xdW2Kj2x1PCqqdw==} @@ -730,6 +775,9 @@ packages: '@socket.io/component-emitter@3.1.2': resolution: {integrity: sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==} + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@swc/helpers@0.5.17': resolution: {integrity: sha512-5IKx/Y13RsYd+sauPb2x+U/xZikHjolzfuDgTAl/Tdf3Q8rslRvC19NKDLgAJQ6wsqADk10ntlv08nPFw/gO/A==} @@ -768,6 +816,9 @@ packages: '@types/tapable@2.2.7': resolution: {integrity: sha512-D6QzACV9vNX3r8HQQNTOnpG+Bv1rko+yEA82wKs3O9CQ5+XW7HI7TED17/UE7+5dIxyxZIWTxKbsBeF6uKFCwA==} + '@types/tapable@2.3.0': + resolution: {integrity: sha512-oMnbAXeVo+KUnje3hzdORXUbfnzTfqD0H92mLl19NE5hFqH9Q4ktq+xehNSxcNeeLm1COopYwa0zeP6Iz+oIXg==} + '@types/yauzl@2.10.3': resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==} @@ -780,6 +831,10 @@ packages: resolution: {integrity: sha512-SnbaqayTVFEA6/tYumdF0UmybY0KHyKwGPBXnyckFlrrKdhWFrL3a2HIPXHjht5ZOElKGcXfD2D63P36btb+ww==} engines: {node: '>=20.0.0'} + '@vercel/oidc@3.1.0': + resolution: {integrity: sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==} + engines: {node: '>= 20'} + abort-controller@3.0.0: resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==} engines: {node: '>=6.5'} @@ -797,6 +852,10 @@ packages: resolution: {integrity: sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==} engines: {node: '>=0.4.0'} + acorn-walk@8.3.5: + resolution: {integrity: sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==} + engines: {node: '>=0.4.0'} + acorn@8.15.0: resolution: {integrity: sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==} engines: {node: '>=0.4.0'} @@ -806,6 +865,12 @@ packages: resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} engines: {node: '>= 14'} + ai@6.0.159: + resolution: {integrity: sha512-S18ozG7Dkm3Ud1tzOtAK5acczD4vygfml80RkpM9VWMFpvAFwAKSHaGYkATvPQHIE+VpD1tJY9zcTXLZ/zR5cw==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + ansi-regex@5.0.1: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} @@ -866,10 +931,6 @@ packages: resolution: {integrity: sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==} engines: {node: ^4.5.0 || >= 5.9} - baseline-browser-mapping@2.8.18: - resolution: {integrity: sha512-UYmTpOBwgPScZpS4A+YbapwWuBwasxvO/2IOHArSsAhL/+ZdmATBXTex3t+l2hXwLVYK382ibr/nKoY9GKe86w==} - hasBin: true - before-after-hook@2.2.3: resolution: {integrity: sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==} @@ -892,14 +953,6 @@ packages: browserslist-load-config@1.0.1: resolution: {integrity: sha512-orLR5HAoQugQNVUXUwNd+GAAwl3H64KLIwoMFBNW0AbMSqX2Lxs4ZV2/5UoNrVQlQqF9ygychiu7Svr/99bLtg==} - browserslist-to-es-version@1.2.0: - resolution: {integrity: sha512-wZpJM7QUP33yPzWDzMLgTFZzb3WC6f7G13gnJ5p8PlFz3Xm9MUwArRh9jgE0y4/Sqo6CKtsNxyGpVf5zLWgAhg==} - - browserslist@4.26.3: - resolution: {integrity: sha512-lAUU+02RFBuCKQPj/P6NgjlbCnLBMp4UtgTx7vNHd3XSIJF87s9a5rA3aH2yw3GS9DqZAUbOtZdCCiZeVRqt0w==} - engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} - hasBin: true - buffer-crc32@0.2.13: resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==} @@ -921,9 +974,6 @@ packages: resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} engines: {node: '>= 0.4'} - caniuse-lite@1.0.30001751: - resolution: {integrity: sha512-A0QJhug0Ly64Ii3eIqHu5X51ebln3k4yTUkY1j8drqpWHVreg/VLijN48cZ1bYPiqOQuqpkIKnzr/Ul8V+p6Cw==} - chainsaw@0.1.0: resolution: {integrity: sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==} @@ -1023,19 +1073,6 @@ packages: deprecation@2.3.1: resolution: {integrity: sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==} - dom-serializer@2.0.0: - resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==} - - domelementtype@2.3.0: - resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==} - - domhandler@5.0.3: - resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==} - engines: {node: '>= 4'} - - domutils@3.2.2: - resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==} - dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} @@ -1043,9 +1080,6 @@ packages: eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} - electron-to-chromium@1.5.237: - resolution: {integrity: sha512-icUt1NvfhGLar5lSWH3tHNzablaA5js3HVHacQimfP8ViEBOQv+L7DKEuHdbTZ0SKCO1ogTJTIL1Gwk9S6Qvcg==} - emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} @@ -1064,21 +1098,13 @@ packages: resolution: {integrity: sha512-QHTXI/sZQmko1cbDoNAa3mJ5qhWUUNAq3vR0/YiD379fWQrcfuoX1+HW2S0MTt7XmoPLapdaDKUtelUSPic7hQ==} engines: {node: '>=10.13.0'} - entities@4.5.0: - resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} - engines: {node: '>=0.12'} - - entities@6.0.1: - resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} - engines: {node: '>=0.12'} - envinfo@7.14.0: resolution: {integrity: sha512-CO40UI41xDQzhLB1hWyqUKgFhs250pNcGbyGKe1l/e4FSaI/+YE4IMG76GDt0In67WLPACIITC+sOi08x4wIvg==} engines: {node: '>=4'} hasBin: true - envinfo@7.18.0: - resolution: {integrity: sha512-02QGCLRW+Jb8PC270ic02lat+N57iBaWsvHjcJViqp6UVupRB+Vsg7brYPTqEFXvsdTql3KnSczv5ModZFpl8Q==} + envinfo@7.21.0: + resolution: {integrity: sha512-Lw7I8Zp5YKHFCXL7+Dz95g4CcbMEpgvqZNNq3AmlT5XAV6CgAAk6gyAMqn2zjw08K9BHfcNuKrMiCPLByGafow==} engines: {node: '>=4'} hasBin: true @@ -1101,9 +1127,8 @@ packages: resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} engines: {node: '>= 0.4'} - escalade@3.2.0: - resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} - engines: {node: '>=6'} + es-toolkit@1.45.1: + resolution: {integrity: sha512-/jhoOj/Fx+A+IIyDNOvO3TItGmlMKhtX8ISAHKE90c4b/k1tqaqEZ+uUqfpU8DMnW5cgNJv606zS55jGvza0Xw==} event-target-shim@5.0.1: resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==} @@ -1116,6 +1141,10 @@ packages: resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} engines: {node: '>=0.8.x'} + eventsource-parser@3.0.6: + resolution: {integrity: sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==} + engines: {node: '>=18.0.0'} + fast-fifo@1.3.2: resolution: {integrity: sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==} @@ -1176,6 +1205,7 @@ packages: glob@10.4.5: resolution: {integrity: sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me hasBin: true gopd@1.2.0: @@ -1204,9 +1234,6 @@ packages: html-entities@2.6.0: resolution: {integrity: sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==} - htmlparser2@10.0.0: - resolution: {integrity: sha512-TwAZM+zE5Tq3lrEHvOlvwgj1XLWQCtaaibSN11Q+gGBAS7Y1uZSWwXXRe4iF6OXnaq1riyQAPFOBtYc77Mxq0g==} - http-proxy-agent@7.0.2: resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} engines: {node: '>= 14'} @@ -1269,6 +1296,9 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + json-schema@0.4.0: + resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==} + json-stream-stringify@3.0.1: resolution: {integrity: sha512-vuxs3G1ocFDiAQ/SX0okcZbtqXwgj1g71qE9+vrjJ2EkjKQlEFDAcUNRxRU8O+GekV4v5cM2qXP0Wyt/EMDBiQ==} @@ -1281,6 +1311,9 @@ packages: jwt-decode@3.1.2: resolution: {integrity: sha512-UfpWE/VZn0iP50d8cz9NrZLM9lSWhcJ+0Gt/nm4by88UL+J1SiKN8/5dkjMmbEzwL2CAe+67GsegCbIKtbp75A==} + launch-editor@2.13.2: + resolution: {integrity: sha512-4VVDnbOpLXy/s8rdRCSXb+zfMeFR0WlJWpET1iA9CQdlZDfwyLjUuGQzXU4VeOoey6AicSAluWan7Etga6Kcmg==} + lazystream@1.0.1: resolution: {integrity: sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==} engines: {node: '>= 0.6.3'} @@ -1372,9 +1405,6 @@ packages: encoding: optional: true - node-releases@2.0.25: - resolution: {integrity: sha512-4auku8B/vw5psvTiiN9j1dAOsXvMoGqJuKJcR+dTdqiXEK20mMTk1UEo3HS16LeGQsVG6+qKTPM9u/qQ2LqATA==} - normalize-path@3.0.0: resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} engines: {node: '>=0.10.0'} @@ -1496,6 +1526,9 @@ packages: rslog@1.3.0: resolution: {integrity: sha512-93DpwwaiRrLz7fJ5z6Uwb171hHBws1VVsWjU6IruLFX63BicLA44QNu0sfn3guKHnBHZMFSKO8akfx5QhjuegQ==} + rslog@1.3.2: + resolution: {integrity: sha512-1YyYXBvN0a2b1MSIDLwDTqqgjDzRKxUg/S/+KO6EAgbtZW1B3fdLHAMhEEtvk1patJYMqcRvlp3HQwnxj7AdGQ==} + run-parallel@1.2.0: resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} @@ -1524,6 +1557,10 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} + shell-quote@1.8.3: + resolution: {integrity: sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==} + engines: {node: '>= 0.4'} + signal-exit@3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} @@ -1589,6 +1626,10 @@ packages: resolution: {integrity: sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==} engines: {node: '>=6'} + tapable@2.3.2: + resolution: {integrity: sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==} + engines: {node: '>=6'} + tar-stream@3.1.7: resolution: {integrity: sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==} @@ -1652,12 +1693,6 @@ packages: unzip-stream@0.3.4: resolution: {integrity: sha512-PyofABPVv+d7fL7GOpusx7eRT9YETY2X04PhwbSipdj6bMxVCFJrr+nm0Mxqbf9hUiTin/UsnuFWBXlDZFy0Cw==} - update-browserslist-db@1.1.3: - resolution: {integrity: sha512-UxhIZQ+QInVdunkDAaiazvvT/+fXL5Osr0JZlJulepYu6Jd7qJtDZjlur0emRlT71EN3ScPoE7gvsuIKKNavKw==} - hasBin: true - peerDependencies: - browserslist: '>= 4.21.0' - util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} @@ -1710,6 +1745,9 @@ packages: resolution: {integrity: sha512-zK7YHHz4ZXpW89AHXUPbQVGKI7uvkd3hzusTdotCg1UxyaVtg0zFJSTfW/Dq5f7OBBVnq6cZIaC8Ti4hb6dtCA==} engines: {node: '>= 14'} + zod@4.3.6: + resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==} + snapshots: '@actions/artifact@2.3.2': @@ -1770,6 +1808,48 @@ snapshots: '@actions/io@1.1.3': {} + '@ai-sdk/anthropic@3.0.69(zod@4.3.6)': + dependencies: + '@ai-sdk/provider': 3.0.8 + '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) + zod: 4.3.6 + + '@ai-sdk/deepseek@2.0.29(zod@4.3.6)': + dependencies: + '@ai-sdk/provider': 3.0.8 + '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) + zod: 4.3.6 + + '@ai-sdk/gateway@3.0.96(zod@4.3.6)': + dependencies: + '@ai-sdk/provider': 3.0.8 + '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) + '@vercel/oidc': 3.1.0 + zod: 4.3.6 + + '@ai-sdk/google@3.0.63(zod@4.3.6)': + dependencies: + '@ai-sdk/provider': 3.0.8 + '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) + zod: 4.3.6 + + '@ai-sdk/openai@3.0.52(zod@4.3.6)': + dependencies: + '@ai-sdk/provider': 3.0.8 + '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) + zod: 4.3.6 + + '@ai-sdk/provider-utils@4.0.23(zod@4.3.6)': + dependencies: + '@ai-sdk/provider': 3.0.8 + '@standard-schema/spec': 1.1.0 + eventsource-parser: 3.0.6 + zod: 4.3.6 + + '@ai-sdk/provider@3.0.8': + dependencies: + json-schema: 0.4.0 + '@ast-grep/napi-darwin-arm64@0.37.0': optional: true @@ -2128,6 +2208,8 @@ snapshots: dependencies: '@octokit/openapi-types': 12.11.0 + '@opentelemetry/api@1.9.0': {} + '@pkgjs/parseargs@0.11.0': optional: true @@ -2178,16 +2260,6 @@ snapshots: core-js: 3.46.0 jiti: 2.6.1 - '@rsbuild/plugin-check-syntax@1.4.0(@rsbuild/core@1.6.0-beta.0)': - dependencies: - acorn: 8.15.0 - browserslist-to-es-version: 1.2.0 - htmlparser2: 10.0.0 - picocolors: 1.1.1 - source-map: 0.7.6 - optionalDependencies: - '@rsbuild/core': 1.6.0-beta.0 - '@rsbuild/plugin-react@1.4.1(@rsbuild/core@1.5.17)': dependencies: '@rsbuild/core': 1.5.17 @@ -2196,17 +2268,15 @@ snapshots: transitivePeerDependencies: - webpack-hot-middleware - '@rsdoctor/cli@1.3.3-beta.2(@rsbuild/core@1.6.0-beta.0)(@rsdoctor/client@1.3.3-beta.2)(@rspack/core@1.5.8(@swc/helpers@0.5.17))': + '@rsdoctor/cli@1.5.8(@rsdoctor/client@1.5.8)(@rspack/core@1.5.8(@swc/helpers@0.5.17))': dependencies: - '@rsdoctor/client': 1.3.3-beta.2 - '@rsdoctor/core': 1.3.3(@rsbuild/core@1.6.0-beta.0)(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - '@rsdoctor/graph': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - '@rsdoctor/sdk': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - '@rsdoctor/types': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - '@rsdoctor/utils': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + '@rsdoctor/client': 1.5.8 + '@rsdoctor/graph': 1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + '@rsdoctor/sdk': 1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + '@rsdoctor/types': 1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + '@rsdoctor/utils': 1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17)) ora: 5.4.1 transitivePeerDependencies: - - '@rsbuild/core' - '@rspack/core' - bufferutil - supports-color @@ -2215,9 +2285,7 @@ snapshots: '@rsdoctor/client@1.3.1': {} - '@rsdoctor/client@1.3.3': {} - - '@rsdoctor/client@1.3.3-beta.2': {} + '@rsdoctor/client@1.5.8': {} '@rsdoctor/core@1.3.1(@rspack/core@1.5.8(@swc/helpers@0.5.17))': dependencies: @@ -2239,28 +2307,6 @@ snapshots: - utf-8-validate - webpack - '@rsdoctor/core@1.3.3(@rsbuild/core@1.6.0-beta.0)(@rspack/core@1.5.8(@swc/helpers@0.5.17))': - dependencies: - '@rsbuild/plugin-check-syntax': 1.4.0(@rsbuild/core@1.6.0-beta.0) - '@rsdoctor/graph': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - '@rsdoctor/sdk': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - '@rsdoctor/types': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - '@rsdoctor/utils': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - browserslist-load-config: 1.0.1 - enhanced-resolve: 5.12.0 - filesize: 10.1.6 - fs-extra: 11.3.2 - lodash: 4.17.21 - semver: 7.7.3 - source-map: 0.7.6 - transitivePeerDependencies: - - '@rsbuild/core' - - '@rspack/core' - - bufferutil - - supports-color - - utf-8-validate - - webpack - '@rsdoctor/graph@1.3.1(@rspack/core@1.5.8(@swc/helpers@0.5.17))': dependencies: '@rsdoctor/types': 1.3.1(@rspack/core@1.5.8(@swc/helpers@0.5.17)) @@ -2272,11 +2318,11 @@ snapshots: - '@rspack/core' - webpack - '@rsdoctor/graph@1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17))': + '@rsdoctor/graph@1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17))': dependencies: - '@rsdoctor/types': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - '@rsdoctor/utils': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - lodash.unionby: 4.8.0 + '@rsdoctor/types': 1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + '@rsdoctor/utils': 1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + es-toolkit: 1.45.1 path-browserify: 1.0.1 source-map: 0.7.6 transitivePeerDependencies: @@ -2315,15 +2361,16 @@ snapshots: - utf-8-validate - webpack - '@rsdoctor/sdk@1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17))': + '@rsdoctor/sdk@1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17))': dependencies: - '@rsdoctor/client': 1.3.3 - '@rsdoctor/graph': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - '@rsdoctor/types': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) - '@rsdoctor/utils': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + '@rsdoctor/client': 1.5.8 + '@rsdoctor/graph': 1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + '@rsdoctor/types': 1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + '@rsdoctor/utils': 1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + launch-editor: 2.13.2 safer-buffer: 2.1.2 socket.io: 4.8.1 - tapable: 2.2.3 + tapable: 2.3.2 transitivePeerDependencies: - '@rspack/core' - bufferutil @@ -2340,11 +2387,11 @@ snapshots: optionalDependencies: '@rspack/core': 1.5.8(@swc/helpers@0.5.17) - '@rsdoctor/types@1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17))': + '@rsdoctor/types@1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17))': dependencies: '@types/connect': 3.4.38 '@types/estree': 1.0.5 - '@types/tapable': 2.2.7 + '@types/tapable': 2.3.0 source-map: 0.7.6 optionalDependencies: '@rspack/core': 1.5.8(@swc/helpers@0.5.17) @@ -2370,22 +2417,22 @@ snapshots: - '@rspack/core' - webpack - '@rsdoctor/utils@1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17))': + '@rsdoctor/utils@1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17))': dependencies: '@babel/code-frame': 7.26.2 - '@rsdoctor/types': 1.3.3(@rspack/core@1.5.8(@swc/helpers@0.5.17)) + '@rsdoctor/types': 1.5.8(@rspack/core@1.5.8(@swc/helpers@0.5.17)) '@types/estree': 1.0.5 acorn: 8.15.0 acorn-import-attributes: 1.9.5(acorn@8.15.0) - acorn-walk: 8.3.4 + acorn-walk: 8.3.5 deep-eql: 4.1.4 - envinfo: 7.18.0 + envinfo: 7.21.0 fs-extra: 11.3.2 get-port: 5.1.1 json-stream-stringify: 3.0.1 lines-and-columns: 2.0.4 picocolors: 1.1.1 - rslog: 1.3.0 + rslog: 1.3.2 strip-ansi: 6.0.1 transitivePeerDependencies: - '@rspack/core' @@ -2575,6 +2622,8 @@ snapshots: '@socket.io/component-emitter@3.1.2': {} + '@standard-schema/spec@1.1.0': {} + '@swc/helpers@0.5.17': dependencies: tslib: 2.8.1 @@ -2622,6 +2671,10 @@ snapshots: dependencies: tapable: 2.3.0 + '@types/tapable@2.3.0': + dependencies: + tapable: 2.3.0 + '@types/yauzl@2.10.3': dependencies: '@types/node': 24.9.1 @@ -2641,6 +2694,8 @@ snapshots: transitivePeerDependencies: - supports-color + '@vercel/oidc@3.1.0': {} + abort-controller@3.0.0: dependencies: event-target-shim: 5.0.1 @@ -2658,10 +2713,22 @@ snapshots: dependencies: acorn: 8.15.0 + acorn-walk@8.3.5: + dependencies: + acorn: 8.15.0 + acorn@8.15.0: {} agent-base@7.1.4: {} + ai@6.0.159(zod@4.3.6): + dependencies: + '@ai-sdk/gateway': 3.0.96(zod@4.3.6) + '@ai-sdk/provider': 3.0.8 + '@ai-sdk/provider-utils': 4.0.23(zod@4.3.6) + '@opentelemetry/api': 1.9.0 + zod: 4.3.6 + ansi-regex@5.0.1: {} ansi-regex@6.2.2: {} @@ -2711,8 +2778,6 @@ snapshots: base64id@2.0.0: {} - baseline-browser-mapping@2.8.18: {} - before-after-hook@2.2.3: {} binary@0.3.0: @@ -2738,18 +2803,6 @@ snapshots: browserslist-load-config@1.0.1: {} - browserslist-to-es-version@1.2.0: - dependencies: - browserslist: 4.26.3 - - browserslist@4.26.3: - dependencies: - baseline-browser-mapping: 2.8.18 - caniuse-lite: 1.0.30001751 - electron-to-chromium: 1.5.237 - node-releases: 2.0.25 - update-browserslist-db: 1.1.3(browserslist@4.26.3) - buffer-crc32@0.2.13: {} buffer-crc32@1.0.0: {} @@ -2771,8 +2824,6 @@ snapshots: es-errors: 1.3.0 function-bind: 1.1.2 - caniuse-lite@1.0.30001751: {} - chainsaw@0.1.0: dependencies: traverse: 0.3.9 @@ -2856,24 +2907,6 @@ snapshots: deprecation@2.3.1: {} - dom-serializer@2.0.0: - dependencies: - domelementtype: 2.3.0 - domhandler: 5.0.3 - entities: 4.5.0 - - domelementtype@2.3.0: {} - - domhandler@5.0.3: - dependencies: - domelementtype: 2.3.0 - - domutils@3.2.2: - dependencies: - dom-serializer: 2.0.0 - domelementtype: 2.3.0 - domhandler: 5.0.3 - dunder-proto@1.0.1: dependencies: call-bind-apply-helpers: 1.0.2 @@ -2882,8 +2915,6 @@ snapshots: eastasianwidth@0.2.0: {} - electron-to-chromium@1.5.237: {} - emoji-regex@8.0.0: {} emoji-regex@9.2.2: {} @@ -2911,13 +2942,9 @@ snapshots: graceful-fs: 4.2.11 tapable: 2.3.0 - entities@4.5.0: {} - - entities@6.0.1: {} - envinfo@7.14.0: {} - envinfo@7.18.0: {} + envinfo@7.21.0: {} error-stack-parser@2.1.4: dependencies: @@ -2938,7 +2965,7 @@ snapshots: has-tostringtag: 1.0.2 hasown: 2.0.2 - escalade@3.2.0: {} + es-toolkit@1.45.1: {} event-target-shim@5.0.1: {} @@ -2950,6 +2977,8 @@ snapshots: events@3.3.0: {} + eventsource-parser@3.0.6: {} + fast-fifo@1.3.2: {} fast-glob@3.3.3: @@ -3049,13 +3078,6 @@ snapshots: html-entities@2.6.0: {} - htmlparser2@10.0.0: - dependencies: - domelementtype: 2.3.0 - domhandler: 5.0.3 - domutils: 3.2.2 - entities: 6.0.1 - http-proxy-agent@7.0.2: dependencies: agent-base: 7.1.4 @@ -3106,6 +3128,8 @@ snapshots: js-tokens@4.0.0: {} + json-schema@0.4.0: {} + json-stream-stringify@3.0.1: {} json-stringify-safe@5.0.1: {} @@ -3118,6 +3142,11 @@ snapshots: jwt-decode@3.1.2: {} + launch-editor@2.13.2: + dependencies: + picocolors: 1.1.1 + shell-quote: 1.8.3 + lazystream@1.0.1: dependencies: readable-stream: 2.3.8 @@ -3188,8 +3217,6 @@ snapshots: dependencies: whatwg-url: 5.0.0 - node-releases@2.0.25: {} - normalize-path@3.0.0: {} object-assign@4.1.1: {} @@ -3300,6 +3327,8 @@ snapshots: rslog@1.3.0: {} + rslog@1.3.2: {} + run-parallel@1.2.0: dependencies: queue-microtask: 1.2.3 @@ -3320,6 +3349,8 @@ snapshots: shebang-regex@3.0.0: {} + shell-quote@1.8.3: {} + signal-exit@3.0.7: {} signal-exit@4.1.0: {} @@ -3405,6 +3436,8 @@ snapshots: tapable@2.3.0: {} + tapable@2.3.2: {} + tar-stream@3.1.7: dependencies: b4a: 1.7.3 @@ -3457,12 +3490,6 @@ snapshots: binary: 0.3.0 mkdirp: 0.5.6 - update-browserslist-db@1.1.3(browserslist@4.26.3): - dependencies: - browserslist: 4.26.3 - escalade: 3.2.0 - picocolors: 1.1.1 - util-deprecate@1.0.2: {} vary@1.1.2: {} @@ -3508,3 +3535,5 @@ snapshots: archiver-utils: 5.0.2 compress-commons: 6.0.2 readable-stream: 4.7.0 + + zod@4.3.6: {} diff --git a/rslib.config.ts b/rslib.config.mts similarity index 100% rename from rslib.config.ts rename to rslib.config.mts diff --git a/src/ai-analysis.ts b/src/ai-analysis.ts new file mode 100644 index 0000000..a28190b --- /dev/null +++ b/src/ai-analysis.ts @@ -0,0 +1,96 @@ +import * as fs from 'fs'; +import { generateText, type LanguageModel } from 'ai'; +import { createAnthropic } from '@ai-sdk/anthropic'; +import { createDeepSeek } from '@ai-sdk/deepseek'; +import { createGoogleGenerativeAI } from '@ai-sdk/google'; +import { createOpenAI } from '@ai-sdk/openai'; +import { buildPrompt } from './prompt'; + +export interface AIAnalysisResult { + analysis: string; + provider: string; + model: string; +} + +type Provider = 'anthropic' | 'openai' | 'google' | 'deepseek' | 'qwen'; + +function detectProvider(model: string): Provider { + const m = model.toLowerCase(); + if (m.startsWith('claude')) return 'anthropic'; + if (m.startsWith('gemini')) return 'google'; + if (m.startsWith('deepseek')) return 'deepseek'; + if (m.startsWith('qwen')) return 'qwen'; + return 'openai'; +} + +function createModel(provider: Provider, model: string, token: string): LanguageModel { + switch (provider) { + case 'anthropic': { + const anthropic = createAnthropic({ apiKey: token }); + return anthropic(model); + } + case 'google': { + const google = createGoogleGenerativeAI({ apiKey: token }); + return google(model); + } + case 'deepseek': { + const deepseek = createDeepSeek({ apiKey: token }); + return deepseek(model); + } + case 'qwen': { + const qwen = createOpenAI({ + apiKey: token, + baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1', + }); + return qwen(model); + } + default: { + const openai = createOpenAI({ apiKey: token }); + return openai(model); + } + } +} + +/** + * Run AI degradation analysis on a bundle-diff JSON file. + * + * @param diffJsonPath Path to the JSON file produced by `rsdoctor bundle-diff --json` + * @param token AI API key (Anthropic or OpenAI) + * @param model Model name — auto-detects provider from prefix (default: claude-3-5-haiku-latest) + */ +export async function analyzeWithAI( + diffJsonPath: string, + token: string, + model = 'claude-3-5-haiku-latest', +): Promise { + if (!token) { + console.log('ā„¹ļø No AI token provided, skipping AI analysis'); + return null; + } + + if (!fs.existsSync(diffJsonPath)) { + console.log(`āš ļø Bundle diff JSON not found at ${diffJsonPath}, skipping AI analysis`); + return null; + } + + try { + const diffData: unknown = JSON.parse(fs.readFileSync(diffJsonPath, 'utf8')); + const prompt = buildPrompt(diffData); + const provider = detectProvider(model); + + console.log(`šŸ¤– Running AI analysis with ${provider} (${model})...`); + + const llm = createModel(provider, model, token); + const { text: analysis } = await generateText({ + model: llm, + maxOutputTokens: 2048, + prompt, + }); + + console.log('āœ… AI analysis completed'); + return { analysis, provider, model }; + } catch (error) { + console.warn(`āš ļø AI analysis failed: ${error}`); + return null; + } +} diff --git a/src/index.ts b/src/index.ts index 1ab637d..0ea1f3f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,7 @@ import { uploadArtifact, hashPath } from './upload'; import { downloadArtifactByCommitHash } from './download'; import { GitHubService } from './github'; import { loadSizeData, generateSizeReport, parseRsdoctorData, generateBundleAnalysisReport, BundleAnalysis, generateProjectMarkdown, formatBytes, calculateDiff } from './report'; +import { analyzeWithAI, AIAnalysisResult } from './ai-analysis'; import path from 'path'; import * as fs from 'fs'; import { execFile } from 'child_process'; @@ -99,6 +100,7 @@ interface ProjectReport { diffHtmlArtifactId?: number; baselineUsedFallback?: boolean; baselineLatestCommitHash?: string; + aiAnalysis?: AIAnalysisResult | null; } export function extractProjectName(filePath: string): string { @@ -152,6 +154,8 @@ async function processSingleFile( targetCommitHash: string | null, baselineUsedFallback?: boolean, baselineLatestCommitHash?: string, + aiToken?: string, + aiModel?: string, ): Promise { const fileName = path.basename(fullPath); const relativePath = path.relative(process.cwd(), fullPath); @@ -273,11 +277,49 @@ async function processSingleFile( console.warn(`āš ļø Failed to upload diff html for ${projectName}: ${e}`); } } + + // Generate JSON diff for AI analysis (requires @rsdoctor/cli >= 1.5.6-canary.0) + if (aiToken) { + try { + const diffJsonPath = path.join(tempOutDir, `rsdoctor-diff-${projectName}.json`); + const defaultDiffJsonPath = path.join(tempOutDir, 'rsdoctor-diff.json'); + + try { + const cliEntry = require.resolve('@rsdoctor/cli', { paths: [process.cwd()] }); + const binCliEntry = path.join(path.dirname(path.dirname(cliEntry)), 'bin', 'rsdoctor'); + runRsdoctorViaNode(binCliEntry, [ + 'bundle-diff', + '--json', + `--baseline=${baselineJsonPath}`, + `--current=${fullPath}`, + ]); + } catch (e) { + console.log(`āš ļø rsdoctor CLI (json) not found in node_modules: ${e}`); + try { + const shellCmd = `npx @rsdoctor/cli bundle-diff --json --baseline="${baselineJsonPath}" --current="${fullPath}"`; + console.log(`šŸ› ļø Running rsdoctor --json via npx: ${shellCmd}`); + await execFileAsync('sh', ['-c', shellCmd], { cwd: tempOutDir }); + } catch (npxError) { + console.log(`āš ļø npx approach (json) also failed: ${npxError}`); + } + } + + // Rename default output to project-specific name to avoid collisions in monorepo + if (fs.existsSync(defaultDiffJsonPath) && !fs.existsSync(diffJsonPath)) { + await fs.promises.rename(defaultDiffJsonPath, diffJsonPath); + } + + const resolvedJsonPath = fs.existsSync(diffJsonPath) ? diffJsonPath : defaultDiffJsonPath; + report.aiAnalysis = await analyzeWithAI(resolvedJsonPath, aiToken, aiModel); + } catch (e) { + console.warn(`āš ļø Failed to generate JSON diff for AI analysis: ${e}`); + } + } } catch (e) { console.warn(`āš ļø rsdoctor bundle-diff failed for ${projectName}: ${e}`); } } - + return report; } @@ -307,7 +349,13 @@ async function processSingleFile( const currentCommitHash = githubService.getCurrentCommitHash(); console.log(`Current commit hash: ${currentCommitHash}`); - + + const aiToken = process.env.AI_TOKEN || ''; + const aiModel = getInput('ai_model') || 'claude-3-5-haiku-latest'; + if (aiToken) { + console.log(`šŸ¤– AI analysis enabled (model: ${aiModel})`); + } + let targetCommitHash: string | null = null; let baselineUsedFallback = false; let baselineLatestCommitHash: string | undefined = undefined; @@ -399,7 +447,7 @@ async function processSingleFile( } for (const fullPath of matchedFiles) { - const report = await processSingleFile(fullPath, currentCommitHash, targetCommitHash, baselineUsedFallback, baselineLatestCommitHash); + const report = await processSingleFile(fullPath, currentCommitHash, targetCommitHash, baselineUsedFallback, baselineLatestCommitHash, aiToken, aiModel); projectReports.push(report); // For workflow_dispatch, also upload artifacts @@ -562,6 +610,21 @@ async function processSingleFile( } } + // Append AI degradation analysis if available (one section per project that has it) + const reportsWithAI = projectReports.filter(r => r.aiAnalysis); + if (reportsWithAI.length > 0) { + commentBody += '
\nšŸ¤– AI Degradation Analysis (Click to expand)\n\n'; + for (const report of reportsWithAI) { + if (!report.aiAnalysis) continue; + if (reportsWithAI.length > 1) { + commentBody += `#### šŸ“ ${report.projectName}\n\n`; + } + commentBody += report.aiAnalysis.analysis + '\n\n'; + commentBody += `Analysis by ${report.aiAnalysis.model}\n\n`; + } + commentBody += '
\n\n'; + } + commentBody += '*Generated by [Rsdoctor GitHub Action](https://rsdoctor.rs/guide/start/action)*'; try { diff --git a/src/prompt.ts b/src/prompt.ts new file mode 100644 index 0000000..3617d8b --- /dev/null +++ b/src/prompt.ts @@ -0,0 +1,45 @@ +const MAX_CHARS = 50000; + +export function buildPrompt(diffData: unknown): string { + // Truncate large diff data to avoid token limits (~50k chars) + let diffStr = JSON.stringify(diffData, null, 2); + if (diffStr.length > MAX_CHARS) { + diffStr = diffStr.substring(0, MAX_CHARS) + '\n... (truncated due to size)'; + } + + return `You are a senior frontend performance engineer. Analyze the Rsdoctor bundle-diff JSON below (baseline → current) and produce a concise GitHub PR comment in Markdown. + +## Output format + +### šŸ“Š Size Changes + +| Asset / Chunk | Baseline | Current | Ī” Size | Ī” % | Initial? | +|---|---|---|---|---|---| + +(Only list entries with **>5 % or >10 KB** increase. If none, write "No significant regressions detected šŸŽ‰".) + +### šŸ” Root Cause Analysis +- Bullet points: which modules / dependencies drove each regression. + +### āš ļø Risk Assessment +Overall severity: **Low / Medium / High** +- One-sentence justification focusing on initial-chunk impact and total size delta. + +### šŸ’” Optimization Suggestions +- Numbered, actionable steps (e.g. code-split, tree-shake, replace heavy deps). + +## Priority rules +1. Initial / entry chunks > async chunks > static assets. +2. Newly added large modules or duplicate dependencies deserve explicit callout. +3. If total bundle size *decreased*, highlight the wins instead. + +## Constraints +- Be concise — aim for <400 words. +- Use exact numbers from the data; do not fabricate figures. +- If the diff data is empty or shows no meaningful change, state that clearly and skip the table. + +Bundle diff data: +\`\`\`json +${diffStr} +\`\`\``; +}